python如何重构反数子句

2024-05-19 03:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

如果可能,我想将以下两个子句(彼此完全相反)重构为一个:

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

Tags: ifdiceselectelseturnscoreothertake
1条回答
网友
1楼 · 发布于 2024-05-19 03:39:55

您的代码很复杂,因为您分散了相关的数据

因此,您所要做的就是收集数据并将其作为参数传递

这里有一些可能的场景,我将使用字典来编写以下代码

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

我认为类实现更好,你应该试试

相关问题 更多 >

    热门问题