开发者

list query, functions in function

开发者 https://www.devze.com 2023-01-10 01:05 出处:网络
i have a fu开发者_C百科nction: I need to first reverse the list and then take an entry from it. Earlier, I was making the 3 functions but now I am defining the main function and the other 2 functio

i have a fu开发者_C百科nction:

       I need to first reverse the list and then take an entry from it.

Earlier, I was making the 3 functions but now I am defining the main function and the other 2 functions in it.


Your code is very unpythonic. Remember Python is not C.

  1. The semicolon is optional.
  2. The parenthesis in an if is optional.
  3. To get the last element of list a, use a[-1], not reversing a then get its first element.
  4. Use the built-in functions! Your modified maxagent can be written simply using the max function:

    def maxagent(gamestate, depth):
        actions = gamestate.getLegalActions(0)
        filteredactions = filter(lambda action: action != Directions.STOP, actions)
        # alternatives: 
        #    filteredactions = filter(Directions.STOP.__ne__, actions)
        #    filteredactions = (a for a in actions if a != Directions.STOP)
        bestaction = max(filteredactions,
                         key=lambda action: self.minvalue(
                                              gamestate.generateSuccessor(0, action),
                                              depth, 1
                                            ))
        return bestaction
    

If you need the score too, consider returning a tuple.

def maxagent(gamestate, depth)
    actions = gamestate.getLegalActions(0)
    scores = ( (self.minvalue(gamestate.generateSuccessor(0, a), depth, 1), a)
               for a in actions if a != Directions.STOP
             )
    return max(scores)
...
score, action = maxagent(gamestate, depth)
0

精彩评论

暂无评论...
验证码 换一张
取 消