'How to make code which overwrites smaller answers with a bigger one?
I have the following code:
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128 ():
for num in my_list:
val = num
ans = val*128
highest = (ans)
if ans > highest:
highest = ans
return(highest)
print(multiplied128())
I need to have code where if the answer is greater than the answer already stored in highest, it is overwritten. With the final return being just the highest result, in this case it would be the 11th result.
Solution 1:[1]
You need a few things:
- Make sure to move the
highestvariable outside the loop. If not, it would be replaced each time the loop runs, and you never find out what is the highest value in your list. - And the second, which might not be completely necessary in your case, but it might be helpful, is to use
float("-inf")as the first assigning value to thehighestvariable. This makes sure that you have not ignored any element in your list (there might have been negative values in the list, too) - Make sure that
returnis out of theforloop and at the end of the function.
Here is what I have come up with:
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128 ():
highest = float("-inf")
for num in my_list:
val = num # This is not necessary. You can simply replace `num` with `val` in the for loop itself.
ans = val*128
if ans > highest:
highest = ans
return(highest)
print(multiplied128())
Output
10240
The output is as it should be: The highest value in your list is 80. Mutliplying this number by 128 results in 10240.
Solution 2:[2]
To find the highest number you should create a variable to store the highest result so far and compare to it every new result.
Here I defined the variable highest before the loop and set its value to 0
I'm not sure why you're doing the multiply by 128 but I left it there for you.
my_list = [1, 3, 5, 6, 10, 40, 2, 3, 9, 80, 23, 22]
def multiplied128():
highest = 0
for num in my_list:
ans = num*128
if ans > highest:
highest = ans
return highest
print(multiplied128())
BTW, the same result can be achieved with the built-in function max:
print(128*max(my_list))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
