Questions: While And List Comprehension

Emile van Sebille emile at fenx.com
Wed Nov 10 23:56:45 CET 2010

```On 11/10/2010 4:36 AM Felipe Vinturini said...
> Hi Folks,
>
> I am quite new to python and I don't have a lot of experience with it yet.
>
> I have two simple questions:
>
> 1. Is there a way to limit the number of times a list comprehension will
> execute? E.g. I want to read from input only 5 values, so I would like
> something like (the values between # # are what I want):
> ===================================================================================
> COUNT = 0
> print [ v for v in sys.stdin.readlines() *# *IF COUNT<  5* #* ] ## Increment
> COUNT somewhere

Easiest would be print [ v for v in sys.stdin.readlines()[:5] ] but that
still reads the entire sys.stdin (whatever it may be...)

> ===================================================================================
>
> 2.* *I would like to know another way, a more pythonic way, to write the
> following:
> ===================================================================================
> import sys
>
> def Z(iNumber):
>      sum=0
>      while (iNumber>=5):
>          iNumber=iNumber/5
>          sum = sum + iNumber
>      print sum
>
> def factorialCountZeros2():
>      [ Z(int(sysStdinReadLine())) for x in xrange(numValues) ]
>
> if __name__ == '__main__':
>      factorialCountZeros2()
> ===================================================================================
> To be more specific, I would like to know about the Z function, is there a
> way to rewrite that while with list comprehension?

Well, you could use

def X(iNumber):
print sum([iNumber/(5**ii) for ii in range(1,2*int(len("%s" %
iNumber)))])

but the range selection is rather arbitrary.

Emile

>
> This code is to solve the CodeChef problem:
> http://www.codechef.com/problems/FCTRL/ (I am still in the easy part) and it
> executed in 2.5 secs, I would like to know if there is something else I can
> improve performance.
>