NOOB coding help....

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Igorati

    #1

    NOOB coding help....

    Ok, this is what I have so far:

    #This program will ask for a user to imput numbers. The numbers will then
    be calculated
    #to find the statistical mean, mode, and median. Finallly the user will be
    asked
    #if he would like to print out the answers.
    list = [ ]
    a = 1
    print 'Enter numbers to add to the list. (Enter 0 to quit.)'
    while a != 0 :
    a = input('Number? ')
    list.append(a)
    zero = list.index(0)
    del list[zero]
    list.sort()

    variableMean = lambda x:sum(x)/len(x)
    variableMedian = lambda x: x.sort() or x[len(x)//2]
    variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
    s = variableMean(li st)
    y = variableMedian( list)
    t = variableMode (list)

    x = (s,y,t)
    inp = open ("Wade_Stoddard SLP3-2.py", "r")
    outp = open ("avg.py", "w")
    f = ("avg.py")
    for x in inp:
    outp.write(x)
    import pickle
    pickle.dump(x, f)


    print 'Thank you! Would you like to see the results after calculating'
    print 'The mode, median, and mean? (Please enter Yes or No)'
    raw_input('Plea se enter Yes or No:')
    if raw_input == Yes:

    f = open("avg.py"," r")
    avg.py = f.read()
    print 'The Mean average is:', mean
    print 'The Median is:', meadian
    print 'The Mode is:', mode

    I am attempting to make it so that I can save the mean, meadian, and mode
    and then if the user wants the data to give it to him. Thank you for any
    assistance you can provide!

    Wade

  • James Stroud

    #2
    Re: NOOB coding help....

    Could you phrase this in the form of a question, like Jeopardy?


    On Monday 21 February 2005 08:08 pm, Igorati wrote:[color=blue]
    > Ok, this is what I have so far:
    >
    > #This program will ask for a user to imput numbers. The numbers will then
    > be calculated
    > #to find the statistical mean, mode, and median. Finallly the user will be
    > asked
    > #if he would like to print out the answers.
    > list = [ ]
    > a = 1
    > print 'Enter numbers to add to the list. (Enter 0 to quit.)'
    > while a != 0 :
    > a = input('Number? ')
    > list.append(a)
    > zero = list.index(0)
    > del list[zero]
    > list.sort()
    >
    > variableMean = lambda x:sum(x)/len(x)
    > variableMedian = lambda x: x.sort() or x[len(x)//2]
    > variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
    > s = variableMean(li st)
    > y = variableMedian( list)
    > t = variableMode (list)
    >
    > x = (s,y,t)
    > inp = open ("Wade_Stoddard SLP3-2.py", "r")
    > outp = open ("avg.py", "w")
    > f = ("avg.py")
    > for x in inp:
    > outp.write(x)
    > import pickle
    > pickle.dump(x, f)
    >
    >
    > print 'Thank you! Would you like to see the results after calculating'
    > print 'The mode, median, and mean? (Please enter Yes or No)'
    > raw_input('Plea se enter Yes or No:')
    > if raw_input == Yes:
    >
    > f = open("avg.py"," r")
    > avg.py = f.read()
    > print 'The Mean average is:', mean
    > print 'The Median is:', meadian
    > print 'The Mode is:', mode
    >
    > I am attempting to make it so that I can save the mean, meadian, and mode
    > and then if the user wants the data to give it to him. Thank you for any
    > assistance you can provide!
    >
    > Wade[/color]

    --
    James Stroud, Ph.D.
    UCLA-DOE Institute for Genomics and Proteomics
    Box 951570
    Los Angeles, CA 90095

    Comment

    • Steven Bethard

      #3
      Re: NOOB coding help....

      Igorati wrote:[color=blue]
      > list = [ ]
      > a = 1
      > print 'Enter numbers to add to the list. (Enter 0 to quit.)'
      > while a != 0 :
      > a = input('Number? ')
      > list.append(a)
      > zero = list.index(0)
      > del list[zero]
      > list.sort()[/color]

      A simpler approach is to use the second form of the builtin iter
      function which takes a callable and a sentinel:

      py> def getint():
      .... return int(raw_input(' Number? '))
      ....
      py> numbers = sorted(iter(get int, 0))
      Number? 3
      Number? 7
      Number? 5
      Number? 2
      Number? 0
      py> numbers
      [2, 3, 5, 7]

      Note that I've renamed 'list' to 'numbers' so as not to hide the builtin
      type 'list'.
      [color=blue]
      > variableMean = lambda x:sum(x)/len(x)
      > variableMedian = lambda x: x.sort() or x[len(x)//2]
      > variableMode = lambda x: max([(x.count(y),y) for y in x])[1]
      > s = variableMean(li st)
      > y = variableMedian( list)
      > t = variableMode (list)[/color]

      See "Inappropri ate use of Lambda" in
      http://www.python.org/moin/DubiousPython.

      Lambdas aside, some alternate possibilities for these are:

      def variable_median (x):
      # don't modify original list
      return sorted(x)[len(x)//2]
      def variable_mode(x ):
      # only iterate through x once (instead of len(x) times)
      counts = {}
      for item in x:
      counts[x] = counts.get(x, 0) + 1
      # in Python 2.5 you'll be able to do
      # return max(counts, key=counts.__ge titem__)
      return sorted(counts, key=counts.__ge titem__, reverse=True)[0]

      Note also that you probably want 'from __future__ import divsion' at the
      top of your file or variableMean will sometimes give you an int, not a
      float.
      [color=blue]
      > x = (s,y,t)
      > inp = open ("Wade_Stoddard SLP3-2.py", "r")
      > outp = open ("avg.py", "w")
      > f = ("avg.py")
      > for x in inp:
      > outp.write(x)
      > import pickle
      > pickle.dump(x, f)[/color]

      If you want to save s, y and t to a file, you probably want to do
      something like:

      pickle.dump((s, y, t), file('avg.pickl e', 'w'))

      I don't know why you've opened Wade_StoddardSL P3-2.py, or why you write
      that to avg.py, but pickle.dump takes a file object as the second
      parameter, and you're passing it a string object, "avg.py".
      [color=blue]
      > f = open("avg.py"," r")
      > avg.py = f.read()
      > print 'The Mean average is:', mean
      > print 'The Median is:', meadian
      > print 'The Mode is:', mode[/color]

      mean, median, mode = pickle.load(fil e('avg.pickle') )
      print 'The Mean average is:', mean
      print 'The Median is:', meadian
      print 'The Mode is:', mode

      HTH,

      STeVe

      Comment

      • Igorati

        #4
        Re: NOOB coding help....

        Thank you, that does help quit a bit. I am working on the corrections now.
        To the first poster... don't know what that meant. I thought I made my
        case understandable. Thank you again. I will work on that. I was
        attempting to open wade_stoddard.. . b/c that was my file I was working
        with, and I was told I had to open it in order to save information to
        another file so I could recall that information. Thank you again for the
        help Steven.

        Comment

        • Igorati

          #5
          Re: NOOB coding help....

          #This program will ask for a user to imput numbers. The numbers will then
          be calculated
          #to find the statistical mean, mode, and median. Finallly the user will be
          asked
          #if he would like to print out the answers.
          numbers = [ ]
          print 'Enter numbers to add to the list. (Enter 0 to quit.)'
          def getint():
          return int(raw_input(' Number? '))

          numbers = sorted(iter(get int, 0))

          numbers
          [2, 3, 5, 7]
          def variable_median (x):

          return sorted(x)[len(x)//2]
          def variable_mode(x ):

          counts = {}
          for item in x:
          counts[x] = counts.get(x, 0) + 1

          return sorted(counts, key=counts.__ge titem__, reverse=True)[0]



          s = variableMean(nu mbers)
          y = variableMedian( numbers)
          t = variableMode (numbers)

          import pickle
          pickle.dump((s, y, t), file('avg.pickl e', 'w'))


          print 'Thank you! Would you like to see the results after calculating'
          print 'The mode, median, and mean? (Please enter Yes or No)'
          print 'Please enter Yes or No:'


          if raw_input == yes:

          f = open("avg.py"," r")
          avg.py = f.read()
          print 'The Mean average is:', mean
          print 'The Median is:', meadian
          print 'The Mode is:', mode


          I got the error:

          Traceback (most recent call last):
          File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 9, in ?
          numbers = sorted(iter(get int, 0))
          File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 7, in
          getint
          return int(raw_input(' Number? '))
          TypeError: 'str' object is not callable

          and this one for my if statement:

          Traceback (most recent call last):
          File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 39, in ?
          if raw_input == Yes:
          NameError: name 'Yes' is not defined

          I cannot understand how I can define yes so that when they type yes the
          data is printed out. Also if they type no how do I make the program do
          nothing. Or is that just infered.



          Comment

          • Brian van den Broek

            #6
            Re: NOOB coding help....

            Igorati said unto the world upon 2005-02-22 03:51:[color=blue]
            > #This program will ask for a user to imput numbers. The numbers will then
            > be calculated
            > #to find the statistical mean, mode, and median. Finallly the user will be
            > asked
            > #if he would like to print out the answers.
            > numbers = [ ]
            > print 'Enter numbers to add to the list. (Enter 0 to quit.)'
            > def getint():
            > return int(raw_input(' Number? '))
            >
            > numbers = sorted(iter(get int, 0))
            >
            > numbers
            > [2, 3, 5, 7]
            > def variable_median (x):
            >
            > return sorted(x)[len(x)//2]
            > def variable_mode(x ):
            >
            > counts = {}
            > for item in x:
            > counts[x] = counts.get(x, 0) + 1
            >
            > return sorted(counts, key=counts.__ge titem__, reverse=True)[0]
            >
            >
            >
            > s = variableMean(nu mbers)
            > y = variableMedian( numbers)
            > t = variableMode (numbers)
            >
            > import pickle
            > pickle.dump((s, y, t), file('avg.pickl e', 'w'))
            >
            >
            > print 'Thank you! Would you like to see the results after calculating'
            > print 'The mode, median, and mean? (Please enter Yes or No)'
            > print 'Please enter Yes or No:'
            >
            >
            > if raw_input == yes:
            >
            > f = open("avg.py"," r")
            > avg.py = f.read()
            > print 'The Mean average is:', mean
            > print 'The Median is:', meadian
            > print 'The Mode is:', mode
            >
            >
            > I got the error:
            >
            > Traceback (most recent call last):
            > File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 9, in ?
            > numbers = sorted(iter(get int, 0))
            > File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 7, in
            > getint
            > return int(raw_input(' Number? '))
            > TypeError: 'str' object is not callable
            >
            > and this one for my if statement:
            >
            > Traceback (most recent call last):
            > File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 39, in ?
            > if raw_input == Yes:
            > NameError: name 'Yes' is not defined
            >
            > I cannot understand how I can define yes so that when they type yes the
            > data is printed out. Also if they type no how do I make the program do
            > nothing. Or is that just infered.[/color]

            Hi,

            have you tried examining the objects you are trying to put together to
            see why they might not fit?

            For instance, look what happens when you run this, entering 42 at the
            prompt:

            ri = raw_input('Gimm e! ')
            print type(ri)
            print type(int(ri))
            print ri == 42
            print ri == '42'
            name_not_define d_in_this_code

            Does looking at the output of that help?

            Best,

            Brian vdB

            Comment

            • bruno modulix

              #7
              Re: NOOB coding help....

              Igorati wrote:[color=blue]
              > #This program will ask for a user to imput numbers. The numbers will then
              > be calculated
              > #to find the statistical mean, mode, and median. Finallly the user will be
              > asked
              > #if he would like to print out the answers.
              >
              > numbers = [ ]
              > print 'Enter numbers to add to the list. (Enter 0 to quit.)'[/color]

              so 0 is not a valid value ?
              Since you only want numbers, any alpha char could be used to exit...
              [color=blue]
              > def getint():
              > return int(raw_input(' Number? '))[/color]

              What happens if the user type "foo" ?
              [color=blue]
              > numbers = sorted(iter(get int, 0))
              >
              > numbers
              > [2, 3, 5, 7]
              > def variable_median (x):
              >
              > return sorted(x)[len(x)//2]
              > def variable_mode(x ):
              >
              > counts = {}
              > for item in x:
              > counts[x] = counts.get(x, 0) + 1
              >
              > return sorted(counts, key=counts.__ge titem__, reverse=True)[0]
              >
              >
              >
              > s = variableMean(nu mbers)
              > y = variableMedian( numbers)
              > t = variableMode (numbers)
              >
              > import pickle
              > pickle.dump((s, y, t), file('avg.pickl e', 'w'))[/color]

              Take care of removing hard-coded filenames... (this is ok for testing
              but should not be released like this)
              [color=blue]
              >
              > print 'Thank you! Would you like to see the results after calculating'
              > print 'The mode, median, and mean? (Please enter Yes or No)'
              > print 'Please enter Yes or No:'
              >
              >
              > if raw_input == yes:[/color]

              First, raw_input() is a function, you need to use the () operator to
              *call* (execute) the function.

              Then, raw_input() returns a string. A string is something between
              quotes. Yes is a symbol (a variable name, function name or like), not a
              string. And since this symbol is not defined, you have an exception.

              What you want to do is to compare the string returned by the raw_input()
              function to the literral string "Yes". What you're doing in fact is
              comparing two symbols, one being defined, the other one being undefined...

              if raw_input() == "Yes":
              [color=blue]
              >
              > f = open("avg.py"," r")[/color]
              Same remark as above about hard-coded file names...
              [color=blue]
              > avg.py = f.read()[/color]

              Notice that the dot is an operator. Here you trying to access the
              attribute 'py' of an (actually inexistant) object named 'avg'. What you
              want is to bind the data returned by f.read() to a variable.

              data = f.read()

              [color=blue]
              > print 'The Mean average is:', mean
              > print 'The Median is:', meadian
              > print 'The Mode is:', mode[/color]

              At this time, mean, meadian and mode are undefined symbols. Since you
              used the pickle module to persist your data, you should use it to
              unserialize'em too. The pickle module is well documented, so you may
              want to read the manual.
              [color=blue]
              >
              > I got the error:
              >
              > Traceback (most recent call last):
              > File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 9, in ?
              > numbers = sorted(iter(get int, 0))
              > File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 7, in
              > getint
              > return int(raw_input(' Number? '))
              > TypeError: 'str' object is not callable[/color]

              Can't tell you since I'm running python 2.3.x here (sorted() is new in 2.4)
              [color=blue]
              > and this one for my if statement:
              >
              > Traceback (most recent call last):
              > File "C:\Python24\Li b\New Folder\Wade_Sto ddardSLP3-2.py", line 39, in ?
              > if raw_input == Yes:
              > NameError: name 'Yes' is not defined[/color]

              See above.
              [color=blue]
              > I cannot understand how I can define yes so that when they type yes the
              > data is printed out.[/color]

              Yes = 'yes' ?-)
              [color=blue]
              > Also if they type no how do I make the program do
              > nothing. Or is that just infered.[/color]

              May I suggest that you :
              - subscribe to the 'tutor' mailing-list (it's a ml for absolute beginners)
              - do some tutorials (there's one with the doc, and many others freely
              available on the net)
              - use the interactive python shell to test bits of your code ?

              HTH
              Bruno
              --
              bruno desthuilliers
              python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
              p in 'onurb@xiludom. gro'.split('@')])"

              Comment

              Working...