Grieve (grieve) wrote,
Grieve
grieve

List Comprehensions in python

veloso had an interesting python puzzle for me in python. How could you take a tuple in python, such as (1,2,3) and transform it into the tuple (1,1,2,2,3,3)? For the examples below assume orig = (1,2,3)

His original stab as presented to me was follows:
    newTuple = tuple(chain(*(repeat(x, 2) for x in orig)))

I was able to modify as follows:
    newTuple = tuple(chain(*((x, x) for x in orig)))

Which is slightly cleaner, but his coworker had the best solution:
    newTuple = tuple(i for x in orig for i in (x,x))


I am not a big fan of list comprehensions (I think they make the code harder to read), so I came up with the follow:
   def repeatElements(list, count):
      for x in list:
         for y in range(count):
            yield x

   newTuple = tuple(repeatElements(orig, 2))

This has the added benefit of being able to repeat any number of times, but of course requires more lines and a generator function.
Tags: progamming
Subscribe

  • A C++ quiz

    Suppose I gave you the following snippets of code: #include <cstdio> void Class::PrintFoo() { printf("Foo\n"); } int main() { Class13 c13;…

  • Volatile does not thread safe make.

    I keep running across code, some old and some new, that uses the volatile keyword in an attempt to make the code thread "safe". Using that is always…

  • How many Univacs is that?

    Today at work one of my coworkers had a new phone. I flippantly asked him how many Univacs it was? Of course in a room full of geeks once a question…

  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments