Reputation: 379
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.
Upvotes: 24
Views: 12089
Reputation: 297
Here's one of my personal favorites:
number = 20
even, odd = 0, 0
for i in range(number):
# use bitwise operators to decide if lsb is 1 (odd) or 0 even
even += (i&1 == 0) * i
odd += (i&1 == 1) * i
print("even:", even, "odd:", odd)
Output:
even: 90 odd: 100
Upvotes: 0
Reputation: 21
number = 1000000
x = 0
y = 0
[(x:=x+n, y:=y+(n+1)) for n in range(0,number,2)]
print(f'{x}, {y}')
This uses a list comprehension and the new Python assignment operator.
Upvotes: 2
Reputation: 628
There's another way which sums the odd and even indices together in the for loop based on the remainder modulo 2:
number = int(input())
odd = 0
even = 0
for i in range(len(number)):
odd += i * (i % 2)
even += i * ((i + 1) % 2)
print (odd, even)
Upvotes: 2
Reputation: 4445
If you're allowed to use a list
number = int( input() )
counts = [ 0, 0 ]
for n in range( number ):
counts[ n % 2 ] += n
print( counts[ 0 ] )
print( counts[ 1 ] )
Upvotes: 2
Reputation: 9681
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?
input()
function returns a str
object, which is converted into an integer using the int()
function.range()
and list()
functions to convert the given number into a list of values within that range.
sum()
function to get the sums.Upvotes: 17
Reputation: 82889
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
.
Upvotes: 11
Reputation: 10624
Here is my 2cents if we are allowed to use numpy.
import numpy as np
number = int(input())
l = np.array(range(number))
print('odd:',sum(l % 2 * l))
print('even:', sum((1- l % 2) * l))
Upvotes: 3
Reputation: 2214
There is also mathematical way:
num = int(input("Enter number:"))
odd = ((num+1)/2)**2
even = num*(num+1)/2 - odd
The sum of the first n odd numbers is n^2. To get count of odd numbers we use (num+1)/2
. To get sum of even numbers, we could use similar approach, but I preferred, subtracting odd
from the sum of the first n numbers, which is n*(n+1)/2.
Upvotes: 7
Reputation: 380
I think you are a beginner. I wouldn't like to confuse you with slicing operators complex implementation.
As you mentioned
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.
There is no need to find the initial number is odd/even And your program is wrong if you want to include the input number in calculating the even/odd sum.
Example
Input
5
Expected Output
6 9
Explanation
Even Sum : 2+4 = 6
Odd Sum : 1+3+5 = 9
Your Output
6 4 (wrong output)
The range() function will exclude the number. It will only iterate from 0 to 4 while the input is 5. so if you want to include 5, you should add 1 to the number while passing it in the range() function.
number = int(input())
x = 0
y = 0
for n in range(number+1):
x += (1 - n % 2) * n #this will add 0 if not even
y += (n % 2) * n #this will add 0 if not odd
print(x)
print(y)
Upvotes: 4
Reputation: 133
Sum of first n numbers is n(n+1)/2 (Mathematically derived). So if we know the value of n then we can find the sum of all numbers from 1 to n.
If we find the sum of all odd numbers before n and subratract it from the sum of first n we get he sum of all even numbers before n.
Here's the code:
n = int(input("Enter a number: "))
odd = 0
for i in range(1,n+1,2):
odd += i
even = int(n*(n+1)/2) - odd
print("even:",even,"odd:",odd)
Upvotes: 1
Reputation: 360
Ternary operator:
for n in range(number):
x += (n,0)[n%2]
y += (0,n)[n%2]
Upvotes: 4
Reputation: 49
for n in range(1,number,2):
x += n
y += n-1
print(y)
print(x)
This code has the same output with the example.
Upvotes: 4