Help With Python

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

    #1

    Help With Python


    I am currently taking a course to learn Python and was looking for
    some help. I need to write a Python statement to print a comma-
    separated repetition of the word, "Spam", written 511 times ("Spam,
    Spam, … Spam").

    Can anybody help me get started? I am completely new to programming!

    Thanks in advance!



  • Thomas Guettler

    #2
    Re: Help With Python

    Am Wed, 26 Jan 2005 15:55:28 +0000 schrieb Judi Keplar:
    [color=blue]
    >
    > I am currently taking a course to learn Python and was looking for
    > some help. I need to write a Python statement to print a comma-
    > separated repetition of the word, "Spam", written 511 times ("Spam,
    > Spam, … Spam").
    >
    > Can anybody help me get started? I am completely new to programming![/color]

    Hi,

    # This way, there is a comma after the last:
    import sys
    for i in range(511):
    sys.stdout.writ e("Spam, ")

    # No comma at the end:
    mylist=[]
    for i in range(511):
    mylist.append(" Spam")
    print ", ".join(myli st)

    Thomas

    --
    Thomas Güttler, http://www.thomas-guettler.de/


    Comment

    • Peter Maas

      #3
      Re: Help With Python

      Judi Keplar schrieb:[color=blue]
      > I am currently taking a course to learn Python and was looking for
      > some help. I need to write a Python statement to print a comma-
      > separated repetition of the word, "Spam", written 511 times ("Spam,
      > Spam, … Spam").
      >
      > Can anybody help me get started? I am completely new to programming![/color]

      Online:

      - http://www.python.org/moin/BeginnersGuide (Beginner, Advanced)
      - http://www.freenetpages.co.uk/hp/alan.gauld/ (Beginner)
      - http://docs.python.org/tut/tut.html (Beginner)
      - http://diveintopython.org/ (Advanced)

      Books (Look for most recent editions):

      - Mark Lutz, Learning Python (Beginner)
      - Alex Martelli, Python in a Nutshell (Beginner, Advanced)
      - Frederik Lundh, Python Standard Library (Beginner, Advanced)
      - Alex Martelli, Python Cookbook (Beginner, Advanced)
      - Mark Pilgrim Dive Into Python (Advanced)

      --
      -------------------------------------------------------------------
      Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0
      E-mail 'cGV0ZXIubWFhc0 BtcGx1c3IuZGU=\ n'.decode('base 64')
      -------------------------------------------------------------------

      Comment

      • Will McGugan

        #4
        Re: Help With Python

        Judi Keplar wrote:[color=blue]
        > I am currently taking a course to learn Python and was looking for
        > some help. I need to write a Python statement to print a comma-
        > separated repetition of the word, "Spam", written 511 times ("Spam,
        > Spam, … Spam").
        >
        > Can anybody help me get started? I am completely new to programming!
        >
        > Thanks in advance![/color]
        [color=blue][color=green][color=darkred]
        >>> print "Spam, " * 510 + "Spam"[/color][/color][/color]

        Will McGugan

        Comment

        • Will McGugan

          #5
          Re: Help With Python

          [color=blue]
          >[color=green][color=darkred]
          > >>> print "Spam, " * 510 + "Spam"[/color][/color][/color]

          Or if you have 2.4..
          [color=blue][color=green][color=darkred]
          >>> print ", ".join( "Spam" for _ in xrange( 511 ) )[/color][/color][/color]

          Although, the replys with links will ultimately be more helpful!

          Will McGugan

          Comment

          • Kartic

            #6
            Re: Help With Python

            Py>>> print "Spam, " * 115
            Spam, Spam, Spam, Spam, Spam, ............... .. Spam,

            Multiplies (repeats) the string 115 times.

            To eliminate the last ", " (that is, a comma followed by space), you
            can do it using the slice notation and say:
            Py>>> print ("Spam, " * 115) [:-2]
            Spam, Spam, Spam, Spam, Spam, ............... .., Spam

            The [:-2] means that you asking Python to print everything from the
            beginning to the last but two characters of the string. You can also
            write this as [0:-2]

            [or [0:length_of_spa m - 2] where length_of_spam = len("Spam, " * 115)]

            Since you are starting off, please read and follow the tuturial that
            available with your Python installation or on the Python.org site at
            Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax an...


            Thank you,
            --Kartic

            Comment

            • Steven Bethard

              #7
              Re: Help With Python

              Thomas Guettler wrote:[color=blue]
              > Am Wed, 26 Jan 2005 15:55:28 +0000 schrieb Judi Keplar:
              >
              >[color=green]
              >>I am currently taking a course to learn Python and was looking for
              >>some help. I need to write a Python statement to print a comma-
              >>separated repetition of the word, "Spam", written 511 times ("Spam,
              >>Spam, � Spam").
              >>
              >>Can anybody help me get started? I am completely new to programming![/color]
              >
              >
              > Hi,
              >
              > # This way, there is a comma after the last:
              > import sys
              > for i in range(511):
              > sys.stdout.writ e("Spam, ")
              >
              > # No comma at the end:
              > mylist=[]
              > for i in range(511):
              > mylist.append(" Spam")
              > print ", ".join(myli st)[/color]

              # also no comma at the end, using a list comprehension
              print ", ".join(["Spam" for _ in xrange(511)])

              # also no comma at the end, using a generator expresssion (Python 2.4)
              print ", ".join("Spa m" for _ in xrange(511))

              Steve

              Comment

              • Kent Johnson

                #8
                Re: Help With Python

                Thomas Guettler wrote:[color=blue]
                > # No comma at the end:
                > mylist=[]
                > for i in range(511):
                > mylist.append(" Spam")[/color]

                or just
                mylist = ["Spam"] * 511

                Kent
                [color=blue]
                > print ", ".join(myli st)
                >
                > Thomas
                >[/color]

                Comment

                • Roy Smith

                  #9
                  Re: Help With Python

                  In article <mailman.1356.1 106754931.22381 .python-list@python.org >,
                  Judi Keplar <judi-keplar@charter. net> wrote:[color=blue]
                  >
                  >I am currently taking a course to learn Python and was looking for
                  >some help. I need to write a Python statement to print a comma-
                  >separated repetition of the word, "Spam", written 511 times ("Spam,
                  >Spam, =85 Spam").
                  >
                  >Can anybody help me get started? I am completely new to programming![/color]

                  Well, I'll point you in a couple of good directions.

                  The first direction would be to approach this as a traditional
                  procedural programming problem. You need some kind of loop that can
                  exectute a print statement 511 times. In Python, that looks something
                  like:

                  for i in range(511):
                  print "spam"

                  Almost immediately, the question that comes to mind is where, exactly,
                  does the loop start and stop? For example, you might expect that

                  for i in range(5):
                  print i

                  would print the numbers 1 through 5, but it really prints 0 through
                  4. This kind of "off by one" thing is a very common common issue in
                  writing loops in almost any programming language. It's a common
                  enough issue that a whole class of bugs is named after it, known as
                  "fencepost errors". So, left as an exercise for the reader
                  (i.e. you), is to figure out if "for i in range(511)" really does the
                  loop 511 times, or maybe 510 or 512?

                  Next, you'll notice that the first loop I wrote prints one "spam" on
                  each line. The way you described the problem, you want all the spams
                  on one big long line, with commas between each one. The way you get
                  Python to not advance to the next line is to end the print statement
                  with a comma, like this:

                  for i in range(511):
                  print "spam",

                  Notice that there's something tricky going on here; the comma doesn't
                  get printed, it's just a way of telling the print statement, "don't go
                  on to the next line". To really get it to print a comma, you need
                  something like:

                  for i in range(511):
                  print "spam,",

                  The first comma is inside the quoted string, so it gets printed. The
                  second one is the one that says "don't go to the next line".

                  You're still not quite done, but I've given you enough hints. Go play
                  with that, see what you get, and see if you can figure out what
                  problems you still need to fix.

                  I said I'd point you in a couple of good directions, and the second
                  one is to look up how the "join()" string method works. It's really
                  cool, and solves your problem in a different way. But, first I think
                  you should master the straight-forward way.

                  Lastly, the really cool Pythonic way would be to get a bunch of
                  Vikings into a restaurant and give them all breakfast menus. The only
                  problem there is you'd have trouble handing all those Vikings in with
                  your assignment.

                  Comment

                  • Fredrik Lundh

                    #10
                    Re: Help With Python

                    Peter Maas wrote:
                    [color=blue][color=green]
                    > > Can anybody help me get started? I am completely new to programming![/color][/color]
                    [color=blue]
                    > Online:
                    >
                    > - http://www.python.org/moin/BeginnersGuide (Beginner, Advanced)
                    > - http://www.freenetpages.co.uk/hp/alan.gauld/ (Beginner)
                    > - http://docs.python.org/tut/tut.html (Beginner)
                    > - http://diveintopython.org/ (Advanced)[/color]

                    also:


                    [color=blue]
                    > Books (Look for most recent editions):
                    >
                    > - Mark Lutz, Learning Python (Beginner)
                    > - Alex Martelli, Python in a Nutshell (Beginner, Advanced)
                    > - Frederik Lundh, Python Standard Library (Beginner, Advanced)[/color]

                    on-line here: http://effbot.org/librarybook
                    on-line here: http://effbot.org/zone/librarybook.htm (pdf version)
                    [color=blue]
                    > - Alex Martelli, Python Cookbook (Beginner, Advanced)
                    > - Mark Pilgrim Dive Into Python (Advanced)[/color]

                    on-line here: http://diveintopython.org

                    </F>



                    Comment

                    • Nick Vargish

                      #11
                      Re: Help With Python


                      Here's my Monty Pythonic answer:

                      ## cut here
                      class Viking():

                      def __init__():
                      pass

                      def order():
                      return 'Spam'

                      # this is one viking making one order repeated 511 times. if you want
                      # 511 vikings making seperate orders, you'll have to write a loop.
                      v = Viking()
                      orders = [ v.order() ] * 511

                      print ', '.join(orders)
                      ## cut here

                      With no apologies to Eric Idle,

                      Nick


                      --
                      # sigmask || 0.2 || 20030107 || public domain || feed this to a python
                      print reduce(lambda x,y:x+chr(ord(y )-1),' Ojdl!Wbshjti!=o bwAcboefstobudi/psh?')

                      Comment

                      • Steven Bethard

                        #12
                        Re: Help With Python

                        Nick Vargish wrote:[color=blue]
                        > Here's my Monty Pythonic answer:
                        >
                        > ## cut here
                        > class Viking():
                        >
                        > def __init__():
                        > pass
                        >
                        > def order():
                        > return 'Spam'
                        >
                        > # this is one viking making one order repeated 511 times. if you want
                        > # 511 vikings making seperate orders, you'll have to write a loop.
                        > v = Viking()
                        > orders = [ v.order() ] * 511
                        >
                        > print ', '.join(orders)[/color]

                        No need to write a loop:

                        py> class Viking(object):
                        .... def order(self):
                        .... return 'Spam'
                        ....
                        py> v = Viking()
                        py> orders = [v.order()] * 7
                        py> ', '.join(orders)
                        'Spam, Spam, Spam, Spam, Spam, Spam, Spam'
                        py> orders = [Viking().order( )] * 7
                        py> ', '.join(orders)
                        'Spam, Spam, Spam, Spam, Spam, Spam, Spam'

                        Steve

                        Comment

                        • Matt

                          #13
                          Re: Help With Python

                          Nick Vargish wrote:[color=blue]
                          > Here's my Monty Pythonic answer:
                          >
                          > ## cut here
                          > class Viking():
                          >
                          > def __init__():
                          > pass
                          >
                          > def order():
                          > return 'Spam'
                          >
                          > # this is one viking making one order repeated 511 times. if you want
                          > # 511 vikings making seperate orders, you'll have to write a loop.
                          > v = Viking()
                          > orders = [ v.order() ] * 511
                          >
                          > print ', '.join(orders)
                          > ## cut here
                          >
                          > With no apologies to Eric Idle,
                          >
                          > Nick
                          >
                          >
                          > --
                          > # sigmask || 0.2 || 20030107 || public domain || feed this[/color]
                          to a python[color=blue]
                          > print reduce(lambda x,y:x+chr(ord(y )-1),'[/color]
                          Ojdl!Wbshjti!=o bwAcboefstobudi/psh?')

                          Not to be nit-picky, but you got some issues here ;-). Never forget
                          the importance of "self"!

                          ############### ########
                          class Viking:
                          .. def __init__(self):
                          .. pass
                          .. def sing(self):
                          .. return 'Spam'
                          v = Viking()
                          spam_song = [ v.sing() ] * 511
                          print ', '.join(spam_son g)

                          Comment

                          • Nick Vargish

                            #14
                            Re: Help With Python

                            "Matt" <matthew_shomph e@countrywide.c om> writes:
                            [color=blue]
                            > Not to be nit-picky, but you got some issues here ;-). Never forget
                            > the importance of "self"![/color]

                            Teach me to post untested code. *hangs head*

                            Nick

                            --
                            # sigmask || 0.2 || 20030107 || public domain || feed this to a python
                            print reduce(lambda x,y:x+chr(ord(y )-1),' Ojdl!Wbshjti!=o bwAcboefstobudi/psh?')

                            Comment

                            • Nick Craig-Wood

                              #15
                              Re: Help With Python

                              Steven Bethard <steven.bethard @gmail.com> wrote:[color=blue]
                              > Nick Vargish wrote:[color=green]
                              > > # this is one viking making one order repeated 511 times. if you want
                              > > # 511 vikings making seperate orders, you'll have to write a loop.[/color]
                              >
                              > No need to write a loop:
                              >
                              > py> class Viking(object):
                              > ... def order(self):
                              > ... return 'Spam'
                              > ...
                              > py> v = Viking()
                              > py> orders = [v.order()] * 7
                              > py> ', '.join(orders)
                              > 'Spam, Spam, Spam, Spam, Spam, Spam, Spam'
                              > py> orders = [Viking().order( )] * 7
                              > py> ', '.join(orders)
                              > 'Spam, Spam, Spam, Spam, Spam, Spam, Spam'[/color]

                              Thats still one Viking making 7 orders surely?

                              Eg
                              [color=blue][color=green][color=darkred]
                              >>> vikings = [Viking()] * 7
                              >>> vikings[0] is vikings[1][/color][/color][/color]
                              True

                              whereas
                              [color=blue][color=green][color=darkred]
                              >>> vikings = [Viking() for _ in range(7)]
                              >>> vikings[0] is vikings[1][/color][/color][/color]
                              False

                              So you want this...
                              [color=blue][color=green][color=darkred]
                              >>> orders = [ Viking().order( ) for _ in range(7) ][/color][/color][/color]

                              --
                              Nick Craig-Wood <nick@craig-wood.com> -- http://www.craig-wood.com/nick

                              Comment

                              Working...