Python, starting a new line after end = " " - python

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

Related

Sum input integer by itself, integer times

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

Finding all unique values that add up to specific target value

Is there a more Pythonic way to find all combinations of numbers (each combination is made up of unique numbers) that add up to a specific target number. For example:
largest_single_number = 9 # in this example: single digits only
num_of_inputs = 5
target_sum = 30
# expected output:
0 + 6 + 7 + 8 + 9 = 30
1 + 5 + 7 + 8 + 9 = 30
2 + 4 + 7 + 8 + 9 = 30
2 + 5 + 6 + 8 + 9 = 30
3 + 4 + 6 + 8 + 9 = 30
3 + 5 + 6 + 7 + 9 = 30
4 + 5 + 6 + 7 + 8 = 30
number of possibilities: 7
The code we have looks like this:
counter = 0
largest_single_number = 9 # in this example: single digits only
num_of_inputs = 5 # Not used but dictates number of nested loops
target_sum = 30
for digit_1 in range(largest_single_number + 1):
for digit_2 in range(digit_1 + 1, largest_single_number + 1):
for digit_3 in range(digit_2 + 1, largest_single_number + 1):
for digit_4 in range(digit_3 + 1, largest_single_number + 1):
for digit_5 in range(digit_4 + 1, largest_single_number + 1):
if (
digi_sum := (digit_1 + digit_2 + digit_3 + digit_4 + digit_5)
) == target_sum:
print(
f"{digit_1} + {digit_2} + {digit_3} + {digit_4} + {digit_5} = {target_sum}"
)
counter += 1
elif digi_sum > target_sum:
break
print("number of possibilities: ", counter)
We would appreciate knowing what's a more Pythonic way to achieve the SAME RESULT.
Use itertools.combinations
Check the equality in a List Comprehensions
from itertools import combinations
values = [x for x in combinations(range(10), 5) if sum(x) == 30]
print(len(values))
>>> 7
print(values)
[(0, 6, 7, 8, 9),
(1, 5, 7, 8, 9),
(2, 4, 7, 8, 9),
(2, 5, 6, 8, 9),
(3, 4, 6, 8, 9),
(3, 5, 6, 7, 9),
(4, 5, 6, 7, 8)]
To get your expected output
for x in values:
expected = ' + '.join(map(str, x)) + ' = 30'
print(expected)
0 + 6 + 7 + 8 + 9 = 30
1 + 5 + 7 + 8 + 9 = 30
2 + 4 + 7 + 8 + 9 = 30
2 + 5 + 6 + 8 + 9 = 30
3 + 4 + 6 + 8 + 9 = 30
3 + 5 + 6 + 7 + 9 = 30
4 + 5 + 6 + 7 + 8 = 30
As a function
def calculation(largest: int, number: int, target: int) -> list:
values = [x for x in combinations(range(largest + 1), number) if sum(x) == target]
print(f'number of possibilites: {len(values)}')
for x in values:
print(' + '.join(map(str, x)) + f' = {target}')
calculation(9, 5, 30)
number of possibilites: 7
0 + 6 + 7 + 8 + 9 = 30
1 + 5 + 7 + 8 + 9 = 30
2 + 4 + 7 + 8 + 9 = 30
2 + 5 + 6 + 8 + 9 = 30
3 + 4 + 6 + 8 + 9 = 30
3 + 5 + 6 + 7 + 9 = 30
4 + 5 + 6 + 7 + 8 = 30
Here's a 1-liner (not counting the import):
from itertools import combinations
print("number of possibilities ",len([s for s in combinations(range(largest_single_number+1), num_of_inputs) if sum(s)== target_sum]))
I'll leave printing the individual sets as an exercise.
I would probably use itertools.combinations
possibilities = [combo for combo in
itertools.combinations(range(largest_single_number+1), num_of_inputs))
if sum(combo) == target_sum]

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

Creating number patterns in python

I am trying to create 2 patterns of similar type (in python):
1
2 2
3 3 3
and
1
2 3
4 5 6
up to a length specified by the user
I have written a code to print the pattern of the 1st type:
def rec1():
for i in range(0,n,1):
count=i
print(" "*(n-i) + str(i+1) + " ",end=" ")
if count!=0:
rec2(i+1)
else:
print("\n")
def rec2(x):
print(str(x) + " ",end=" ")
count=count-1
if count>0:
rec2(x)
else:
print("\n")
return
count=0
n=int(input("Number?"))
rec1()
However i am getting the following error:
Number?5
1
2 2 *Traceback (most recent call last):
File "C:/Python34/pattern1.py", line 33, in <module>
rec1()
File "C:/Python34/pattern1.py", line 18, in rec1
rec2(i+1)
File "C:/Python34/pattern1.py", line 24, in rec2
count=count-1
UnboundLocalError: local variable 'count' referenced before assignment*
Can anyone provide a more efficient code?
Try this:
def rec1(n):
for i in range(1,n+1,1):
s = ""
s += (" "*(n-i))
for j in range(0,i,1):
s += (str(i) + " ")
print(s)
n=int(input("Number?"))
rec1(n)
You don't need rec2
The following is another approach to generate the first and second pattern:
def generate(n, flag = 0):
""" n: number; 0 is 1st pattern; 1 is 2nd pattern """
g = [range(1,n+2)[i*(i+1)/2:i*(i+1)/2 +i+1] for i in range((n+2)/2-1)] if flag else \
[ (i,)*i for i in range(1, n+1)]
return [' '* range(1,len(g)+1)[::-1][i] + ' '.join([str(j) for j in g[i]]) for i in range(len(g))]
for t in generate(6, 0): print t # 1st pattern
for t in generate(6, 1): print t # 2nd pattern
Output:
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
1
2 3
4 5 6

Categories

Resources