python how to sum odd numbers in a range? [duplicate] - python

This question already has answers here:
Adding odd numbers in a list
(6 answers)
Closed 5 years ago.
I want to sum my odd numbers, so if I enter num=7 or 8 it counts: 1, 3, 5, 7 : Correct, but I want to sum them. So the answer for 7 and 8 should be 16 (1 + 3 + 5 + 7 = 16)
Or if I enter num=9 then I expect 1 + 3 + 5 + 7 + 9 = 25
I must use While for this calc.
num = int(input("Insert number: "))
sum = 1
num += 1
while sum < num:
print(sum)
sum = sum + 2

You can use the built-in sum() function like this:
num = int(input("Insert number: "))
s = sum(range(1, num+1, 2))
range() takes start (inclusive), end (exclusive), and step (In our case: start=1, end=num+1 and step=2)
Output:
>>> num = 9
>>> s = sum(range(1, num+1, 2))
>>> s
25
If using while is a requirement, then you can achieve the same result with:
>>> s = 0
>>> i = 1
>>> while i < num + 1:
... if i % 2: # Or: i % 2 != 0, which means we only consider odd nums
... s += i
... i += 1
...
>>> s
25

Related

How can i calculate and print the sum of first N elements of below sequence using recursive function

How can i calculate and print the sum of first N elements of below sequence using recursive function
Example:
Sample Input N: 4
Sample Output: 7 + 12 + 17 + 22 = 58
I did some part of the code but it gives wrong result and I don't know where I'm making mistakes. That's why I need help!
def recur_sum(n):
if n <= 1:
return n
else:
for i in range(7,n+1):
return i + recur_sum(i-1)
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
As far as I understand your question, you want the sum of a sequence which each element of this sequence is increased by a step (such as 5), and it has an initial value (like 7), and you want the sum of first N (like 4) elements of this sequence.
At each recursion level, we add the current value to step , but when n == 1 we only return the current value (which is the Nth item of the sequence).
Do this:
def recur_sum(cur_val, step, n):
if n == 1:
return cur_val
return cur_val + recur_sum(cur_val+step,step,n-1)
num = int(input("Enter a number: "))
init_val = 7
step = 5
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(init_val, step, num))
Output:
The sum is 58
this returns a list of all sequential numbers starting at 7 each increment of 5. sum the return array.... change 5 and 2 to change increments for desired jumps/steps, and change the initial return value..
def recur_sum(n):
if n == 1:
return [7]
else:
return [5*n+2] + recur_sum(n-1)
num = int(input("Enter a number: "))
res = recur_sum(num)
print(sum(res))
A recursive function which returns all the elements up to n (where n is the input of your function) has already been proposed above.
In my understanding, you want a function with some recursive logic that return the sum of all the elements up to the n-th.
Your sequence is 7, 12, 17, 22, 27 and so forth. If we disect it:
it element sum sum is element is
1 7 7 1 * 7 + 0 * 5 1 * 7 + 0 * 5
2 12 19 2 * 7 + 1 * 5 1 * 7 + 1 * 5
3 17 36 3 * 7 + 3 * 5 1 * 7 + 2 * 5
4 22 58 4 * 7 + 6 * 5 1 * 7 + 3 * 5
5 27 85 5 * 7 + 10 * 5 1 * 7 + 4 * 5
If you want at any cost to implement a recursive solution, if is evident that at each step you need to increase the rolling sum by it * 7 + (it - 1) * 5 (where 7 is your start point, while 5 is your step).
You can implement a recursive solution as follows:
def recursive(n, step = 5, start = 7, counter = 1):
if n > 0:
this_element = start + (counter - 1) * step
if counter == n:
return this_element
else:
return this_element + recursive(n, step = step, start = start, counter = counter + 1)
else:
return 0
for i in range(1, 10):
print(recursive(i))
OUTPUT
7
19
36
58
85
117
154
196
243
From the table above you can see though that maybe a recursive solution is overkilling here given that the sum of elements up to n-th step has solution:
def my_sum(n, step = 5, start = 7):
return n * start + int(step * (n - 1) * n / 2)
for i in range(1, 10):
print(my_sum(i))
OUTPUT
7
19
36
58
85
117
154
196
243

Python. How do i count the number of divisors in nested for loop?

I have a code that generates triangular numbers, calculates the divisors for each triangular number and prints out 3 columns where the first column is the input numbers, the second column is the triangular numbers and the third column is the divisors of each triangular number. How can I count the number of divisors of each triangular number(count the numbers in the third column)?
for num in range(10):
triangle_number = num*(num+1)//2
print(num, end = ' ')
print(triangle_number, end = ' ')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
print()
Output looks like this:
0 0
1 1 1,
2 3 1,3,
3 6 1,2,3,6,
4 10 1,2,5,10,
5 15 1,3,5,15,
6 21 1,3,7,21,
7 28 1,2,4,7,14,28,
8 36 1,2,3,4,6,9,12,18,36,
9 45 1,3,5,9,15,45,
You can add a variable inside for loop and increment it when you get the divisor and print a the end.
for num in range(10):
count = 0
triangle_number = num*(num+1)//2
print(num, end = '\t')
print(triangle_number, end = '\t')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
count += 1
print("\t", count)
##Output:
##0 0 0
##1 1 1, 1
##2 3 1,3, 2
##3 6 1,2,3,6, 4
##4 10 1,2,5,10, 4
##5 15 1,3,5,15, 4
##6 21 1,3,7,21, 4
##7 28 1,2,4,7,14,28, 6
##8 36 1,2,3,4,6,9,12,18,36, 9
##9 45 1,3,5,9,15,45, 6
##Output order : input number, count of divisors divisors, triangular number
or you can create a list of divisors and measure length before printing.
for num in range(10):
divisors = []
triangle_number = num*(num+1)//2
print(num, end = '\t')
print(triangle_number, end = '\t')
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
divisors.append(divisor)
print(len(divisors), "\t", ",".join(str(div )for div in divisors))
##Output:
##0 0 0
##1 1 1 1
##2 3 2 1,3
##3 6 4 1,2,3,6
##4 10 4 1,2,5,10
##5 15 4 1,3,5,15
##6 21 4 1,3,7,21
##7 28 6 1,2,4,7,14,28
##8 36 9 1,2,3,4,6,9,12,18,36
##9 45 6 1,3,5,9,15,45
##Output order : input number, triangular number, count of divisors divisors
You might replace your inner for loop using list comprehension and then just get length of that list using len function, that is replace:
for divisor in range(1, triangle_number+1):
if triangle_number%divisor == 0:
print(divisor, end = ',')
with:
divisors = [divisor for divisor in range(1, triangle_number+1) if triangle_number%divisor == 0]
print(*divisors, sep=',', end=' ')
print(len(divisors), end='')
list comprehension is succint way of creating list which might be created via appending inside for loop, * (star operator) does unpacking, if you would have list x = [1, 2, 3] then print(*x) is equivalent of print(1, 2, 3) and so on.

How to write the following pattern

I am trying to print the following pattern in python but am not getting the desired output :
0
2 2
4 4 4
6 6 6 6
I have already used the following code but am not getting the desired output
n = int (input("Enter number : "))
for i in range (n):
print (i *2 )
Try this:
n = int (input("Enter number : "))
for i in range (n):
print (' '.join([str(i * 2) for _ in range(i + 1)]) )
You need to print the number i+1 times.
for i in range (n):
for _ in range(i+1):
print (i * 2," ", end='') # print without newlines
print() # end the line
Following simple code could help:
n = int (input("Enter number : "))
j = 1
k = 0
for i in range(n):
s = str(k)+' '
print(s*j)
j += 1
k += 2
if n = 4, then it would print the following :
0
2 2
4 4 4
6 6 6 6
n = int (input("Enter number : "))
count = 1
for i in range (n):
res = str(i*2) + " "
print (res * (i+1))
print n

logic errors with print the sum of all the numbers that are either multiple of three or five

I'm having some logic errors with my program. I've been trying to solve this for the last couple of hours. It's supposed to print the sum of all the numbers that are either multiple of three or five.
my output
1.)enter an integer number (0 to end): enter an integer number (0 to end):
2.)enter an integer number (0 to end): 3+ = 3
expected output
1.)enter an integer number (0 to end): 3 = 3
2.)enter an integer number (0 to end): 3+5 = 8
below is my code.
while True:
answer = ""
num = int(input("enter an integer number (0 to end): "))
end_answer = 0
if num == 0:
exit()
for i in range(1, num+1):
if i%3==0 or i%5==0 :
answer += str(i)
end_answer += i
if i != num and (i%3==0 or i%5==0):
answer += "+"
print(str(answer) + " = " + str(end_answer) )
I've seen similar answers for this just not in python specifically
The following (properly indented) code will give you what you need:
while True:
num = int(input('Enter an integer number (0 to end): '))
if num == 0: exit()
answer = ''
end_answer = 0
sep = ''
for i in range(1, num+1):
if i % 3 == 0 or i % 5 == 0 :
answer += sep + str(i)
sep = ' + '
end_answer += i
if end_answer > 0:
print(str(answer) + ' = ' + str(end_answer) )
Note that it uses a variable separator sep to more cleanly print the item you're working out. A sample run follows:
Enter an integer number (0 to end): 2
Enter an integer number (0 to end): 3
3 = 3
Enter an integer number (0 to end): 10
3 + 5 + 6 + 9 + 10 = 33
Enter an integer number (0 to end): 38
3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20 + 21 + 24 + 25 + 27 + 30 + 33 + 35 + 36 = 329
Enter an integer number (0 to end): 0
You can simplify your code a lot by using the sum builtin and f-strings for printed text formatting. This will likely be more efficient as well.
Code
from itertools import count
counter = count(1)
while True:
num = int(input(f'{next(counter)}). Enter an integer number (0 to end): '))
if num == 0:
break
nums = [x for x in range(1, num + 1) if x % 3 == 0 or x % 5 == 0]
print(f'{" + ".join(map(str, nums))} = {sum(nums)}')
Output
1). Enter an integer number (0 to end): 3
3 = 3
2). Enter an integer number (0 to end): 9
3 + 5 + 6 + 9 = 23
3). Enter an integer number (0 to end): 15
3 + 5 + 6 + 9 + 10 + 12 + 15 = 60
4). Enter an integer number (0 to end): 0

Python times table using while

Why in python a times table program doesn't work like this?
n = int(input("Type a number: "))
count = 10
while count < 0:
print(f"{count} x {n} = {n * count}")
count = count - 1
But this works correctly:
n = int(input("Type a number: "))
for i in range(1, 11):
print(f"{i} x {n} = {n * i}")
The result is (or should be), for example:
1 x 5 = 5
2 x 5 = 10
3 x 5 = 15
4 x 5 = 20
5 x 5 = 25
6 x 5 = 30
7 x 5 = 35
8 x 5 = 40
9 x 5 = 45
10 x 5 = 50
As a beginner I need to understand... and is it possible to use while in that situation?
This is python 3.x
You want to start count from 1 so that your loop increments rather than decrements. Your while loop conditional check is also incorrect as count is never less than 0. Try this:
n = int(input("Type a number: "))
count = 1
while count <= 10:
print(f"{count} x {n} = {n * count}")
count = count + 1
You need to set the condition in the while to be true to go through the loop. Thus we will say do while count is greater than or equal to zero.
n = int(input("Type a number: "))
count = 10
while count >= 0:
print(f"{count} x {n} = {n * count}")
count = count - 1

Categories