Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum even and odd values with one for-loop and no if-condition?

I am taking a programming class in college and one of the exercises in the problem sheet was to write this code:

number = int(input())
x = 0
y = 0
for n in range(number):
    if n % 2 == 0:
        x += n
    else:
        y += n
print(x)
print(y)

using only one "for" loop, and no "while" or "if".

The purpose of the code is to find the sum of the even and the sum of the odd numbers from zero to the number inputted and print it to the screen.

Be reminded that at this time we aren't supposed to know about functions.

I've been trying for a long time now and can't seem to find a way of doing it without using "if" statements to know if the loop variable is even or odd.

like image 857
Rui Coito Avatar asked Nov 26 '20 08:11

Rui Coito


Video Answer


3 Answers

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

Output:

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?

  • The input() function returns a str object, which is converted into an integer using the int() function.
  • The integer is wrapped in the range() and 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.
like image 68
S3DEV Avatar answered Oct 24 '22 04:10

S3DEV


for n in range(number):
    x += (1 - n % 2) * n
    y += (n % 2) * n
like image 13
delta Avatar answered Oct 24 '22 04:10

delta


You asked for a solution with one loop, but how about a solution with no loop?

It is well known that the sum of the numbers from 1 to n is (n+1)*n/2. Thus, the sum of even numbers is 2 * (m+1)*m/2 with m = n//2 (i.e. floor(n/2)). The sum of odd can then be calculated by the sum of all numbers minus the sum of even numbers.

n = 12345
m = n // 2
e = (m+1)*m
o = (n+1)*n//2 - e

Verification:

>>> e, e==sum(i for i in range(n+1) if i % 2 == 0)
38112102 True
>>> o, o==sum(i for i in range(n+1) if i % 2 == 1)
38105929 True

Note: This calculates the sums for number up to and including n.

like image 11
tobias_k Avatar answered Oct 24 '22 03:10

tobias_k