How to sum even and odd values with one for-loop and no if-condition?
for n in range(number): x += (1 - n % 2) * n y += (n % 2) * n
Purely for educational purposes (and a bit of fun), here is a solution that does not use any
for loops at all. (Granted, in the underlying logic of the functions, there are at least five loops.)
num = list(range(int(input('Enter number: ')))) even = num[::2] odd = num[1::2] print('Even list:', even) print('Odd list:', odd) print('Even:', sum(even)) print('Odd:', sum(odd))
Enter number: 10 Even list: [0, 2, 4, 6, 8] Odd list: [1, 3, 5, 7, 9] Even: 20 Odd: 25
How does it work?
input()function returns a
strobject, which is converted into an integer using the
- The integer is wrapped in the
list()functions to convert the given number into a list of values within that range.
- This is a convention you will use/see a lot through your Python career.
- List slicing is used to get every second element in the list. Given the list is based at zero, these will be even numbers.
- Slice the same list again, starting with the second element, and get every second element ... odd numbers.
- Link to a nice SO answer regarding slicing in Python.
- The simply use the
sum()function to get the sums.