3 回答

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個(gè)贊
首先,您的代碼有錯(cuò)誤的對(duì)齊方式(“ if not cmp:”應(yīng)保留一個(gè)位置,最后兩行應(yīng)與第一行位于同一列),如下所示:
def fun(lst):
for item in lst:
cmp = 0
for other in lst:
if item < other:
cmp -= 1
elif item > other:
cmp += 1
if not cmp:
return item
nums = [1,3,2,2]
print("fun({0}) = {1}".format(nums,fun(nums)))
fun函數(shù)返回第一個(gè)數(shù)組的項(xiàng),以使“ not cmp”,即cmp!=0。cmp是小于給定項(xiàng)的數(shù)組元素?cái)?shù)減去大于項(xiàng)的數(shù)組元素?cái)?shù)
if item < other:
cmp -= 1
elif item > other:
cmp += 1
現(xiàn)在,讓我們看一下數(shù)組項(xiàng)[1、3、2、2]
1:比self(3,2,2)多3個(gè)項(xiàng)目,且不小于self,因此cmp = 0-3 = -3,不返回
3:有3個(gè)項(xiàng)目,沒(méi)有比自己少的項(xiàng)目,有3個(gè)(3、2、2)多于自己,因此cmp = 3-0 = 3,不返回
2:比self(3)多一件商品,而比(1)小一件商品,cmp = 0,函數(shù)將其返回(2)

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超10個(gè)贊
def fun(lst):
for item in lst:
cmp = 0
for other in lst:
if item < other:
cmp -= 1
elif item > other:
cmp += 1
if not cmp:
return item
nums = [1, 3, 2, 2]
您的代碼有一個(gè)嵌套循環(huán),一個(gè)for循環(huán)中的一個(gè)for循環(huán)。
外部for循環(huán)是for item in lst,內(nèi)部for循環(huán)是:for other in lst:
循環(huán)看起來(lái)像這樣:
1(outer) - > 1, 3, 2, 2 # 1,3,2,2 are assigned one by one to `other`
3(outer) - > 1, 3, 2, 2
2(outer) - > 1, 3, 2, 2
2(outer) - > 1, 3, 2, 2
它首先從外循環(huán)開(kāi)始,分配給item的值是1,并cmp設(shè)置為0?,F(xiàn)在,在內(nèi)部循環(huán)中遍歷整個(gè)列表。
分配給other的第一個(gè)值是1。現(xiàn)在,它檢查它是否大于或小于item(在這種情況下為1),并cmp基于此值增加或減少。在下一次迭代中,現(xiàn)在分配了other 3,再次將其與item(1)比較,并cmp根據(jù)該值更改了值。同樣,它移至下兩個(gè)項(xiàng)目2,2。
現(xiàn)在出現(xiàn)這種情況:
if not cmp: return item
它檢查的值是否cmp為falsey,如果cmp為0(0為falsey值),則返回該項(xiàng)目,函數(shù)終止。(not 0是True在python)
如果條件為假,則返回到外部循環(huán),并為該時(shí)間item分配值3,然后內(nèi)部循環(huán)按照上面已經(jīng)描述的那樣繼續(xù),但事實(shí)item是now 3。
內(nèi)部循環(huán)實(shí)際上所做的是,它實(shí)際上比較有多少個(gè)項(xiàng)目大于或小于當(dāng)前項(xiàng)目。
1(outer) - > 1, 3, 2, 2 # cmp is -3, because 3,2,2 are bigger than 1
3(outer) - > 1, 3, 2, 2 # cmp is 3, because 1,2,2 are smaller than 3
2(outer) - > 1, 3, 2, 2 # cmp is 0, because 3 is greater than 2 and 1 is smaller
# than 2, so the condition `if cmp` is True for this case
# and the function return 2 (i,e. item)
2(outer) - > 1, 3, 2, 2 # this is never reached as function already returned
如果所有循環(huán)都結(jié)束并且cmp永遠(yuǎn)都不會(huì)變?yōu)?,則您的函數(shù)將返回None(函數(shù)的默認(rèn)返回值)。

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個(gè)贊
是否有人對(duì)如何簡(jiǎn)化代碼塊的解釋有任何提示?
把它寫(xiě)出來(lái)。在頁(yè)面中為每個(gè)名稱(chēng)分配自己的空間,并在運(yùn)行代碼時(shí)跟蹤對(duì)值的更改。經(jīng)過(guò)一些練習(xí),您將能夠輕松跟蹤簡(jiǎn)單值,只需要寫(xiě)出非標(biāo)量值即可。
添加回答
舉報(bào)