Function to return table of a number - python

I have tried below code to return a multiplication table for input number:
def table_of(n):
for i in range(1,11):
print(n,"*",i,"=",n*i)
a = input("Enter a Number:")
table_of(a)
This returns:
Enter a Number:2
2 * 1 = 2
2 * 2 = 22
2 * 3 = 222
2 * 4 = 2222
2 * 5 = 22222
2 * 6 = 222222
2 * 7 = 2222222
2 * 8 = 22222222
2 * 9 = 222222222
2 * 10 = 2222222222
What is the problem?

The input() function returns a string therefor the loop prints that string i times. The solution would be to replace a = input(“Enter a number: ”) with
a = int(input(“Enter a number: ”))

The output from an input statement is always a string. You need to convert n to an integer before multiplying, either at the input statement, or in the print, as below.
def table_of(n):
for i in range(1,11):
print(n,"*",i,"=",int(n)*i)
a = input("Enter a Number:")
table_of(a)
Gives the output:
Enter a Number:>? 2
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Related

Python - How can I line up the equals sign of all my equations?

Currently in maths class we are working on gcd and I have written a Python script on my NumWorks calculator.
Here is the code I already wrote :
def div(n):
return [x for x in range(1,n+1) if n%x==0]
def pgcd(x,y):
a = x
b = y
while b > 0:
reste = a % b
print(a, "=", a//b, "*", b, "+", a%b)
a,b = b,reste
return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
And it ouputs this :
pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
I want it to output that :
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
I've read many articles online but I have no idea how to put that into my code.
Thanks in advance.
You can use the rjust string method.
The thing is you need to figure out what is the widest string on the left hand side you will print. Luckily here, it would be the first value.
So I would go with this.
def pgcd(x,y):
a = x
b = y
len_a = len(f"{a}")
while b > 0:
reste = a % b
print(f"{a}".rjust(len_a), "=", a//b, "*", b, "+", a%b)
a,b = b,reste
return "PGCD("+str(x)+";"+str(y)+") = " + str(a)
Should print this.
>>> pgcd(178,52)
178 = 3 * 52 + 22
52 = 2 * 22 + 8
22 = 2 * 8 + 6
8 = 1 * 6 + 2
6 = 3 * 2 + 0
'PGCD(178;52) = 2'
See .format for strings. An example of right justifying would look something like print('{:>6}'.format(42))
You can also use rjust
Use str.format() to achieve this:
'{0: >{width}}'.format(178, 3)
'{0: >{width}}'.format(52, 3)
Will output
178
52
Ok I asked it on a Discord server and they found out so if anyone is having the same problem as me here is the solution (did not put all code for space) :
def pgcd(x,y):
a = x
b = y
maxi = len(str(a))
while b > 0:
reste = a % b
print(" "*(maxi-len(str(a))),a, "=", a//b, "*", b, "+", a%b)
Basically compare to original code we added a maxi variable that has the maximum lenght of my integers, and then if the int is smaller like 8 compare to 178 we add to spaces because the difference of their length is 2.
This explanation is probably not 100% correct but it helps getting an idea.

How can I write a program that prints a multiplication table of size m by n which is provided by the user in Python?

Examples:
m n: 2 3
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
m n: 4 2
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
3 * 1 = 3
3 * 2 = 6
4 * 1 = 4
4 * 2 = 8
I have written this code but i said "list assignment index out of range", how can I fix it? thanks
m, n = input('m n: ').split()
x = []
for i in range(0, int(m)):
for j in range(0, int(n)):
x[j] = int(m[i]) * int(n[j])
print(str(i) + ' * ' + str(j) + ' = ',x[j])
m, n = input('m n: ').split()
for i in range(1, int(m)+1):
for j in range(1, int(n)+1):
print(str(i) + ' * ' + str(j) + ' = ', i * j)

How to make code to print 1 2 3 4 2 2 3 4 3 2 3 4, and so on? using For Loops [duplicate]

This question already has answers here:
Print several values in the same line with commas
(2 answers)
Closed 4 years ago.
I need to modify this code, to replace the
number 1 with the number of the current measure. So, the first
number in each measure will always rise.
instead of
1
2
3
4
1
2
3
4
1
2
3
4
(with each number on its own line), I'd now print
1 2 3 4 2 2 3 4 3 2 3 4
, and so on.
beats_per_measure = 4
measures = 5
for measure in range(0, measures):
for beat in range(1, beats_per_measure + 1):
print(beat)
Perhaps you need something like below.
beats_per_measure = 4
measures = 5
### loop from 1 to 5 measures ###
# remove +1 to get sequence of 4
# iterations
for measure in range(1, measures+1):
# print the measure value in a single line
# first at iteration of outer loop to get
# the sequence
print(measure, end = " ")
## then loop from 2 to measure
for beat in range(2, beats_per_measure + 1):
# print each beat
print(beat, end = " ")
Output
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
If you are using python 3, this is the answer(tested):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print(measure, end = ' ')
for beat in range(2, beats_per_measure + 1):
print(beat, end = ' ')
Or if you are using python 2, use this (tested):
beats_per_measure = 4
measures = 5
for measure in range(1, measures+1):
print measure,
for beat in range(1, beats_per_measure + 1):
print beat,
More info here: https://www.quora.com/How-do-I-print-something-on-the-same-line-in-Python
You can solve this by manually printing the measure you are currently in - followed by the remaining beats:
beats_per_measure = 4
measures = 5
for m in range(measures):
# manually print the measure you are in
print(m+1, end=" ") # do not put a newline after the print statement
# print the beats 0...bmp-1 == 0,1,2 - output adds 2 to each => 2,3,4
for beat in range(beats_per_measure - 1):
print(beat+2, end = " ") # do not put a newline after the print statement
Output:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4
* * * * *
The * are manually printed, the others filled in by the for-loop
You can read more about printing in one line here:
Print in one line dynamically
Python: multiple prints on the same line
Print several values in the same line with commas
Doku: https://docs.python.org/3/library/functions.html#print
You can also create a generator that counts measures on its own (I'll mark the measure-number with * manually):
def gimme_measure(beats_per_measure):
beats = list(range(2,beats_per_measure+1))
yield gimme_measure.measure
gimme_measure.measure += 1
yield from beats
gimme_measure.measure = 1 # defines the starting measure
# print 2*10 measures
for _ in range(10):
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
for _ in range(10): # continues the beat measuring
print(*gimme_measure(4), end = " ") # the * decomposes the values from the generator
Output:
1 2 3 4 2 2 3 4 3 2 3 4 4 2 3 4 5 2 3 4 6 2 3 4 7 2 3 4 8 2 3 4 9 2 3 4 10 2 3 4 11 2 3 4 12 2 3 4 13 2 3 4 14 2 3 4 15 2 3 4 16 2 3 4 17 2 3 4 18 2 3 4 19 2 3 4 20 2 3 4
* * * * * * * * * ** ** ** ** ** ** ** ** ** ** **
The generator gimme_measure has it's own measure counter which is initialized to 1 and incremented each time you generate a new measure using the generator - if you do not reset the gimme_measure.measure to some other number it keeps counting upwards any time you print another generated measure.
You can even chain different bpm together:
# piece with 2 measures of 4 beats, 2 measures of 8 beats, 2 measures of 3 beats
for _ in range(2):
print(*gimme_measure(4), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(8), end = " ")
for _ in range(2): # continues the beat measuring
print(*gimme_measure(3), end = " ")
Output:
1 2 3 4 2 2 3 4 3 2 3 4 5 6 7 8 4 2 3 4 5 6 7 8 5 2 3 6 2 3
* * * * * *

All + - / x combos for 4 numbers

4 one digit numbers and try to get all the possible combos
4511
like 4 + 5 + 1 x 1
Code to get first, 2nd 3rd and 4th numbers
numbers = input("Input 4 numbers separated with , : ")
numlist = numbers.split(",")
print (numlist)
No1 = int(numlist.pop(0))
No2 = int(numlist[0])
No3 = int(numlist[1])
No4 = int(numlist[2])
An exhaustive search:
from random import randrange
from itertools import permutations
def solve(digits):
for xs in permutations(digits):
for ops in permutations('+-*/', 3):
equation = reduce(lambda r, (x, op): '{0} {1} {2}'.format(r, op, float(x)), zip(xs[1:], ops), xs[0])
try:
if eval(equation) == 10:
yield equation.replace('.0','')
except ZeroDivisionError:
pass
digits = [randrange(0,10,1) for x in range(4)]
solutions = list(solve(digits))
if solutions:
print '\n'.join(solutions)
else:
print 'No solution for {0}'.format(digits)
Example output:
2 * 5 / 1 + 0
2 * 5 / 1 - 0
2 * 5 + 0 / 1
2 * 5 - 0 / 1
2 / 1 * 5 + 0
2 / 1 * 5 - 0
5 * 2 / 1 + 0
5 * 2 / 1 - 0
5 * 2 + 0 / 1
5 * 2 - 0 / 1
5 / 1 * 2 + 0
5 / 1 * 2 - 0
0 + 2 * 5 / 1
0 + 2 / 1 * 5
0 + 5 * 2 / 1
0 + 5 / 1 * 2
0 / 1 + 2 * 5
0 / 1 + 5 * 2
or
No solution for [7, 1, 0, 2]
Note: I like the recursive expression generator referred to in the comment above, but I just don't think recursively straight off.
Use a recursive approach:
numbers = input("Input 4 numbers separated with , : ")
numlist = list(numbers)
def f(lst,carry,result):
x = lst.pop(0)
if lst == []:
return carry+x == result or \
carry-x == result or \
carry*x == result or \
carry/x == result
elif carry==None:
carry = x
return f(lst,carry,result)
else:
return f(lst,carry+x,result) or\
f(lst,carry-x,result) or\
f(lst,carry*x,result) or\
f(lst,carry/x,result)
print(f(numlist, None, 10))
Your I/O is wrong (first two lines), and I don't know if this is something that you have already tried.

Multiplication Table For Python in IEP?

I Am using python 3.3 with IEP and i am trying to make a multiplication table that is nice an orderly. Everywhere i look online says it will be nice but it ends up just being 1 row and long where i want
1 2 3 4
2 4 6 8
3 6 9 12
the code i find is generally like this... SO whats wrong with it?
def main():
i = 1
print("-" * 50)
while i < 11:
n = 1
while n <= 10:
print("%4d" % (i * n),)
n += 1
print("")
i += 1
print("-" * 50)
main()
Because there is a line break after each print
Change 7th line to
print("%4d" % (i * n), end=" ")
The problem is right here:
print("%4d" % (i * n),)
Each print call implicitly puts a line break at the end of the output, but you can change that by providing the end keyword argument to print().
You can do something like this:
In [1]: def print_table(size):
...: for i in range(1, size+1):
...: print(''.join('{:>4d}'.format(i*j) for j in range(1, size+1)))
...:
In [2]: print_table(5)
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

Categories