在 Python 中怎樣讓乙個遞迴函式返回此函式的總遞迴次數?

時間 2021-05-31 18:55:29

1樓:

設乙個變數count在遞迴函式裡,大概這樣:

def a(b):

count=0

if:return a(b)

count+=1

return count

當然我還不是很清楚return語句的原理,這樣貌似可以?可以試試

2樓:lbaby

無子目錄即可返回。除非自己展開迭代或模擬呼叫棧,否則無法避免遞迴,python不支援尾遞迴優化,要不然可以放個計數引數做尾遞迴

3樓:starays

用乙個可變物件來記載filecounter,每次呼叫函式的時候修改此物件。類似C++中通過引用修改函式的引數。類似以下:

#!/usr/bin/env pythondef power(x, n, counter):

counter[0] += 1

if n == 0:

return 1

else:

return x * power(x, n-1, counter)counter = [0]

print power(5,3,counter)print counter

執行結果:

125[4]

4樓:alswl

我是 Python 程式設計師,但是明顯這個需求用 shell 寫更方便嘛,`find /your/path/ -type f | wc -l` 即可

殺雞焉用宰牛刀

5樓:

為什麼不直接用os.walk().

按你這種方法,不需要用filecounter引數,直接返回檔案數即可def func(...) :

c = 0

...c += func(...)

...return c

6樓:

把這個函式包在乙個工廠函式裡面,然後在工廠函式的作用域中建立乙個 collections.Counter 物件,在 fstable 的開頭為 collections.Counter 物件加一。

由於閉包的關係,每次遞迴引用的都將是同乙個 counter。

Python怎麼讓乙個列表中的數字同時乘另乙個數 並生成新的列表?

盜藍 列表解析 a 1,2 3,4 5 b 10c i b foriina 新的列表,速度更快 函式式程式設計 高階函式 map a 1,2,3,4,5 b 10 c generator map lambda a a b,a 生成器,可迭代物件,可以比列表解析有更多更靈活的表達 c list c g...

請問怎樣在centos中安裝python3?

楊高峰 如果安裝Python 3.6的話很簡單,已包括pip yum install epel release yum install python36 MorningDeng Googel centos install python3 How To Install Python 3 and Set...

怎樣在解除安裝乙個python庫的同時把僅有該庫依賴的其他庫一併解除安裝

善用 Google StackOverflow Github 可得 winson 折騰了一會兒,自己來答.找到了乙個神奇的包deptree,這個包可以用樹的形式將包的依賴關係列印出來 雖然包依賴關係嚴格來說並不是乙個樹 我的做法是將這個命令的輸出儲存到檔案,並使用vscode開啟 方便摺疊 然後開始...