Python 无效的文字排序程序



我收到"ValueError:int()的无效文字,基数为10:"错误。我的规格:

  1. 程序必须生成整数的随机列表,这些整数的长度和值范围将在运行时指定。
  2. 您必须显示未排序的列表。
  3. 您必须显示该列表包含用户指定的条目数。
  4. 必须编写并演示代码以证明列表中的所有值都在用户指定的范围内。
  5. 您必须使用自己的插入排序实现才能创建一个列表,该列表按升序包含原始列表中的所有项目。
  6. 在生成列表时,必须显示排序列表的元素。
  7. 必须显示排序列表。

我的代码

import random
length = input("Input the length of the random list: ")
temp = input("Input the range of values for the random list (0-n)")
def gen_list(L, T):
    LIST = []
    ranlower = T[0:T.index('-')]
    ranhigher = T[T.index('-')+1:len(T)]
    for num in range(L):
        x = random.randint(int(ranlower),int(ranhigher))
        LIST.append(x)
    tempmax = ranlower
    tempmin = ranhigher
    for i in range (L):
        for t in range (L):
            if LIST[t] > tempmax:
                tempmax = LIST[t]
            if LIST[t] < tempmin:
                tempmin = LIST[t]
    print("Unsorted List: ", LIST)
    print("The largest value in the list was: ", tempmax, " with upper bound at ", ranhigher, ".")
    print("The smallest value in the list was: ", tempmin, " with lower bound at ", ranlower, ".")
    print("The random unsorted list has ", L, " items.")
    sort_numbers(LIST)
def sort_numbers(s):
    for i in range(1, len(s)):
        # let's see what values i takes on
        print ("i = ", i)
        val = s[i]
        j = i - 1
        while (j >= 0) and (s[j] > val):
            s[j+1] = s[j]
            j = j - 1
            print (s)
        s[j+1] = val
    print(s)
gen_list(length, temp)

这是完整的回溯:

Input the length of the random list: 10
Input the range of values for the random list (0-n)
10-15
Traceback (most recent call last):
  File "/private/var/folders/8_/7j1ywj_93vz2626l_f082s9c0000gn/T/Cleanup At Startup/Program 1-437933490.889.py", line 42, in <module>
    gen_list(length, temp)
  File "/private/var/folders/8_/7j1ywj_93vz2626l_f082s9c0000gn/T/Cleanup At Startup/Program 1-437933490.889.py", line 13, in gen_list
    x = random.randint(int(ranlower),int(ranhigher))
ValueError: invalid literal for int() with base 10: ''

从错误消息中可以看出,您正在尝试在空字符串 ( '' ) 上调用 int() )。

由于产生错误的行包含对int()的两个调用,这意味着ranlowerranhigher都是空字符串。找出原因(print陈述在那里很有帮助),你的问题就会得到解决。

最新更新