Ask Your Question
0

Strange behaviour

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

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

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
4

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

fidbc gravatar image

You can try

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

then

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

Comments

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 -0500 )edit
1

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 -0500 )edit

Aha! Cool! That makes sense.

PerAlexandersson gravatar imagePerAlexandersson ( 2013-07-06 05:08:31 -0500 )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

Stats

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

Seen: 56 times

Last updated: Jul 05 '13