Python Forum

Full Version: Help with Code!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi I am trying to calculate the median, or average for the list "numbers", excluding the negative numbers in this list. My question is how do I iteratively sum up all my numbers in a list, without the use of the special function sum(), so I can calculate the average number in this list?

Note: I am NOT allow to use special functions like sort(0, sum(0, or median().

Here is my code so far:

def test() : # do not change this or the next line!
  numbers = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]
  average = 0
  length_numbers = len(numbers)-1
  is_sorted = False
  if is_sorted == False:
    for i in numbers:
      for j in range(0, length_numbers):
       if numbers[j] > numbers[j + 1]:
         temp = numbers[j]
         numbers[j] = numbers[j + 1]
         numbers[j + 1] = temp      #This is the Bubble Sort so I can list the values from least to greatest.
         
         for j in range(numbers >=0, length_numbers):
             sum = sum + numbers[j] #Is this correct for summing the numbers iteratively?
         

         print(average)
         return average 

test()
There might be a misunderstanding how the median is calculated.
The median of a set of data values
Sorry for the typo, I meant mean*. Not median.
Calculating the sum is correct, but the for statement above that will not do what you want, and you are not counting the items to be able to calculate a mean.
(Nov-14-2019, 04:26 AM)Than999 Wrote: [ -> ]My question is how do I iteratively sum up all my numbers in a list, without the use of the special function sum()

Just iterate over items in list and add to total (sum means adding all items; do you want sum only positive values?):

>>> nums = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]         
>>> total = 0                                                                              
>>> for num in nums: 
...    total += num 
...                                                                                        
>>> total                                                                                  
258.8
NB! Never use sum as variable name. You overwrite built-in function and it will come and 'bite you when you least expect'

EDIT: for only positive numbers value checking must be added:

>>> nums = [11.5, 28.3, 23.5, -4.8, 15.9, -63.1, 79.4, 80.0, 0, 67.4, -11.9, 32.6]         
>>> total = 0                                                                              
>>> for num in nums:
...     if 0 <= num:     
...         total += num 
...                                                                                        
>>> total
338.6