I want to have a Multiplication table... with a given n. I tried... but my solution does not return what I want!
If n=3
def should return this:
[[1, 2, 3, 4],
[2, 4, 6, 8],
[3, 6, 9, 12],
[4, 8, 12, 16]]
My solution:
def multiplication_table(n):
r=[]
m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
for i in m:
i = [str(j).rjust(len(str(m[-1][-1]))+1) for j in i]
r.append(i)
return r
n=4
print(multiplication_table(n))
But it returns:
[[' 1',' 2',' 3',' 4'],
[' 2',' 4',' 6',' 8'],
[' 3',' 6',' 9',' 12'],
[' 4',' 8',' 12',' 16']]
It return string in list... but I want int in my list! I tried other ways but I could not solve this! Can anyone help me?
This should solve your problem I guess.
def multiplication_table(n):
r=[]
m = list(list(range(1*i,(n+1)*i, i)) for i in range(1,n+1))
for i in m:
i = [int(str(j).rjust(len(str(m[-1][-1]))+1)) for j in i]
r.append(i)
return r
n=4 print(multiplication_table(n))