# timestable.py
t = int(input("What size of multiplication table would you like to see (enter 1 – 12)?"))
if (t <=12):
s = input("What kind table would you like to display, enter either R, U, or L? (R for regular full matrix, U for upper triangular matrix, L for lower triangular matrix)?")
if s=="R":
for row in range (1,t+1):
for col in range (1,t+1):
prod = row * col
if prod < 10:
print(' ', end = '')
print(row * col, ' ', end = '')
print()
elif s== "L" :
for i in range(1,t+1):
for j in range (1, i+1):
prod = i *j
if prod < 10:
print(' ', end = '')
print(i * j, ' ', end = '')
print()
elif s== "U" :
for i in range(1,t+1):
for j in range (1, i-1):
prod = i *j
if prod < 10:
print(' ', end = '')
print(j * i, ' ', end = '')
print()
else :
t= int(input("Please enter a valid multiplecation table size (enter 1 – 12)?"))
答案 0 :(得分:0)
如果你想要一个上(下)三角矩阵,你知道位置i,j处的元素x,其中i> j(i 输出# upper example
t = 6
for i in range(1, t+1):
for j in range (1, t+1):
if i > j:
print("0\t", end=' ') # use whitespace if you want instead of 0
else:
prod = i*j
print("%s\t" % prod, end=' ')
print()
1 2 3 4 5 6
0 4 6 8 10 12
0 0 9 12 15 18
0 0 0 16 20 24
0 0 0 0 25 30
0 0 0 0 0 36
答案 1 :(得分:0)
如果您不介意使用numpy
,整个数组处理将更加轻松和紧凑,因此您可以专注于漂亮的打印。
import numpy as np
t = int(input("What size of multiplication table would you like to see (enter 1 – 12)?"))
if (t <=12):
s = input("What kind table would you like to display?\n"
"Enter either R, U, or L? (R for regular full, "
"U for upper triangular, and L for lower triangular arrays)")
a = np.arange(1,t+1)
prod = a.reshape(t,1).dot(a.reshape(1,t))
if s== "L" :
prod = np.tril(prod)
elif s== "U" :
prod = np.triu(prod)
for x in range(prod.shape[0]):
print(*prod[x].tolist(), sep='\t',end=' \n')
else :
t= int(input("Please enter a valid multiplecation table size (enter 1 – 12)?"))