下面的代码用于获取数组中一组学生的分数,并需要找到分数最高的那一行。
下面是不完整的代码,因为仍然需要搜索最大和行;但由于错误而停留在不完整的代码上。
在py3.codeskulptor.org/中出现以下错误,而在Pythontutor中,程序在相同的行号处终止。
第17行:IndexError:列表分配索引超出范围
# Input number of tests
t = int(input("Input number of tests"))
# Input size of rows (of students)
n = int(input("Input size of rows"))#.strip().split())
print (t,n)
arr = [[[] for i in range(t)] for i in range(n)]
total = [[] for i in range (n)]
for i in range(0,t):
# Input score of each student in row
sum =0
for j in range(n):
arr[i][j] = map(int, input("Input score").strip().split())#[:n]
#the above line causes compilation error
# Find sum of all scores row-wise
for m in arr[i][j]:
sum += m
total[i] = sum1
# Find the max. of total
for j in range(t):
y = max(total[j])
也请提出一种更清晰的方法来编程上述问题。
P.S。我发现上面的代码几乎是错误的,但是将我踢向正确的方向。
在下面的修改后的代码中出现一个与调试有关的问题:
max()在[]之前优先于整数值
当错误地将第13行声明为:
total = [[[]对于范围(l)的i]对于范围(n)的i]]
# Input number of tests
t = int(input("Input number of tests"))
# Input number of rows (of students)
n = int(input("Input number of rows"))#.strip().split())
# Input limit on number of students in a row (of students)
l = int(input("Input max. number of studentsin any row"))#.strip().split())
print ('t :',t,'n :',n, 'l :', l)
arr = [[[[] for i in range(l)] for i in range(n)] for i in range(t)]
total = [[[] for i in range (n)] for i in range (t)]
# run input of tests
for i in range(t):
# Input score of each student in the i-th row, out of n
sum =0
for j in range(n):
#for k in range(l):
print("jkl:","i:",i,"j:",j)
arr[i][j] = map(int, input("Input score").strip().split())[:l]
for i in range(t):
for j in range(n):
# Find sum of all scores row-wise
sum = 0
for m in arr[i][j]:
#sum[i][j][] += m
print ('m :', m)
sum += m
#total[i][j] = sum[i][j][]
total[i][j] = sum
for i in range(t):
print("Test no. ", i)
for j in range(n):
#for m in arr[i][j]:
print (arr[i][j])
#print (m)
print("=========")
for i in range(t):
for j in range(n):
print(i,"-",j, total[i][j])
print("::::::")
print("=========")
# Find the max. of total
for i in range(t):
print([m for m in total[i]])
y = max([m for m in total[i]])
print ('i:',i,',', 'max total:',y)
请求由max()显示的优先级的原因,并尽可能将答案与对CPython中基础实现的一些引用联系起来。
答案 0 :(得分:1)
arr = [[[] for i in range(t)] for i in range(n)]
考虑到arr
的上述构造,您已在嵌套循环中交换了t
和n
:
for i in range(t): # … for j in range(n): arr[i][j] = …
arr
中的第一个索引(对应于 outer 循环)必须是0到 n –1之间的数字。
arr
中的第二个索引(对应于 inner 循环)必须是0到 t –1之间的数字。
答案 1 :(得分:1)
您在t和n之间犯了一个错误
我应该在range(n)
并且j应该在range(t)