Shuffling in python - python

I'm trying to shuffle an array of functions in python. My code goes like this:
import random
def func1():
...
def func2():
...
def func3():
...
x=[func1,func2,func3]
y=random.shuffle(x)
And I think it might be working, the thing is that I don't know how to call the functions after I shuffle the array!
if I write "y" after the last line, it doesn't do anything!
Thanks

Firstly, random.shuffle() shuffles the list in place. It does not return the shuffled list, so y = None. That is why it does nothing when you type y.
To call each function, you can loop through x and call each function like so:
for function in x:
function() # The parentheses call the function
Lastly, your functions actually produce a SyntaxError. If you want them to do nothing, add pass at the end of them. pass does absolutely nothing and is put where python expects something.
So altogether:
def func1():
pass
def func2():
pass
def func3():
pass
x = [func1, func2, func3]
random.shuffle(x)
for function in x:
function()

Related

How to get variable but not call function

i'm trying to get the value from an inside function func2, to put it outside without calling func1 and func2. Here is my program:
def func1():
def func2(x, y, z):
# global str
str = "Xin chao`"
# func2()
#func1()
print("Result:", str)
If you don't call the functions, that variable doesn't exists. You could declare it global but it will not take the value Xin chao if you don't call those functions

How to pass function as variable with fixed argument

I'm newbie in Python, but the second time I encouter this problem.
Problem:
In some libraries there are functions with arguments. Sometimes there is argument as function, like this:
def somefun(fun):
x = [1,2,3]
z = fun(x)
return z
And I want to pass there some other function like this:
def func(x,y):
return x*y
which have more than one argument. I want to make one argument static, so somefun except func as argument.
Finally I want to make some kind of cycle where I can change static arg.
Something like this:
for i in xrange(1,9):
somefun(func(i,*))
Please do not offer me to change any functions. They are from library and it's not very comfortable to change them.
Thanks a lot!
You can use lambda statement:
somefun(lambda x: func(i, x))
It sure sounds like you are looking for functools.partial. From the docs:
functools.partial(func, *args, **keywords)
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords.
In your example, you could pass partial(func, 10) as the argument to somefun. Or you could create the partial objects and use them in a loop:
for i in xrange(1,9):
somefun(partial(func, i))
My solution with decorator
from functools import wraps
import numpy as np
def p_decorate(f):
#wraps(f)
def wrapped(*args):
z = f(*args)
return z
return wrapped
#p_decorate
def myfunc(a,b):
"""My new function"""
z = np.dot(a,b)
return z
x = [1,2,3]
y = [4,2,0]
r = myfunc(x,y)
print (r)
print (myfunc.__name__)
print (myfunc.__doc__)
You can change myfunc as you wish.You can also insert more function layers.Without the use of this decorator factory,you would lose the name of myfunc and the docstring.

A function that calls X function

I want to basically turn a list element into a function with
the do function. This way any pre-written funcction i can call by just use a
do(list[x]).
What im trying to do is a function that takes away the quotes of a list element and then executes the function that is in that list element.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
#I think the problem is here
funs = ['func()','func1()','func2()']
print ''.join(funs[0])
do(''.join(funs[0]))
Edit:
What im trying to do is a function that takes away the quotes of a
list element and then executes the function that is in that list
element
You don't need the extra functions, and you don't need to turn them into a string either:
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
funcs = [func, func1, func2]
for function in funcs:
function()
Well, it basically works like this. Note that the list contains the functions themselves, not a string.
def func():
print "python"
def func1():
print "is"
def func2():
print "awesome"
def do(fun):
fun()
funcs = [func, func1, func2]
for function in funcs:
do(function)
Output:
python
is
awesome
EDIT: If you do want the list to contain the functions' names as strings, use eval():
funcs = ['func', 'func1', 'func2']
for function in funcs:
do(eval(function))
If you really want to execute arbitrarily named functions from a list of names in the current global/module scope then this will do:
NB: This does NOT use the potentially unsafe and dangerous eval():
Example:
def func():
return "python"
def func1():
return "is"
def func2():
return "awesome"
def do(func_name, *args, **kwargs):
f = globals().get(func_name, lambda : None)
if callable(f):
return f(*args, **kwargs)
funs = ["func", "func1", "func2"]
print "".join(funs[0])
print "".join(map(do, funs))
Output:
$ python foo.py
func
pythonisawesome
You can also individually call "named" functions:
>>> do(funs[0])
python
Note the implementation of do(). This could also be applied more generically on objects and other modules too swapping out globals() lookups.
As the people above have said the best way is to define a dictionary of functions, as functions are objects in python this is possible
def One():
pass
def Two():
pass
functions = {"ONE":One, "TWO":Two}
You can then call it like this:
functions[input]()
If you want to give true control to the user (And I DO NOT recommend doing this) you could use the eval function.
eval(input+"()")

How to simultaneously access a global variable used inside while loop in another function?

I want to access the value of a variable which is being modified by the while loop, to be continuously printed outside loop. What I did:
x=0
def funcA():
global x
while True:
x=x+1
return x
def funB():
print x
Now, I want x to keep print continously:
1
2
3 and so on!
But it does not. I DONT WANT THIS:
def funB():
while True:
print x
That is to say that I dont want any while loop inside function funcB().
Thank you very much!
I don't know if this is what you are looking for, but you could use a generator.
def funcA():
x = 0
while True:
yield x
x += 1
def funcB():
for x in funcA():
print x #=> 1, 2, 3...
You don't have a useful loop anywhere. In funcA, you have a while True:, but it just does a return every time through the loop, meaning it just runs once.
So, you could put a loop outside the two functions:
while True:
funcA()
funB()
Or, you could fix funcA so it loops forever instead of just once, then call funB from inside it:
def funcA():
global x
while True:
x=x+1
funB()
Or you could pass funB to funcA and have it call whatever it gets passed:
def funcA(*functions):
global x
while True:
x=x+1
for function in functions:
functions()
funcA(funB)
Or you could make funcA yield each time through the loop instead of returning, and use that to drive funB:
def funcA():
global x
while True:
x=x+1
yield x
for _ in funcA():
funB()
Or… there are all kinds of things you could do. The question is what you actually want to do. If you can explain that, someone can help you write it.
Meanwhile, you don't actually need a global variable in most of these cases. Given that funcA is already trying to return x, you can just pass the returned value in to funB in the outer-loop version, or pass x itself to funB and to function in the next two versions, and pass the yielded value in the generator version, …
A callback would work and avoids the need for a global x:
def funcA(cb):
x = 0
while True:
x=x+1
cb(x)
def funB(a):
print a
funcA(funB)

Checking what function was passed into a function

I have a function that takes a function as one of its arguments, but depending on the context that function could be one of several (they are all comparator functions for creating rules for the sorted method). Is there any way to check which function was passed into a function? What I'm thinking is some kind of conditional logic like this:
def mainFunction (x, y, helperFunction):
if helperFunction == compareValues1():
do stuff
elif helperFunction == compareValues2():
do other stuff
etc. Would this work? Would I need to pass in all of the arguments for the function when checking for its existence? is there a better way?
You are on the right track, you just need to remove those parentheses:
def mainFunction (x, y, helperFunction):
if helperFunction == compareValues1(): <-- this actually CALLS the function!
do stuff
elif helperFunction == compareValues2():
do other stuff
Instead you would want
def mainFunction (x, y, helperFunction):
if helperFunction is compareValues1:
do stuff
elif helperFunction is compareValues2:
do other stuff
>>> def hello_world():
... print "hi"
...
>>> def f2(f1):
... print f1.__name__
...
>>> f2(hello_world)
hello_world
its important to note this only checks the name not the signature..
helperFunction==compareValues1
Since functions are itself an object in python, So, when you pass a function to your function, a reference is copied to that parameter.. So, you can directly compare them to see if they are equal: -
def to_pass():
pass
def func(passed_func):
print passed_func == to_pass # Prints True
print passed_func is to_pass # Prints True
foo = func # Assign func reference to a different variable foo
bar = func() # Assigns return value of func() to bar..
foo(to_pass) # will call func(to_pass)
# So, you can just do: -
print foo == func # Prints True
# Or you can simply say: -
print foo is func # Prints True
So, when you pass to_pass to the function func(), a reference to to_pass is copied in the argument passed_func

Categories

Resources