[Tutor] Re: Creatively solving math problems -----help

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Sep 9 19:21:28 EDT 2003


> This won't help you a lot because it's too difficult to understand, but
> it's fun to see anyway *wink*; a one-line solution:
>
>  >>> [ x for x in range(20000) if [x%i for i in range(2,8)]==[1]*5+[0] ]
> [301, 721, 1141, 1561, 1981, 2401, 2821, 3241, 3661, 4081, 4501, 4921, 5341,
> 5761, 6181, 6601, 7021, 7441, 7861, 8281, 8701, 9121, 9541, 9961, 10381, 10801,
> 11221, 11641, 12061, 12481, 12901, 13321, 13741, 14161, 14581, 15001, 15421,
> 15841, 16261, 16681, 17101, 17521, 17941, 18361, 18781, 19201, 19621]

Hi Andrei,



Here's one over-the-top way to solve the problem... using itertools!
*grin*


###
#!/usr/local/bin/python
import itertools


"""Small program to demonstrate the use of itertools in solving numeric
puzzles...  *grin*"""


def main():
    twos = makeStream(lambda x: x*2 + 1)
    threes = makeStream(lambda x: x*3 + 1)
    fours = makeStream(lambda x: x*4 + 1)
    fives = makeStream(lambda x: x*5 + 1)
    sixes = makeStream(lambda x: x*6 + 1)
    sevens = makeStream(lambda x: x*7)
    numbers = reduce(intersect, [twos, threes, fours,
                                 fives, sixes, sevens])
    for n in numbers:
        print n


def intersect(i1, i2):
    """Intersects two integer iterators into a single iterator."""
    i1, i2 = iter(i1), iter(i2)
    x, y = i1.next(), i2.next()
    while 1:
        if x < y:
            x = i1.next()
        elif x > y:
            y = i2.next()
        else:
            yield x
            x = i1.next()
            y = i2.next()

def makeStream(f):
    """Produces a stream of numbers based on the given function."""
    return itertools.imap(f, itertools.count())


if __name__ == '__main__':
    main()
###


Sorry, I couldn't resist.  *grin*




More information about the Tutor mailing list