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.
- The semicolon is optional.
- The parenthesis in an
if
is optional. - To get the last element of list
a
, usea[-1]
, not reversinga
then get its first element. Use the built-in functions! Your modified
maxagent
can be written simply using themax
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)
精彩评论