0

我必须定义一个过程,该过程将一个正整数作为输入,并打印出一个乘法表,显示所有整数乘法直到并包括输入数。例如,我需要这个输出:

打印乘法表(2)

1 * 1 = 1

1 * 2 = 2

2 * 1 = 2

2 * 2 = 4

所以我试过这个:

def print_multiplication_table(n):
    count=0
    multiplicador=n
    while count<multiplicador:
        count+=1
        print n,"x", count, "=", n*count

    def print_multiplication_table(n):
        num=1
        print str(num) + ' * ' + str(num) + ' = ' + str(num*num)
        while num<n:
            siguiente=num+1
            conteo=num-1
            while conteo<n:
                print str(num) + ' * ' + str(siguiente) + ' = ' + str(num*siguiente)
                print str(num) + ' * ' + str(siguiente) + ' = ' + str(num*siguiente)

但这会产生一个永远运行的循环,我不知道如何让它停止。

然后我尝试了一种不同的、更优雅的方法,比如这个:

def print_multiplication_table(n):
    count=0
    multiplicador=n
    while count<multiplicador:
        count+=1
        print n,"x", count, "=", n*count

但它没有考虑到我要相乘的数字之前的数字相乘(输出为 2x1=2、2x2=4,但不乘以 1x1,也不乘以 1x2)。

我需要做哪些改变?有什么提示吗?谢谢!

4

3 回答 3

6

最简单的是:

from itertools import product

def pmt(n):
    for fst, snd in product(xrange(1, n + 1), repeat=2):
        print '{} * {} = {}'.format(fst, snd, fst * snd)

pmt(2)

1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
于 2013-07-21T14:26:23.103 回答
4

你需要一个嵌套for循环。

>>> def print_multiplication_table(n):
        for i in xrange(1, n+1):
            for j in xrange(1, n+1):
                print "{}x{}={}".format(i, j, i*j)


>>> print_multiplication_table(2)
1x1=1
1x2=2
2x1=2
2x2=4

您的while循环不起作用,因为您从 1 到数字并且仅将数字与 相乘count,因此生成了一个类似10x1, 10x2, 10x3....

于 2013-07-21T14:25:05.677 回答
1

使用生成器表达式:

r = xrange(1, n+1)
g = (' '.join([str(i), '*', str(j), '=', str(i*j)]) for i in r for j in r)
print ('{}\n'*n*n).format(*g)
于 2013-07-21T17:15:48.210 回答