Reputation: 673
I am learning Python and I am trying out some exercises. I am trying to sum all the odd numbers from 0 to 9 using list comprehension, for and if in one line.
I tried the following code:
for idx in range(10): s = 0 if idx == 0 else s = [(i % 2) for i in range(10)][idx] * range(10)[idx] + s
but I get the following error:
SyntaxError: can't assign to conditional expression
I don't quite understand it.
Your advice will be appreciated.
Upvotes: 2
Views: 8482
Reputation: 1
numbers = range(0, 10)
def addOddNumbers(numbers):
for num in numbers:
if num % 2 == 1:
return sum
print sum(numbers)
if __name__ == '__main__':
addOddNumbers(numbers)
Upvotes: 0
Reputation: 7091
This is how you may do it
sum([x for x in range(1,10,2)])
Explaining why your code failed
Here is your code as given in the question
for idx in range(10):
s = 0 if idx == 0 else ([(i % 2) for i in range(10)][idx] * range(10)[idx] + s)
in the else
part you may give the value to be assigned to s ie, s=
is not required.You may re-write it as
for idx in range(10):
s = 0 if idx == 0 else ([(i % 2) for i in range(10)][idx] * range(10)[idx] + s)
The expression syntax for ternary operator in python is as follows
condition_is_true if condition else condition_is_false
Eg usage
value1 = 10
value2 = 20
a = 3
b = 4
value = value1 if a > b else value2
print value
#20
Upvotes: 3
Reputation: 140168
very short oneliner:
sum(range(1,10,2))
but the real formula is for any n
:
((n+1)//2)**2
With that one, you're able compute the sum for a very big n
very quickly.
Back to the point, you cannot accumulate using a list comprehension, or it's very difficult/hacky to do, so sum
is required here. So the most logical if requirements are "use a comprehension notation and an if" is:
sum(x for x in range(1,10) if x % 2)
Note that there's no need to put an extra []
in that case. It's a generator comprehension (avoids generating an extra list
, sum
doesn't need to have all the info at once.
Upvotes: 7
Reputation: 73
you can one line it this reduce
reduce(lambda x,y: x+y if y%2 != 0 else x ,range(10))
output
25
Upvotes: 1
Reputation: 6762
you can do this ..
a = range(0,10)
b = sum([x for x in a if x%2 != 0])
print b
output :
25
Upvotes: 0
Reputation: 1146
You can try this:
sum([x for x in range(10) if x % 2 != 0])
First you create a list of number from 0 to 9 with range
, then you create the list (list comprehension) of the odd numbers (using if x % 2
). Finally, you sum the contents of the array using sum
.
Upvotes: 2