Sum input integer by itself, integer times - python

Salam, I'm given a user input that I have to sum it by itself n-times. Which means if the input is "5" for example, I should return 5 + 5 + 5 + 5 + 5 = 25
I used:
def sum(user_input):
inp_sum = 0
string = ''
for n in range(0, user_input, 1):
inp_sum += user_input
if n != user_input -1:
string+= "5 + "
else: string += '5'
return string + ' = ' + str(inp_sum)
but it returns
Failed for value=6
Expected: 6 + 6 + 6 + 6 + 6 + 6 = 36
Actual: 5 + 5 + 5 + 5 + 5 + 5 = 36
what is the solution?

You hardcoded 5 in to the logic of your function, when you should be passing in the user input to the string format logic. Also, do not name your function sum as you will shadow the built-in function sum.
def mysum(user_input):
inp_sum = 0
string = ""
for n in range(0, user_input, 1):
inp_sum += user_input
if n != user_input - 1:
string += "{} + ".format(user_input)
else:
string += str(user_input)
return "{} = {}".format(string, inp_sum)

You can simplify it like this:
def user_input(n):
return "{} = {}".format(' + '.join([str(n) for _ in range(n)]), str(n*n))
print(user_input(5))
# 5 + 5 + 5 + 5 + 5 = 25
print(user_input(6))
# 6 + 6 + 6 + 6 + 6 + 6 = 36

Related

How to write Python program with output like this: Limit: 18 The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

My code looks like this at the moment:
limit = int(input("Limit:"))
number = 1
sum = 1
while sum < limit:
number = number + 1
sum = sum + number
print(f"The consecutive sum:{sum}")
Add the numbers you're using in a separate list. Then use str.join() to join these numbers with a ' + '.
limit = int(input("Limit:"))
number = 1
total = number
numbers = [str(number)]
while total < limit:
number = number + 1
total = total + number
numbers.append(str(number)) # Need to convert to string here because str.join() wants a list of strings
print(f"The consecutive sum: {' + '.join(numbers)} = {total}")
Which prints the required output:
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
limit = int(input("Limit:"))
number = 1
sum = 1
print("The consecutive sum: 1", end = " ")
while sum < limit:
number += 1
sum += number
print(f'+ {number}', end = " ")
print(f'= {sum}')
Output Will Be:
Limit:18
The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21

how does result = k + tri_recursion(k-1) give me an output of triangular numbers?

I'm currently learning about functions and I came across a recursions example on w3schools.com. This code is giving me a list of triangular numbers for an argument k > 0. My question is how exactly is it printing out a list of triangular numbers with "result" defined as result = k + tri_recursion(k-1) in the body of the code. The output for an input of k = 6, for example, gives me 1, 3, 6, 10, 15, 21 but I just don't understand how I'm getting a list of triangular numbers from such a simple setting of the return variable. Help would be much appreciated :)
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
you need create a list to storage numbers:
tri_list = []
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k-1)
tri_list.append(result)
print(result)
else:
result = 0
return result
print("\n\nexample result")
tri_recursion(6)
print(tri_list)
Then you have:
k = 6
6 + tri_recursion(5)
5 + tri_recursion(4)
4 + tri_recursion(3)
3 + tri_recursion(2)
2 + tri_recursion(1)
1 + tri_recursion(0)
1 + 0 = 1
2 + 1 = 3
3 + 3 = 6
4 + 6 = 10
5 + 10 = 15
6 + 15 = 21
This happens because you are printing the sum of the previous numbers in each return of each recursion

multiplication table python nested loop not printing full table

This is my code for my multiplication table so far. I am a bit confused as to how to continue to finish this problem, basically I need to be able to print a multiplication table with this format for any number between 1 and 9:
1 2 3 4 5
--------------------------
1| 1 2 3 4 5
2| 2 4 6 8 10
3| 3 6 9 12 15
4| 4 8 12 16 20
5| 5 10 15 20 25
x = int(input("enter a number 1-9: "))
output = ""
for x in range(1 ,x+1):
output +=str(x) +"|\t"
for y in range(1,x+1):
output += str(y * x) +"\t"
output +="\n"
print(output)
You are replacing the value of x in the loop, instead you should use a different name for looping parameter:
output = ' '.join([f" {i}" for i in range(1, x+1)]) + "\n"
output += '---' * x + "\n"
for i in range(1, x+1):
output += str(i) + "| "
for y in range(1, x+1):
output += str(y * i) + " "
output += "\n"
Your loop variable should have a different name, other than x. The value of x is getting overwritten by the loop values. Your code should look like this
for i in range(1, x + 1):
output += str(i) + "| "
for y in range(1, x + 1):
output += str(y * i) + " "
output += "\n"
you have to take care also of the padding in order to have a good output, also in your first loop you have to change the name of the variable used for iteration:
x = int(input("enter a number 1-9: "))
sep = ' '
sep_len = len(sep)
output = ' ' + sep + sep.join(str(e).rjust(sep_len, ' ') for e in range(1, x + 1))
output += '\n' + '_' * len(output)
for i in range(1 , x + 1):
output += "\n" + str(i) + '|'
for y in range(1, x + 1):
output += sep + str(y * i).rjust(sep_len, ' ')
print(output)
output (for x = 5):
1 2 3 4 5
__________________________________________
1| 1 2 3 4 5
2| 2 4 6 8 10
3| 3 6 9 12 15
4| 4 8 12 16 20
5| 5 10 15 20 25

Trying to outputting a math equation with for loop in python

So I have changeable sized list with integers in it like [2,5,6,9,1] and I am trying to create an addition formula with for loop:
z= 1
while z > 0:
for i in range(len(list)):
print(list[i],"+", end=" ")
z = 0
print("=",sum(list),end=" ")
This is what i am trying and output is:
2 + 5 + 6 + 9 + 1 + = 23
What should I do if I want to output n integers and n-1 plus signs between integers?
You may use str.join that accept an iterable of strings. You need to map each int to str then join them using the + and print the result
values = [2, 5, 6, 9, 1]
formula = " + ".join(map(str, values))
print(formula, "=", sum(values)) # 2 + 5 + 6 + 9 + 1 = 23
# Using f-strings
formula = f'{" + ".join(map(str, values))} = {sum(values)}'
print(formula)
Use join:
def printfn(alist):
expr = " + ".join((map(str, alist)))
sum_val = sum(alist)
print("{} = {}".format(expr, sum_val))
a = [1,2,3]
printfn(a)
# 1 + 2 + 3 = 6
b = [1,2,3,4]
printfn(b)
# 1 + 2 + 3 + 4 = 10
Another possibility is to use sep= parameter of print() function.
For example:
lst = [2,5,6,9,1]
print(*lst, sep=' + ', end=' ')
print('=', sum(lst))
Prints:
2 + 5 + 6 + 9 + 1 = 23
You can use enumerate(), starting with an index of 1
>>> l= [2,5,6,9,1]
>>> s = ''
>>> sum_ = 0
>>> for i, v in enumerate(l, 1):
if i == len(l):
# If the current item is the length of the list then just append the number at this index, and the final sum
s += str(v) + ' = ' + str(sum_)
else:
# means we are still looping add the number and the plus sign
s += str(v)+' +
>>> print(s)
2 + 5 + 6 + 9 + 1 = 23
Make the for loop in range( len(list)-1 ) and add a print (list[len(list)-1]) before z=0
list = [2,5,6,9,1]
z= 1
while z > 0:
for i in range( len(list)-1 ):
print(list[i],"+", end=" ")
print (list[len(list)-1],end=" ")
print("=",sum(list),end=" ")
z = 0

Python, starting a new line after end = " "

Currently, I have this code:
for i in range(lower_limit, upper_limit+1):
for j in range(0,len(prime_number)):
for k in range(0 + j,len(prime_number)):
if i == prime_number[j] + prime_number[k] and i % 2 == 0:
print(i, "=", prime_number[j], "+", prime_number[k])
which prints:
10 = 3 + 7
10 = 5 + 5
12 = 5 + 7
14 = 3 + 11
14 = 7 + 7
I need the result to look like:
10 = 3 + 7 = 5 + 5
12 = 5 + 7
14 = 3 + 11 = 7 + 7
I know I have to use end = " " somehow, but then it prints all the numbers in just one line. What do I do?
Use end= " ", and an empty print() at the end of the outer loop to end the line.
For example:
>>> for i in range(3):
... print("foo", end = " ")
... print("bar", end = " ")
... print()
...
foo bar
foo bar
foo bar
Specifically for your case:
for i in range(lower_limit, upper_limit+1):
print(i, end = " ")
for j in range(0,len(prime_number)):
for k in range(0 + j,len(prime_number)):
if i == prime_number[j] + prime_number[k] and i % 2 == 0:
print("=", prime_number[j], "+", prime_number[k],end = " ")
print()

Categories

Resources