1
votes

I've this assignment in Python 3 where I get a list of numbers and using at least a for loop I need to find the min, max, sum, and average of the numbers. But the tricky part is that I can only use the len() function, no while loops, def/return, max/min, just len() and for loops, can do if/else statements tho. So please let's say this is the list.

numbers=[1,35,54,99,67,2,9]
biggest= numbers[0]
smallest=numbers[0]
for bigs in range(1,len(numbers)):
    if numbers[bigs] > biggest:
        biggest = numbers [bigs]
print("The max number is", biggest)

for smalls in range(1,len(numbers)):
    if numbers[smalls] < smallest:
        smallest = numbers [smalls]
print("The min number is", smallest)

That's what I have for max and min and it does work, a bit messy but it works, but I've no clue how to do sum and average. How could I do all that using only for loops and len()? Thanks!

1
What have you tried so far? Hint: use comparison operators <, >, +, / ... - jpp
You are already accessing every element of your list when you say "for bigs in range..." and "number[bigs] = ...." All you need to do is add this element to a "sum" variable that you initialize to 0 before the for loop. Then you divide that by len() to get the average. - hikerjobs
I can't use sum - Jonathan
You don't need to use sum. When I said 'sum' it is just a variable name. Call it 'Hello' if you want :-) hello = 0 and then keep adding the rest to this: hello = hello + numbers[big] ... At the end of this, you will have the sum in the hello variable. - hikerjobs
I'm not sure how to do what you are saying - Jonathan

1 Answers

3
votes

If you are allowed to store values you could do something like:

smallest = numbers[0]
biggest = numbers[0]
total = 0

for num in numbers:
    if num < smallest:
        smallest = num
    elif num > biggest:
        biggest = num
    total += num

average = total / len(numbers)