I'm looking to get the maximum absolute value in a random list. I need to create it in a function. I'm not sure what I'm doing wrong here. I have a for loop setup so it should check each number but it's only returning the first value.
def main():
print(maxabsinlst([-19, -3, 20, -1, 5, -25]))
def maxabsinlst(num):
for x in (num):
max_abs_value = num[5]
if abs(x) > max_abs_value:
max_abs_value = abs(x)
return max(abs(max_abs_value))
main()
The shortest way would be:
def maxabsinlst(num):
return max(map(abs, num))
The map()
function applies abs()
to each number on the list, and returns a list of these absolute values, then max()
finds the maximum in the list.
You are assigning max_abs_value
to num[5]
inside the loop. Instead assign it as first element of list then loop through it comparing with other elements
def main():
print(maxabsinlst([-19, -3, 20, -1, 5, -25]))
def maxabsinlst(num):
max_abs_value = abs(num[0])
for x in num[1:]:
if abs(x) > max_abs_value:
max_abs_value = abs(x)
return max_abs_value
main()
OR
In [36]: max(abs(i) for i in [-19, -3, 20, -1, 5, -25])
Out[36]: 25
You can make this quite a bit more concise:
def max_abs_in_lst(num):
num = [abs(i) for i in num]
return max(num)
max_abs_value = num[5]
Every time the for loop runs, it is setting the max value to -25. Store the value outside the for loop and initialize it with max_abs_value = 0
There are a few issues with your function. First, you're setting max_abs_value
at every iteration of the for
loop. Second, you're assuming that the list passed to the function will have length 6 every time. Third, you never computed the absolute value of num[5]
. So, you're comparing abs(x)
to a negative number. Fourth, you're returning from the function as soon as you find any value greater than max_abs_value
. You have no guarantee that it was the the greatest value in the list.
What you want is
def maxabsinlist(num):
max_abs_value=abs(num[0])
for x in num[1:]:
value=abs(x)
if value > max_abs_value:
max_abs_value=value
return max_abs_value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.