Ask Your Question
0

Strange behaviour

asked 2013-07-05 18:38:03 +0100

PerAlexandersson gravatar image

updated 2013-07-06 06:34:55 +0100

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 20:07:06 +0100

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 21:14:52 +0100 )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 11:16:55 +0100 )edit

Aha! Cool! That makes sense.

PerAlexandersson gravatar imagePerAlexandersson ( 2013-07-06 12:08:31 +0100 )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 18:38:03 +0100

Seen: 770 times

Last updated: Jul 05 '13