multiplication table python nested loop not printing full table - python

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

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

Learning Python and need help moving a symbol with out disrupting the rest of the code

I am learning Python and need a little help with moving my symbols over a few spaces to the left. I have completed the assignment and am not looking for homework help. I just want it to look nicer on my end. In the picture that I added in the link below, you can see that the "#" is too far to the right. I would like it to sit next to the even numbers. I have tried making more spaces in my print statements but all that does is move my entire table around. How do I get that "#" to sit right next to my even numbers?
Here is my code.
#ask for user input on size of Multiplication Table.
size = int(input("What size Multiplication Table would you like? (2-10):"))
while (size <2) or (size >10):
print("Invalid entery! Enter a Number Between 2 and 10")
size = int(input("What size Multiplication Table would you like? (2-10):"))
print()
print()
#dispaly header
print(" --- Multiplication Table(",size,"x",size,") ---")
print(" ",end="")
size += 1
for h in range(1,11):
if h == 10:
print(" ",h, end=" ")
else:
print(" ",h, end=" ")
print()
for h in range(1,100):
print('-',end='')
print()
#display Multiplication Table
#outer loop
for a in range(1,size):
if a ==10:
print('',a,'|',end='')
else:
print('',a,' |',end='')
#inner loop
for b in range(1,size):
result = a * b
if result >=100:
print(' ',result, end=' ')
elif result >=10:
print(' ',result, end=' ')
else:
print(' ', result, end=' ')
# for putting '#' at the end of even numbers
if result %2==0:
print('#', end='')
elif result == 100:
print('', end='')
else:
print(' ', end='')
print()
I've made minimal modification to your inner loop, to produce the desired effect:
for b in range(1,size):
result = a * b
# for putting '#' at the end of even numbers
if result %2==0:
end_str='#'
elif result == 100:
end_str=''
else:
end_str=' '
if result >=100:
print(' ',result, end=end_str+' ')
elif result >=10:
print(' ',result, end=end_str+' ')
else:
print(' ', result, end=end_str+' ')
Output, with this modification:
1 2 3 4 5 6 7 8 9 10
---------------------------------------------------------------------------------------------------
1 | 1 2# 3 4# 5 6# 7 8# 9 10#
2 | 2# 4# 6# 8# 10# 12# 14# 16# 18# 20#
3 | 3 6# 9 12# 15 18# 21 24# 27 30#
4 | 4# 8# 12# 16# 20# 24# 28# 32# 36# 40#
5 | 5 10# 15 20# 25 30# 35 40# 45 50#
6 | 6# 12# 18# 24# 30# 36# 42# 48# 54# 60#
7 | 7 14# 21 28# 35 42# 49 56# 63 70#
8 | 8# 16# 24# 32# 40# 48# 56# 64# 72# 80#
9 | 9 18# 27 36# 45 54# 63 72# 81 90#
10 | 10# 20# 30# 40# 50# 60# 70# 80# 90# 100#
Try this:
for b in range(1,size):
result = a * b
flag = " " if result % 2 else "#"
#put the number and the flag together
temp = f"{result}{flag}"
#and pad the number + flag to a constant length
print(f' {temp:6.6}', end="")
see my comment under the question about a clearer breakdown of how f-string formatting works.
output:
--- Multiplication Table( 4 x 4 ) ---
1 2 3 4 5 6 7 8 9 10
---------------------------------------------------------------------------------------------------
1 | 1 2# 3 4#
2 | 2# 4# 6# 8#
3 | 3 6# 9 12#
4 | 4# 8# 12# 16#
see my comment about how f-string formatting works. couldn't find a really clear reference about how the formatting is specified f"{<variable>:<formatting-to-apply>}" so can't link one, but it do things like pad zeros and format floats too.

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]

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