Ask Your Question

Strange behaviour

asked 2013-07-05 11:38:03 -0600

PerAlexandersson gravatar image

updated 2013-07-05 23:34:55 -0600

tmonteil gravatar image

I am new to Sage, so please help me understand the following: How come

map(lambda x: mod(x,2),[4,3,2,1,1])

returns the perfectly sane answer [0,1,0,1,1]

but trying to compute the sum

sum(map(lambda x: mod(x,2),[4,3,2,1,1]))

gives the value 1, and not 3. Somehow, it seems that sage thinks that I wish to apply the inner lambda again on the result of the sum.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-07-05 13:07:06 -0600

fidbc gravatar image

You can try

map(lambda x: x%2,[4,3,2,1,1])


sum(map(lambda x: x%2,[4,3,2,1,1]))

will return the desired output.

What happens when you use mod(x,2) is that sage returns an element of $\mathbb{Z}_2$, however the % operator returns an Integer.

edit flag offensive delete link more


To put it another way, that means that the sum of `mod(x,2)` being either zero or one is a feature, not a bug!

kcrisman gravatar imagekcrisman ( 2013-07-05 14:14:52 -0600 )edit

I would prefer comprehension sum(x%2 for x in [4,3,2,1,1]) rather than map.

vdelecroix gravatar imagevdelecroix ( 2013-07-06 04:16:55 -0600 )edit

Aha! Cool! That makes sense.

PerAlexandersson gravatar imagePerAlexandersson ( 2013-07-06 05:08:31 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-07-05 11:38:03 -0600

Seen: 129 times

Last updated: Jul 05 '13