[英]Dynamic Nesting of For loops in python
考慮到我們還可以選擇球的一個子集(就像根本沒有球一樣),我有一小段代碼可以打印在“c”杯中填充“b”球的所有可能方式:
b = 2
c = 3
for i in range(b+1):
for k in range(b+1):
for j in range(b+1):
if i+j+k<=b:
print(i,k,j)
結果是:
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 2 0
1 0 0
1 0 1
1 1 0
2 0 0
現在,問題在於這不是通用代碼,並且根據杯子的數量(c),嵌套的 For 循環的數量需要更改。 我嘗試使用遞歸,但無法獲得所需的結果。
誰能幫我使這個代碼通用,這樣我只需要輸入'b'和'c'的值並在不編輯代碼的情況下獲得結果嗎?
您不需要遞歸,只需itertools.product
:
for t in product(range(b+1), repeat=c):
if sum(t) <= b:
print(t)
但是,遞歸將通過動態調整每個范圍以考慮先前的選擇來減少您需要考慮的元組的數量。
# Untested
def foo(b, c, stop=0):
for x in range(0, b+1-stop):
for y in foo(b, c-1, stop + x):
yield (x, *y)
for t in foo(b, c):
if sum(t) <= b:
print(t)
這是使用遞歸生成器的解決方案
def fill(b, c):
if c == 0:
yield []
else:
for i in range(b+1):
for sub in fill(b-i, c-1):
yield [i, *sub]
for o in fill(2, 3):
print(o)
Output
[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[0, 1, 1]
[0, 2, 0]
[1, 0, 0]
[1, 0, 1]
[1, 1, 0]
[2, 0, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.