On 1/5/2015 6:33 AM, flebber wrote:
You could do what mathematicians do when they deal with alternating signs: they raise -1 to the power of the index to get an appropriate multiplier. >>> [ n * (-1) ** n for n in range(10) ] [0, -1, 2, -3, 4, -5, 6, -7, 8, -9]
Mathematicians operating in the timeless Platonic universe of mathemtical forms are not concerned with such droll issues as computation time. I think most regard '(-1)**n' as an abbreviation for '(-1 if odd(n) else 1)', where odd(n) is regarded as an O(1) operation, not as an indication to actually raise -1 to an arbitrarily large power. which could take an arbitrarily long time.
Or you could do here what you attempt to do with map below. See below.You are trying to use a binary expression. There are no binary expressions. Add an else branch to make it ternary: lambda x : x if x % 2 == 0 else -x But never mind the number of branches, the serious point is that you didn't specify a value for when the condition is not true. It doesn't make sense without that. There's nothing wrong with a list comprehension, or the corresponding generator expression if you want a generator. It's fine. Map's fine.Thanks Jussi I really like the multiplier solution.
-- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
