Using Dictionaries in Python in place of Case/Switch statement

你说的曾经没有我的故事 提交于 2019-12-05 03:53:23

When you define the dict, it's actually calling the functions, and storing the return value in the dictionary. To just have the dictionary store a reference to the functions, you need to drop the trailing parentheses. So something like:

scramble = {  0: self.up_turn,
              1: self.down_turn,
              etc.

Then, at the bottom, call scramble[i]().

This will call the function with no arguments. To handle the case where you pass "inverted" as an argument, you could either define separate functions like up_turn_inverted(), etc., or you could have the dictionary store a 2-ple consisting of the function, and the argument, then call something liks scramble[i][0](scramble[i][1])

Update from suggestion in comments: You could also use lambda expressions to define the functions, particularly the ones that require an argument. This is basically equivalent to defining an up_turn_inverted function, but done in-place as an anonymous function. It would look like this:

6: lambda: self.up_turn("inverted")
7: lambda: self.down_turn("inverted")

etc.

I believe this is called "functions as first-class values", implying most importantly that you can pass identifiers referring to functions as parameters to other functions.

When you define your dictionary, the Python interpreter evaluates the functions and stores the values in the dictionary. To put this off until you generate your random numbers, try instead storing references to the functions themselves in your dictionary, by leaving off the parentheses:

def random_cube(self):
    scramble = {    0 : self.up_turn,
                    1 : self.down_turn,
                    2 : self.left_turn,
                    3 : self.right_turn,
                    4 : self.front_turn,
                    5 : self.back_turn,
                    6 : self.up_turn,
                    7 : self.down_turn,
                    8 : self.left_turn,
                    9 : self.right_turn,
                    10: self.front_turn,
                    11: self.back_turn
                }

Then when calling your functions in the for loop you'll have to distinguish between your normal and inverted cases by which parameters you pass:

    for x in range(50):
        i = random.randint(0,11)
        if i <= 5:
            scramble[i]()
        else:
            scramble[i]("inverted")

or more simply:

    for x in range(50):
        i = random.randint(0,11)
        scramble[i]( () if i < 6 else ("inverted"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!