我需要构建一个带有两个正整数的函数,并返回一个列表,这些列表表示一个乘法表,用于将所有整数从0乘以给定的数。例如,times_table(3,5)
应返回
[[0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5],
[0, 2, 4, 6, 8, 10],
[0, 3, 6, 9, 12, 15]]
但是,该功能只能执行此操作:4 = 4 , 8 , 12 , 16
。另外,我无法弄清楚如何以(x,y)格式制作它。
这是我到目前为止所做的:
def times_table(s):
n=int(input('Please enter a positive integer between 1 and 15: '))
for row in range(1,n+1):
s = ''
for col in range(1,n+1):
s += '{:3} '.format(row * col)
print(s)
如果你能帮助......
答案 0 :(得分:0)
使用列表推导:
def times_table(y,x):
return [[xi*yi for yi in range(x+1)] for xi in range(y+1)]
y = input("Enter y: ")
x = input("Enter x: ")
print(times_table(y, x))
(随附输入)
答案 1 :(得分:0)
Python(伪)代码:
def times_table(times,factor):
table = [[0]*(factor+1)]
for i in range(1,times+1):
table.append(list(range(0,i*factor+1,i)))
return table
这将返回您需要的表(以数组/列表格式) 那么你可以使用pprint来打印它或以任何其他格式
<强>输出强>
import pprint
pprint.pprint(times_table(3,5))
[[0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5],
[0, 2, 4, 6, 8, 10],
[0, 3, 6, 9, 12, 15]]
最好使用这样的函数:
n=int(input('Please enter a positive integer between 1 and 15: '))
import pprint
pprint.pprint(times_table(n,n))
答案 2 :(得分:0)
def times_table(x, y):
return [[i * j for i in range(x+1)] for j in range(y+1)]
答案 3 :(得分:0)
你可以这样做:
def tables(a, b):
return [[i*x for x in range(b+1)] for i in range(a+1)]
答案 4 :(得分:0)
你的代码很好。您只对 Python 中的缩进有疑问。 for loop 应该是嵌套的。此外,如果要在结果中包含零,则循环的范围必须从零开始。
def times_table(s):
n = int(input('Please enter a positive integer between 1 and 15: '))
for row in range(n+1):
s = ''
for col in range(n+1):
s += '{:3} '.format(row * col)
print(s)
答案 5 :(得分:0)
肉已被其他人所覆盖。看起来你也希望用户同时输入x和y。最简单的方法是:
x,y =输入(“输入x和y,用逗号分隔:”)
如果你真的想要输入中的括号,我输入一个字符串,然后拉出(和,和之间,和)之间的值并转换为整数,但这似乎必须复杂至少。