Processing math: 100%
Ask Your Question
0

Strange behaviour

asked 11 years ago

PerAlexandersson gravatar image

updated 11 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
4

answered 11 years ago

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 Z2, however the % operator returns an Integer.

Preview: (hide)
link

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 ( 11 years ago )
1

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

vdelecroix gravatar imagevdelecroix ( 11 years ago )

Aha! Cool! That makes sense.

PerAlexandersson gravatar imagePerAlexandersson ( 11 years ago )

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: 11 years ago

Seen: 900 times

Last updated: Jul 05 '13