昨天我遇到了一個有趣的數學問題,並解決了它,但是用我寫的代碼,我不得不做一個鍵盤中斷,否則它將永遠運行,哈哈。所以我改變它有一個結束條件,,但現在它只打印1個解決方案並停止。在Python中檢查唯一輸出
問題是這樣的:「你的數字是123456789,按順序在每個數字之間,你必須插入無符號,加號或乘號,以便得到的表達式等於2002.寫(有兩個)「
import random
def try1(param):
global solved
opers = ['+', '*', '']
hotpotato = ('%s'.join(param) % (random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
random.choice(opers),
)
)
if eval(hotpotato) == 2002:
solved += 1
print "Solution:", hotpotato, "= 2002 :-)"
else:
pass
solved = 0
while solved == 0:
try1('123456789')
此代碼打印遇到和停止的第一個解決方案。任何人都可以告訴我如何在停止之前打印兩種解決方案?
這是來自歐拉項目嗎? – Blender
@Blender如果是這樣,我還沒有看到它。 –