回答編集履歴

1

意味のない再帰関数をやめました

2022/04/21 13:30

投稿

lehshell
lehshell

スコア1147

test CHANGED
@@ -1,3 +1,20 @@
1
+ 再帰関数を使う意味はありませんでした。改善したコードです。
2
+ ```Python
3
+ def steps(mx):
4
+ tpl=((),)
5
+ while True:
6
+ tpl = tuple(tp+(i,) if sum(tp) < mx else tp
7
+ for tp in tpl for i in (1,2) if not(tp and tp[-1]==2==i))
8
+ tpl = tuple(set(tpl))
9
+ if all(sum(tp) >= mx for tp in tpl):
10
+ return tuple(tp for tp in tpl if sum(tp) == mx)
11
+
12
+ n = 15
13
+ tpl = steps(n)
14
+ print(f'{n}段の登り方は{len(tpl)}通り')
15
+ # 15段の登り方は277通り
16
+ ```
17
+ 元のコードは以下です。
1
18
  リストではなくタプルを使用し、再帰関数を使用したサンプルコードです。ご参考まで
2
19
  ```Python
3
20
  def steps(mx, tpl=((),)):
@@ -14,3 +31,4 @@
14
31
  # 15段の登り方は277通り
15
32
  ```
16
33
 
34
+