Python无效的文本排序程序

2024-04-26 11:35:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了“ValueError:invalid literal for int()with base 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: ''

Tags: thein列表forinputwithrangerandom
1条回答
网友
1楼 · 发布于 2024-04-26 11:35:14

从错误消息中可以看到,您试图调用空字符串('')上的int()。你知道吗

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

相关问题 更多 >