2012-05-03 41 views
1

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

在做乘法表部分的最后部分时,我得到了与本课程相同的输出结果,但看起来我的结构更清晰(参数更少)。我仍然在试图追踪追踪计划,所以我很难对这些差异进行包揽。我希望有人能让我知道,如果我的代码不如文本的版本更有效或更容易出错,并有助于结束这种头痛的问题;)。

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 

Source

这似乎是他们的结果将有太多+ 1的,因为我+ 1将成为print_multiples“高”,然后结束了在print_multiples'环+ 1再次增加。 (我还注意到,他们不停地结束=“‘而不是一个终点=’\ 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,因为它们在两种情况下都是相同的最终数字。更有效的方法来做这种事情,但我仍然迭代。只是希望试着去感受一下什么是有效的,什么不可以,而这正在扰乱我。

+0

我在这里没有得到相同的输出;你的每一行都是一个更短的元素。 –

+0

尝试他们,我得到一个额外的专栏。课程页面显示我使用代码获得的输出,但使用代码时,表格中print_mult_table(7)的最终条目应为“49”时为“56”。我不确定我是否输入了他们的错误,或者他们在代码中犯了错误。 – Hesuchia

回答

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()') 
+0

啊,我看到了,感谢您的个人资料:)我还没有听说过,应该非常方便。 – Hesuchia