我是新来的。我正在尝试回答以下问题。
我的问题是问题(c)
v=[...]
maxx=v[0]
for i in range(0,len(v)-1):
if maxx<v[i]:
maxx=v[i]
print(maxx)
我知道此算法可以解决我的问题。但是,我想了解我的max函数出了什么问题
import random
v=[]
sum=0
avg=0
maxx=0
minn=0
def generate(v):
for i in range(0,20):
x=random.randint(1,100)
v.append(x)
return v
print(generate(v))
def soma(sum):
for k in range(0,len(v)):
sum=sum+v[k]
return sum
def average(avg):
avg=soma(sum)/20
return avg
print(average(avg))
def maxx(maxx):
maxx=v[0]
for i in range(0,len(v)-1):
if v[i+1]>v[i]:
maxx=v[i+1]
else:
maxx=v[i]
return maxx
print(maxx(maxx))
I expect the function to generate the maximum number in the list and not the last number as it is happening.
import random
v=[]
sum=0
avg=0
maxx=0
minn=0
def generate(v):
for i in range(0,20):
x=random.randint(1,100)
v.append(x)
return v
print(generate(v))
def soma(sum):
for k in range(0,len(v)):
sum=sum+v[k]
return sum
def average(avg):
avg=soma(sum)/20
return avg
print(average(avg))
def maxx(maxx):
maxx=v[0]
for i in range(0,len(v)-1):
if v[i+1]>v[i]:
maxx=v[i+1]
else:
maxx=v[i]
return maxx
print(maxx(maxx))
答案 0 :(得分:4)
设置maxx
函数的方式只会使列表的倒数第二个元素为最大值。无需与v[i]
进行比较,您需要与当前的最大值进行比较:
def maxx(maxx):
maxx=v[0]
for i in range(0,len(v)-1):
if v[i+1]>maxx:
maxx=v[i+1]
return maxx
答案 1 :(得分:0)
有几种方法可以改善实现,包括使用enumerate
遍历列表索引和项目以及使用可挖掘的名称变量。
def maxx(_list):
_max = -float("inf")
for n in _list:
# use for i,n in enumerate(_list): if you need i
if n > _max:
_max = n
return _max