Calculation of median with even number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bferguson94
    New Member
    • Feb 2010
    • 11

    #1

    Calculation of median with even number

    Code:
    def main():
        myList=[]
        choice = 0
        while choice !='4':
            choice= raw_input('1.add number to list\n2.get mean \n3.get median \n4.quit')
            if choice == '1':
                addNum(myList)
            if choice == '2':
                getMean(myList)
            if choice == '3':
                getMedian(myList)
            if int(choice) < 0:
                print "invalid input"
            if int(choice) > 4:
                print "invalid input"
    ##break
    ##input error messages
    def addNum(myList):
        while True:
            num = raw_input("input new number:")
            try:
                num = int(num)
                if num < 0:
                    raise ValueError
                break
            except:
                print"invalid input"
            
            
        myList.append(num)
    
    def getMean(myList):
        total = 0.0
        for value in myList:
            total = total  + value
        mean = total/len(myList)
        print "the mean is:" , mean
    
    def getMedian (myList):
        index= 2
        if len(myList)%2 == 0:
            myMed = (myList[index] + myList[myMed-1])/2
        else:
            myList[len(myList)/2]
        print myMed
    Attached Files
    Last edited by bvdet; Feb 27 '10, 12:13 AM. Reason: Add code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Please use code tags when posting code. See Posting Guidelines here.

    By definition, the median of a sorted list of numbers is the average of the pair of middle numbers. If the modulo of len(myList) and 2 == 0, take the middle pair and divide by 2. If the modulo of len(myList) and 2 == 1, the median is the middle number. Example using integer division:
    Code:
    >>> def median(s):
    ... 	i = len(s)
    ... 	if not i%2:
    ... 		return (s[(i/2)-1]+s[i/2])/2.0
    ... 	return s[i/2]
    ... 
    >>> median([1,2,3,4,5,6,7,8,9,10])
    5.5
    >>> median([1,2,3,4,5,6,7,8,9])
    5
    >>>

    Comment

    • bferguson94
      New Member
      • Feb 2010
      • 11

      #3
      thanks for the advice, but seems as if the median wont print now..any suggestions
      Code:
      ###
      ###
      ##menu reads four options to user
      ##includes: creating a list, mode, median and quit
      ##this program needs to except positive integers
      ##it also needs to inform the user of any errors or invalid input
      ##so far this program seems to work
      ##but the arithometic for median seems off
      ##
      ##
      ##
      def main():
          myList=[]
          choice = 0
          while choice !='4':
              choice= raw_input('1.add number to list\n2.get mean \n3.get median \n4.quit')
              if choice == '1':
                  addNum(myList)
              if choice == '2':
                  getMean(myList)
              if choice == '3':
                  getMedian(myList)
              if int(choice) < 0:
                  print "invalid input"
              if int(choice) > 4:
                  print "invalid input"
      
      def addNum(myList):
          while True:
              num = raw_input("input new number:")
              try:
                  num = int(num)
                  if num < 0:
                      raise ValueError
                  break
              except:
                  print"invalid input"
              
              
          myList.append(num)
      
      def getMean(myList):
          total = 0.0
          for value in myList:
              total = total  + value
          mean = total/len(myList)
          print "the mean is:", mean
      
      def getMedian (myList):
          i = len(myList)
          if not i%2:
              return (myList[(i/2)-1]+myList[i/2])/2.0-1
          else:
              myList[len(myList)/2]
          print "the median is:", i
      ##        
      ## for some reason the median wont print
      ## do i need to create another module for median?
      ##       
         
              
      ##
      ##PREVIOUS MODULE##
      ##
      ##    mid = 2
      ##    prev = mid-1 
      ##    if len(myList)%2 == 0:
      ####        mid = 2
      ####        prev = mid-1
      ##        myMed=(myList[mid]+myList[prev])/2
      ##        print myMed
      ####    else myMed = [len(myList)/2]:
      ##        
      main()

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        In general, it's a good idea to design your functions to accept arguments, return the results, and let your application handle displaying the results to the user. In your revised function, you are returning the result if not i%2. Otherwise i is printed which is nothing but the length of myList. It should look something like this:
        Code:
        def median(s):
            i = len(s)
            if not i%2:
                return (s[(i/2)-1]+s[i/2])/2.0
            return s[i/2]
        
        result = median(myList)
        print result
        In the example, the argument s represents a list and i represents the length of s. The function then determines the median and returns the answer. The returned answer is assigned to the identifier result. Then result is printed to stdout.

        The example uses the indexing operator.
        Code:
        >>> s = ['a','b','c','d']
        >>> s[1]
        'b'
        >>> s[2]
        'c'
        >>> s[-1]
        'd'
        >>>
        Do you understand what that is?

        If you really want the median printed inside your function, substitute print for return.

        Comment

        • bferguson94
          New Member
          • Feb 2010
          • 11

          #5
          I got the program to work. Thanks!! I'm not sure what an index operator is, if you have the time could you explain it to me?

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            Individual elements of strings, lists and tuples can be accessed by index using the form [I]sequence. Of those data types, only lists are mutable. Elements of lists can also be assigned by index. Note that indexing starts with 0. Examples:
            Code:
            >>> "a string"[0]
            'a'
            >>> list("a string")
            ['a', ' ', 's', 't', 'r', 'i', 'n', 'g']
            >>> list("a string")[0]
            'a'
            >>> tuple("a string")
            ('a', ' ', 's', 't', 'r', 'i', 'n', 'g')
            >>> tuple("a string")[0]
            'a'
            >>> myList = list("a string")
            >>> myList[0]='b'
            >>> myList
            ['b', ' ', 's', 't', 'r', 'i', 'n', 'g']
            >>>
            Portions of sequence types can be extracted using the slicing operator. Portions of lists can be assigned also. Example:
            Code:
            >>> myList[0:2] = ['c', 'd', 'e']
            >>> myList
            ['c', 'd', 'e', 's', 't', 'r', 'i', 'n', 'g']
            >>>
            HTH,
            BV

            Comment

            Working...