我是编程的初学者,我正在尝试创建一个程序,在不使用“max”函数的情况下找到1000个随机数列表中的最大数字,然后找到列表中最大的数字位置,不使用“索引”功能(我设置0-10的数字,以便我可以确保程序正常工作)。我的程序到目前为止工作,有点。有时,它会显示位置,当它显示时,它将显示错误的位置,有时,它将显示一个错误,指出索引超出范围。有人可以帮忙吗?
import random
num_list = []
for num in range(10):
num_list.append(random.randrange(0,11))
max_num = -1
for num in num_list:
if num > max_num:
max_num = num
location=num_list[max_num]
print "The computer entered: " + str(num_list)
print "The largest number in this list is: " + str(max_num) + " The location is: " + str(location)
答案 0 :(得分:1)
编辑以反映@JonClements的反馈
max_num = -1
for (i, num) in enumerate(num_list):
if num > max_num:
location = i
max_num = num
答案 1 :(得分:0)
问题是num_list[max_num]
正在作为索引访问最大值..因此,例如在[1 10 2]
中,您要求列表中的第10个值!尝试更改为:
import random
num_list = []
n = 1000
for num in range(n):
num_list.append(random.randrange(0,n))
max_num = -1
i = 0
for num in num_list:
if num > max_num:
max_num = num
location=i
i += 1
print "The computer entered: " + str(num_list)
print "The largest number in this list is: " + str(max_num) + " The location is: " + str(location)
答案 2 :(得分:0)
使用enumerate
:
import random
num_list = []
for num in range(10):
num_list.append(random.randrange(0,11))
max_num = -1
location = -1
for index, num in enumerate(num_list): # <-- Use enumerate
if num > max_num:
max_num = num
location=index # <-- Store the index for the largest number we found until now
print "The computer entered: " + str(num_list)
print "The largest number in this list is: " + str(max_num) + " The location is: " + str(location)