Questions: While And List Comprehension

Felipe Vinturini felipe.vinturini at gmail.com
Wed Nov 10 07:36:41 EST 2010


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
===================================================================================

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():
    sysStdinReadLine = sys.stdin.readline
    numValues = int(sysStdinReadLine())
    [ 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?

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.

Thanks for your attention!

Regards,
Felipe.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20101110/fc408b09/attachment.html>


More information about the Python-list mailing list