Best way to generate alternate toggling values in a loop?

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

    Best way to generate alternate toggling values in a loop?

    I'm writing this little Python program which will pull values from a
    database and generate some XHTML.

    I'm generating a <tablewhere I would like the alternate <tr>'s to be

    <tr class="Even">
    and
    <tr class="Odd">

    What is the best way to do this?

    I wrote a little generator (code snippet follows). Is there a better
    (more "Pythonic") way to do this?


    # Start of Code

    def evenOdd():
    values = ["Even", "Odd"]
    state = 0
    while True:
    yield values[state]
    state = (state + 1) % 2


    # Snippet

    trClass = evenOdd()
    stringBuffer = cStringIO.Strin gIO()

    for id, name in result:
    stringBuffer.wr ite('''
    <tr class="%s">
    <td>%d</td>
    <td>%s</td>
    </tr>
    '''
    %
    (trClass.next() , id, name))


    # End of Code

  • Carsten Haese

    #2
    Re: Best way to generate alternate toggling values in a loop?

    On Wed, 2007-10-17 at 23:55 +0000, Debajit Adhikary wrote:
    I'm writing this little Python program which will pull values from a
    database and generate some XHTML.
    >
    I'm generating a <tablewhere I would like the alternate <tr>'s to be
    >
    <tr class="Even">
    and
    <tr class="Odd">
    >
    What is the best way to do this?
    >
    I wrote a little generator (code snippet follows). Is there a better
    (more "Pythonic") way to do this?
    >
    >
    # Start of Code
    >
    def evenOdd():
    values = ["Even", "Odd"]
    state = 0
    while True:
    yield values[state]
    state = (state + 1) % 2
    >
    >
    # Snippet
    >
    trClass = evenOdd()
    stringBuffer = cStringIO.Strin gIO()
    >
    for id, name in result:
    stringBuffer.wr ite('''
    <tr class="%s">
    <td>%d</td>
    <td>%s</td>
    </tr>
    '''
    %
    (trClass.next() , id, name))
    This is a respectable first attempt, but I recommend you familiarize
    yourself with the itertools module. It has lots of useful tools for
    making your code more elegant and concise.

    Rather than spelling out the final result, I'll give you hints: Look at
    itertools.cycle and itertools.izip.

    HTH,

    --
    Carsten Haese



    Comment

    • Grant Edwards

      #3
      Re: Best way to generate alternate toggling values in a loop?

      On 2007-10-17, Debajit Adhikary <debajit1@gmail .comwrote:
      # Start of Code
      >
      def evenOdd():
      values = ["Even", "Odd"]
      state = 0
      while True:
      yield values[state]
      state = (state + 1) % 2
      I'd replace the last line with

      state ^= 1

      to save a couple instructions, but I spend too much time
      working with micoroprocessor s running on clocks measured in the
      KHz.

      There are probably other more Pythonic ways...

      --
      Grant Edwards grante Yow! My EARS are GONE!!
      at
      visi.com

      Comment

      • Gerard Flanagan

        #4
        Re: Best way to generate alternate toggling values in a loop?

        On Oct 18, 1:55 am, Debajit Adhikary <debaj...@gmail .comwrote:
        I'm writing this little Python program which will pull values from a
        database and generate some XHTML.
        >
        I'm generating a <tablewhere I would like the alternate <tr>'s to be
        >
        <tr class="Even">
        and
        <tr class="Odd">
        >
        What is the best way to do this?
        >

        from itertools import izip

        def toggle(start=Tr ue):
        flag = start
        while 1:
        flag = not flag
        yield flag


        CSS = ("even", "odd")

        HTML = '<tr class="%s"><td> %d</td><td>%s</td></tr>'

        result = [(1, 'One'), (2, 'two'), (3, 'Three'), (4, 'Four'), (5,
        'Five')]

        for flag, (id, name) in izip(toggle(), result):
        print HTML % (CSS[flag], id, name)


        <tr class="even"><t d>1</td><td>One</td></tr>
        <tr class="odd"><td >2</td><td>two</td></tr>
        <tr class="even"><t d>3</td><td>Three</td></tr>
        <tr class="odd"><td >4</td><td>Four</td></tr>
        <tr class="even"><t d>5</td><td>Five</td></tr>

        Comment

        • Amit Khemka

          #5
          Re: Best way to generate alternate toggling values in a loop?

          On 10/18/07, Carsten Haese <carsten@uniqsy s.comwrote:
          On Wed, 2007-10-17 at 23:55 +0000, Debajit Adhikary wrote:
          I'm writing this little Python program which will pull values from a
          database and generate some XHTML.

          I'm generating a <tablewhere I would like the alternate <tr>'s to be

          <tr class="Even">
          and
          <tr class="Odd">

          What is the best way to do this?

          I wrote a little generator (code snippet follows). Is there a better
          (more "Pythonic") way to do this?


          # Start of Code

          def evenOdd():
          values = ["Even", "Odd"]
          state = 0
          while True:
          yield values[state]
          state = (state + 1) % 2


          # Snippet

          trClass = evenOdd()
          stringBuffer = cStringIO.Strin gIO()

          for id, name in result:
          stringBuffer.wr ite('''
          <tr class="%s">
          <td>%d</td>
          <td>%s</td>
          </tr>
          '''
          %
          (trClass.next() , id, name))
          >
          This is a respectable first attempt, but I recommend you familiarize
          yourself with the itertools module. It has lots of useful tools for
          making your code more elegant and concise.
          >
          Rather than spelling out the final result, I'll give you hints: Look at
          itertools.cycle and itertools.izip.
          >
          Why not just use enumerate ?

          clvalues = ["Even", "Odd"]
          for i, (id, name) in enumerate(resul t):
          stringBuffer.wr ite('''
          <tr class="%s">
          <td>%d</td>
          <td>%s</td>
          </tr>
          '''
          %
          (clvalues[i % 2], id, name))

          Cheers,

          --
          --
          Amit Khemka

          Comment

          • Paul Hankin

            #6
            Re: Best way to generate alternate toggling values in a loop?

            On Oct 18, 12:11 pm, "Amit Khemka" <khemkaa...@gma il.comwrote:
            On 10/18/07, Carsten Haese <cars...@uniqsy s.comwrote:
            Rather than spelling out the final result, I'll give you hints: Look at
            itertools.cycle and itertools.izip.
            >
            Why not just use enumerate ?
            >
            clvalues = ["Even", "Odd"]
            for i, (id, name) in enumerate(resul t):
            stringBuffer.wr ite('''
            <tr class="%s">
            <td>%d</td>
            <td>%s</td>
            </tr>
            '''
            %
            (clvalues[i % 2], id, name))
            I like this code: straightforward and pragmatic. Everyone else seems
            to be reinventing itertools.cycle - they should have listened to
            Carsten, and written something like this:

            import itertools

            clvalues = itertools.cycle (['Even', 'Odd'])
            for clvalue, (id, name) in itertools.izip( clvalues, result):
            stringBuffer.wr ite('''
            <tr class="%(name)s ">
            <td>%(id)d</td>
            <td>%(clvalue)s </td>
            </tr>''' % locals())

            --
            Paul Hankin

            Comment

            • Grant Edwards

              #7
              Re: Best way to generate alternate toggling values in a loop?

              On 2007-10-18, Gerard Flanagan <grflanagan@yah oo.co.ukwrote:
              On Oct 18, 1:55 am, Debajit Adhikary <debaj...@gmail .comwrote:
              >I'm writing this little Python program which will pull values from a
              >database and generate some XHTML.
              >>
              >I'm generating a <tablewhere I would like the alternate <tr>'s to be
              >>
              ><tr class="Even">
              >and
              ><tr class="Odd">
              >>
              >What is the best way to do this?
              >>
              >
              >
              from itertools import izip
              >
              def toggle(start=Tr ue):
              flag = start
              while 1:
              flag = not flag
              yield flag
              I like the solution somebody sent me via PM:

              def toggle():
              while 1:
              yield "Even"
              yield "Odd"

              --
              Grant Edwards grante Yow! Are we THERE yet?
              at
              visi.com

              Comment

              • Alex Martelli

                #8
                Re: Best way to generate alternate toggling values in a loop?

                Grant Edwards <grante@visi.co mwrote:
                ...
                I like the solution somebody sent me via PM:
                >
                def toggle():
                while 1:
                yield "Even"
                yield "Odd"
                I think the itertools-based solution is more elegant:

                toggle = itertools.cycle (('Even', 'Odd'))

                and use toggle rather than toggle() later; or, just use that
                itertools.cycle call inside the expression instead of toggle().


                Alex

                Comment

                • Iain King

                  #9
                  Re: Best way to generate alternate toggling values in a loop?

                  On Oct 18, 2:29 am, Grant Edwards <gra...@visi.co mwrote:
                  On 2007-10-17, Debajit Adhikary <debaj...@gmail .comwrote:
                  >
                  # Start of Code
                  >
                  def evenOdd():
                  values = ["Even", "Odd"]
                  state = 0
                  while True:
                  yield values[state]
                  state = (state + 1) % 2
                  >
                  I'd replace the last line with
                  >
                  state ^= 1
                  >
                  to save a couple instructions, but I spend too much time
                  working with micoroprocessor s running on clocks measured in the
                  KHz.
                  >
                  There are probably other more Pythonic ways...
                  >

                  I always use:

                  state = 1 - state

                  for toggles. I doubt it's much more pythonic though :)

                  Iain

                  Comment

                  • cokofreedom@gmail.com

                    #10
                    Re: Best way to generate alternate toggling values in a loop?

                    On Oct 18, 3:48 pm, Iain King <iaink...@gmail .comwrote:
                    On Oct 18, 2:29 am, Grant Edwards <gra...@visi.co mwrote:
                    >
                    >
                    >
                    On 2007-10-17, Debajit Adhikary <debaj...@gmail .comwrote:
                    >
                    # Start of Code
                    >
                    def evenOdd():
                    values = ["Even", "Odd"]
                    state = 0
                    while True:
                    yield values[state]
                    state = (state + 1) % 2
                    >
                    I'd replace the last line with
                    >
                    state ^= 1
                    >
                    to save a couple instructions, but I spend too much time
                    working with micoroprocessor s running on clocks measured in the
                    KHz.
                    >
                    There are probably other more Pythonic ways...
                    >
                    I always use:
                    >
                    state = 1 - state
                    >
                    for toggles. I doubt it's much more pythonic though :)
                    >
                    Iain
                    why not do
                    state = not state
                    ?

                    Comment

                    • Luis Zarrabeitia

                      #11
                      Re: Best way to generate alternate toggling values in a loop?

                      On Thursday 18 October 2007 09:09, Grant Edwards wrote:
                      I like the solution somebody sent me via PM:
                      >
                      def toggle():
                      while 1:
                      yield "Even"
                      yield "Odd"
                      >
                      That was me.
                      Sorry, list, I meant to send it to everyone but I my webmail didn't respect
                      the list* headers :(.

                      Thanks, Grant!

                      --
                      Luis Zarrabeitia (aka Kyrie)
                      Fac. de Matemática y Computación, UH.

                      Comment

                      Working...