如何组合功能,使它们更通用

时间:2019-02-06 17:03:27

标签: python

我已经编写了一个可以掷骰子,计算结果并决定获胜者的代码,我已经为6种不同的情况下完成了一次学校作业,但是当我把它弄回来后,我想把它缩短一些。现在,它只有6种不同的功能,而所有功能仅需要一组数据。

按数据,我指的是这些输入:

 Case 1: 
 S1 = (9, {1,2,3,4}, lambda x: 1/4)
 S2 = (6, {1,2,3,4,5,6}, lambda x: 1/6)

 Case 2:
 S1 = (1, set(range(1,36+1)), lambda x: 1/36)
 S2 = (36, {0,1}, lambda x: 1/2)

Case 3:    
S1 = (6, {1,2,3,4}, lambda x: 1/4)
S2 = (4, {1,2,3,4,5,6}, lambda x: 1/6)

我将这些情况放在这段代码中;

def Case1(Rolls):
    Win = 0
    S1 = (9, {1, 2, 3, 4}, lambda x: 1 / 4)
    S2 = (6, {1,2,3,4,5,6}, lambda x: 1/6)
    for u in range(Rolls):
        Score1 = sum(random.choices(list(S1[1]), list(map(S1[2], range(len(S1[1])))), k=S1[0]))
        Score2 = sum(random.choices(list(S2[1]), list(map(S2[2], range(len(S2[1])))), k=S2[0]))
        if Score1 > Score2:
            Win = Win + 1
            Sentence = Win/100000*100
    print("the probability that player one wins is " + str(Sentence) + " percent.(Case 1)")

def Case2(Rolls):
    Win = 0
    S1 = (1, set(range(1, 36 + 1)), lambda x: 1 / 36)
    S2 = (36, {0, 1}, lambda x: 1 / 2)
    for u in range(Rolls):
        Score1 = sum(random.choices(list(S1[1]), list(map(S1[2], range(len(S1[1])))), k=S1[0]))
        Score2 = sum(random.choices(list(S2[1]), list(map(S2[2], range(len(S2[1])))), k=S2[0]))
        if Score1 > Score2:
                Win = Win + 1
                Sentence = Win / 100000 * 100
        print("the probability that player one wins is " + str(Sentence) + " percent.(Case 2)")
def Case3(Rolls):
    Win = 0
    S1 = (6, {1, 2, 3, 4}, lambda x: 1 / 4)
    S2 = (4, {1, 2, 3, 4, 5, 6}, lambda x: 1 / 6)
    for u in range(Rolls):
        Score1 = sum(random.choices(list(S1[1]), list(map(S1[2], range(len(S1[1])))), k=S1[0]))
        Score2 = sum(random.choices(list(S2[1]), list(map(S2[2], range(len(S2[1])))), k=S2[0]))
        if Score1 > Score2:
            Win = Win + 1
            Sentence = Win / 100000 * 100
    print("the probability that player one wins is " + str(Sentence) + " percent.(Case 3)")

有人知道如何组合这些功能,使它们更通用吗?

Python 3.7中的

1 个答案:

答案 0 :(得分:0)

您的函数实际上是相同的,只有S1S2不同,您可以将它们作为函数的参数传递。另外,Case的输出数量也不同,因此您可以传递case_num

def Case(Rolls,S1,S2,case_num):
    Win = 0
    for u in range(Rolls):
        Score1 = sum(random.choices(list(S1[1]), list(map(S1[2], range(len(S1[1])))), k=S1[0]))
        Score2 = sum(random.choices(list(S2[1]), list(map(S2[2], range(len(S2[1])))), k=S2[0]))
        if Score1 > Score2:
            Win = Win + 1
            Sentence = Win/100000*100
    print("the probability that player one wins is " + str(Sentence) + " percent.(Case "+case_num+")")

Case(somthing,(9, {1, 2, 3, 4}, lambda x: 1 / 4),(6, {1,2,3,4,5,6}, lambda x: 1/6),'1')
Case(somthing,(1, set(range(1, 36 + 1)), lambda x: 1 / 36),(36, {0, 1}, lambda x: 1 / 2),'2')
Case(somthing,(6, {1, 2, 3, 4}, lambda x: 1 / 4),(4, {1, 2, 3, 4, 5, 6}, lambda x: 1 / 6),'3')