[英]Why this insertion sort algorithm outputs None?
def insertion_sort(list):
for index in range(1,len(list)):
value = list[index]
i = index - 1
while i>=0:
if value < list[i]:
list[i+1] = list[i]
list[i] = value
i = i - 1
else:
break
a = [7,1,3,5,9,2,3]
print(insertion_sort(a))
This code is taken from a Khan Academy video . 此代码取自可汗学院的视频 。 However, when I try to run it myself both on Jupyter Notebook and IDLE it outputs None.
但是,当我尝试自己在Jupyter Notebook和IDLE上运行它时,都将输出None。 I can't figure out why when it's exactly the same from the video.
我无法从视频中弄清楚为什么如此。 Thanks in advance for helping.
在此先感谢您的帮助。
Your function doesn't have a return
statement anywhere. 您的函数在任何地方都没有
return
语句。 If a function doesn't return
anything explicitly, it always returns None
. 如果函数没有明确
return
任何内容,则它始终返回None
。
And it's almost certainly intentional that this function doesn't return anything. 而且几乎可以肯定,此函数不返回任何内容。
Notice that the function mutates its argument in-place: 请注意,该函数就地改变了其参数:
>>> a = [7,1,3,5,9,2,3]
>>> insertion_sort(a)
>>> a
[1, 2, 3, 3, 5, 7, 9]
In Python, it's idiomatic for functions that do this to not return anything. 在Python中,执行此操作的函数不返回任何内容是惯用法。 See, for example, builtin methods like
list.sort
and list.append
. 例如,参见诸如
list.sort
和list.append
类的内置方法。
And notice that in the cited video , this is exactly what the instructor does—they don't print
the result of insertion_sort
, they just call it, and then look at the value of the variable. 并注意所引用的视频 ,这正是教练什么呢,他们不
print
的结果insertion_sort
,他们只是把它,然后看看变量的值。
Also, in general, functions that mutate a value in-place, like this one, take an imperative verb, like the list method sort
, while functions that leave the argument unchanged but return a transformed value, take a past participle, like the built-in function sorted
. 同样,一般而言,就地改变值的函数(如此函数)采用命令式动词(如list方法
sort
,而使参数保持不变但返回转换后的值的函数则采用过去分词(如build) -in函数已sorted
。
So, if this function were named insertion_sorted
, Python programmers would expect it to leave its argument alone and return a new, sorted list; 因此,如果将此函数命名为
insertion_sorted
,Python程序员将期望它不理会参数并返回一个新的,已排序的列表。 since it's named insertion_sort
, they'll expect it to sort its argument in-place and return nothing. 由于它的名称为
insertion_sort
,因此他们希望它对参数进行就地排序,并且不返回任何内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.