如果可能,我想将以下两个条款(彼此完全相反)重构为一个:
if who == 0:
score = take_turn(strategy0(score0, score1), score1, select_dice(score0, score1))
if score == 0:
score1 += strategy0(score0, score1)
else:
score0 += score
elif who == 1:
score = take_turn(strategy1(score1, score0), score0, select_dice(score1, score0))
if score == 0:
score0 += strategy1(score1, score0)
else:
score1 += score
我如何才能实现以下目标?
def other(who)
return 1 - who
score = take_turn(strategy+who(score+who, score+other), score+other, select_dice(score+who, score+other))
if score == 0:
score+other += strategy+who(score+who, score+other)
else:
score+who += score
答案 0 :(得分:0)
您的代码很复杂,因为您分散了相关的数据。
所以你要做的就是收集数据并将其作为参数传递。
有一些可能的场景,我将使用字典来代码。
dataWho = {"id": 0, "score": score0, "strategy": strategy0} #gathering related data. function also can be the value of dictionary.
dataOther = {"id": 1, "score": score1, "strategy": strategy1}
def foo(dataWho, dataOther):
score = take_turn(dataWho["strategy"](dataWho["score"], dateOther["score"]), dataOther["score"], select_dice(dataWho["score"], dateOther["score"]))
if score == 0:
dateOther["score"] += dataWho["stratey"](dataWho["score"], dateOther["score"])
else:
dataWho["score"] += score
我认为课程实施更好,你应该尝试。