Reputation: 143
I'm new here. I'm trying to answer to the following problem.
My problem is with the question (c)
v=[...]
maxx=v[0]
for i in range(0,len(v)-1):
if maxx<v[i]:
maxx=v[i]
print(maxx)
i know this algorithm would resolve my problem.However i would like to understand what is wrong with my max function
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))
Upvotes: 0
Views: 194
Reputation: 10789
There are several ways you can improve your implementation including using enumerate
to loop over list indices and items and using miningful name variables.
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
Upvotes: 0
Reputation: 2298
The way you have your maxx
function set up you will only ever have the last or second last element of a list be the max. Instead of comparing to v[i]
you need to compare to your current max:
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
Upvotes: 4