Help with map python 2

Dan Stromberg drsalists at gmail.com
Sun Jan 4 13:06:06 EST 2015


I'm partial to:

#!/usr/local/cpython-3.4/bin/python

def gen_series(top=None):
    '''
    Generate the numbers from 2 to top, with alternating signs.
    If top is None, generate forever.
    If top is an integer, generate from 2 to top.
    '''
    sign = 1
    if top is None:
        number = 2
        while True:
            yield number * sign
            number += 1
            sign = -sign
    else:
        for number in range(2, top):
            yield number * sign
            sign = -sign


def main():
    list_ = list(gen_series(100))
    print(list_)

main()


It's not the shortest, but it's pretty clear what's going on, and
gen_series() is reusable.


On Sun, Jan 4, 2015 at 3:34 AM, flebber <flebber.crue at gmail.com> wrote:
> In repsonse to this question: Write a program that prints the first 100 members of the sequence 2, -3, 4, -5, 6, -7, 8.
>
> This is my solution it works but ugly.
>
> series = range(2,100)
> # answer = [(x,(y* -1)) for x, y in series[::2]]
> # print(answer)
> answer = []
> for item in series:
>     if item % 2 != 0:
>         answer.append(item * -1)
>     else:
>         answer.append(item)
>
> print(answer)
>
> I know I should be better off doing this with map but cannot get it to work. I understand also that map returns a generator so this solution should only working in python2(correct me please if I am wrong).
>
> In [6]: map?
> Type:       builtin_function_or_method
> String Form:<built-in function map>
> Namespace:  Python builtin
> Docstring:
> map(function, sequence[, sequence, ...]) -> list
>
> Just getting something wrong
> list(map((lambda x: x * -1 if (x%2 != 0)), series))
> --
> https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list