Python - 心理数学测试(这可以更有效吗?)

时间:2015-09-30 15:17:08

标签: python

我一直在努力提高我的python技能,基本上我决定制作这个程序,只用+, - 和/来询问用户10个简单的数学问题。我的代码是有效的(我已经测试了它,到目前为止它确实如此)但我希望它保留其当前的功能。但有没有一种方法可以提高效率?它是Python 3.4.3

    import random

    username = input("Enter your name: ")
    score = 0

    for i in range(10):
        sign = ""
        answer = 0
        numOne = random.randint(1,10)
        numTwo = random.randint(1,10)
        pickOperator = random.randint(1,3)
        if pickOperator == 1:
            sign = " + "
            answer = numOne + numTwo
        elif pickOperator == 2:
            sign = " - "
            answer = numOne - numTwo
       elif pickOperator == 3:
            sign = " * "
            answer = numOne * numTwo
        else:
            print ("An error has occured")
        question = "What is " + str(numOne) + sign + str(numTwo) + "? "
        user_answer = int(input(question))
        if user_answer == answer:
            print ("That was the correct answer!")
            score = score + 1
        else:
            print ("That answer was incorrect!")

    print (username + " you got " + str(score) + " out of 10")

1 个答案:

答案 0 :(得分:2)

可以做一些事情来使你的代码更加Pythonic,但请注意:效率(比如更快地运行代码)可能会是相同的,因为它的速度很可能受限于用户输入数据的速度,这是比计算机的时钟慢几个数量级。

为了便于扩展您的操作,您可以创建以下内容:

from operator import add, sub, mul
signs = ['+', '-', '*']
operations = [add, sub, mul]
mapping = {s: o for s, o in zip(signs, operations)}

因此,您可以这样使用pickOperator

sign = signs[pickOperator]
operation = mapping[sign]
answer = operation(numOne, numTwo)

并删除所有ifelif

当发生无效操作时,您的sign作业将收到异常(IndexError)。因此,您必须捕获它并显示错误消息以继续该程序。虽然如果正确使用随机函数,这种情况永远不会发生:

考虑使用randrange代替randint。所以你可以写:

pickOperator = random.randrange(0, len(signs))

另一种选择是放弃此变量并改为使用random.choice

sign = random.choice(signs)