Reputation: 13
I am trying to write a program that do some random moves, and it have a lot of functions, the program select like a keyword to use the function, but my code get big for something simple, there is a simpler way to write this code?
list_mov = ["R", "RI", "L", "LI", "U", "UI", "D", "DI", "F", "FI", "B", "BI"]
mov = random.choice(list_mov)
# Here i need to make a list of selected functions
resolution.append(mov)
if mov == "R":
mov_r()
if mov == "RI":
mov_ri()
if mov == "L":
mov_l()
if mov == "LI":
mov_li()
if mov == "U":
mov_u()
if mov == "UI":
mov_ui()
if mov == "D":
mov_d()
if mov == "DI":
mov_di()
if mov == "F":
mov_f()
if mov == "FI":
mov_fi()
if mov == "B":
mov_b()
if mov == "BI":
mov_bi()
Upvotes: 1
Views: 253
Reputation: 7211
Everything is an object in python. Functions included. So I can write this:
list_mov = {
"R": mov_r,
"RI": mov_ri,
"L": mov_i,
... # fill in more here
}
mov = random.choice(list(list_mov.keys()))
# Here i need to make a list of selected functions
resolution.append(mov)
# get function, then execute it
func = list_mov[mov]
func()
Upvotes: 2
Reputation: 13387
You can actually select from list of function instances, and then call the one you randomly selected, like:
import numpy as np
def x():
print("function x!")
def y():
print("y here.")
def z():
print("zzz")
av_functions=[x,y,z]
mv=np.random.choice(av_functions)
mv()
Upvotes: 0
Reputation: 53
In python, everything is an object. You can simply do this: list_mov = [mov_r, mov_l, ...]
Because of this, you can use:
mov = random.choice(list_mov)
mov()
Upvotes: 0
Reputation: 3095
You can just create a list of functions and choose from them to a variable (as you do with strings). They all have the same parameters, so it should be easy:
list_mov = [mov_r, mov_ri, ...]
mov = random.choice(list_mov)
resolution.append(mov)
# And finally
mov()
Upvotes: 0