1

所以我作为初学者学习python,并且一直在使用如何像计算机科学家一样思考python 3。我在关于迭代的章节中,用我自己的大脑进行编码而不是复制/粘贴,所以我记得更容易.

在做乘法表部分的最后一部分时,我得到了与课程所示相同的输出,但似乎我的更干净(更少的参数)。我仍在尝试掌握跟踪程序的窍门,所以我很难理解这些差异。我希望有人可以让我知道我的代码是否比文本版本效率低或更容易出错,并帮助结束这个头痛;)。

def print_multiples(n, high):         #This is the e-book version
    for i in range(1, high+1):
        print(n * i, end='   ')
    print()

def print_mult_table(high):
    for i in range(1, high+1):
        print_multiples(i, i+1)       #They changed high+1 to i+1 to halve output

来源

似乎他们的结果会有太多的 +1,因为 i+1 在 print_multiples 中会变为“高”,然后最终在 print_multiples 循环中再次添加 +1。(我还注意到他们保留了 end=' ' 而不是 end='\t' ,这会导致对齐。

def print_multiples(n):         #n is the number of columns that will be made
    '''Prints a line of multiples of factor 'n'.'''
    for x in range(1, n+1):     #prints n  2n  3n ... until x = n+1
        print(n * x, end='\t')  #(since x starts counting at 0, 
    print()                     #n*n will be the final entry)


def print_mult_table(n):            #n is the final factor
    '''Makes a table from a factor 'n' via print_multiples().
    '''
    for i in range(1, n+1):         #call function to print rows with i
        print_multiples(i)          #as the multiplier.

这是我的。基本的评论是为了我的利益,试图让追踪在我的脑海中保持直截了当。我的功能对我来说更有意义,但可能会有一些不同。我真的不明白为什么这本书决定为 print_multiples() 创建两个参数,因为 1 对我来说似乎就足够了……我还更改了大多数变量,因为它们多次使用“i”和“high”来演示本地与全球相比。不过,我重新使用了 n,因为在两种情况下它都是相同的最终数字。

可能有更有效的方法来做这种事情,但我仍在迭代中。只是希望尝试了解什么有效,什么无效,而这个让我很烦。

4

1 回答 1

1

(注意:对,您正在运行 Python 3.x)
您的代码更简单,对我来说也更有意义。
他们的说法是对的,但其用意却不尽相同,所以其输出不同。
仔细比较两者的输出,看看你是否能注意到差异模式。

您的代码稍微“高效”一些,但是将内容打印到屏幕上需要(相对)较长的时间,并且您的程序打印的内容比他们的要少一些。

为了衡量效率,您可以在 Python 中“分析”代码以查看需要多长时间。下面是我运行的代码
a) 检查源文本和输出的差异
b) 分析代码以查看哪个更快。
您可以尝试运行它。祝你好运!

import cProfile

def print_multiples0(n, high):         #This is the e-book version
    for i in range(1, high+1):
        print(n * i, end='   ')
    print()

def print_mult_table0(high):
    for i in range(1, high+1):
        print_multiples0(i, i+1)       #They changed high+1 to i+1 to halve output

def print_multiples1(n):        #n is the number of columns that will be made
    '''Prints a line of multiples of factor 'n'.'''
    for x in range(1, n+1):     #prints n  2n  3n ... until x = n+1
        print(n * x, end='\t')  #(since x starts counting at 0,
    print()                     #n*n will be the final entry)

def print_mult_table1(n):            #n is the final factor
    '''Makes a table from a factor 'n' via print_multiples().
    '''
    for i in range(1, n+1):          #call function to print rows with i
        print_multiples1(i)          #as the multiplier.

def test( ) :
     print_mult_table0( 10)
     print_mult_table1( 10)

cProfile.run( 'test()')
于 2012-05-03T04:09:56.323 回答