how to point towards a method given variable python - python

possibleRequests = ['test', 'test1']
def inboxReader():
global inbox
tempInbox = []
tempInbox = inbox.inboxMessage #inboxMesage remains filled?
print(inbox.inboxMessage, 'inboxReader')
i = 0
while (i < len(tempInbox)):
if (tempInbox[i] in possibleRequests):
print('THIS IS WORKING')
#print(i)
i+=1
I want to be able to have possible requests point towards a method to run rather than have a long list of if statments. What am I able to do in order to have a variable point towards and run a method.
Cheers,
Marc

You can first create a dictionary of functions then refer to it with tempInbox[i]. Example code below:
def func_a(x):
return x
def func_b(x):
return x*10
tempInbox = (2,3)
fn_dict = {"a":func_a,"b":func_b}
print fn_dict["a"](tempInbox[0]) # returns 2
print fn_dict["b"](tempInbox[1]) # returns 30

Related

Store the output of a function into a variable

I have the following function that returns data:
def get_comments():
for i in data:
comment_data = i['comments']
for z in comment_data:
comments = comment_data['data']
for j in comments:
comment = j['message']
print(comment)
I would like to save the output of this function to a variable. I'm using print instead of return (in the function get_comments) since, return only returns the final row of my data. This is what i have tried to account for that:
def hypothetical(x):
return x
z = hypothetical(get_comments())
print(z)
However the output of the variable z is "None".
When i try some other value(i.e.):
z = hypothetical(5)
print(z)
z is equal to 5 of course.
Thanks
Instead of printing each line, you need to add it to a different data structure (such as a list) and return the whole list at the end of get_comments().
For example:
def get_comments():
to_return = []
for i in data:
comment_data = i['comments']
for z in comment_data:
comments = comment_data['data']
for j in comments:
comment = j['message']
to_return.append(comment)
return to_return
If you want to get a bit more advanced, you can instead create a generator using yield:
def get_comments():
for i in data:
comment_data = i['comments']
for z in comment_data:
comments = comment_data['data']
for j in comments:
comment = j['message']
yield comment
Then you can iterate over get_comments() and it will go back into the generator each time to get the next comment. Or you could simply cast the generator into a list with list(get_comments()) in order to get back to your desired list of comments.
Refer to this excellent answer for more about yield and generators.

Anybody know how to use pyresttest's 'fixed_sequence' generator?

I'm trying to use pyresttest's benchmarking framework to generate a sequence of entries in my flask_sqlalchemy-based database. I would like to read input values from a pre-defined list as advertised by this framework's benchmarking generator type 'fixed_sequence', but it's only picking up the first element of the list.
Here is the issue that explains my problem in detail, with an example: https://github.com/svanoort/pyresttest/issues/264
Any pointer in the right direction will be greatly appreciated
I looked into the code, it is jsut a bug, this feature was never used by anyone.
https://github.com/svanoort/pyresttest/blob/master/pyresttest/generators.py#L100
instead of:
```
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
if i == len(my_list):
i = 0
return seq_generator
It should be:
def factory_fixed_sequence(values):
""" Return a generator that runs through a list of values in order, looping after end """
def seq_generator():
my_list = list(values)
i = 0
while(True):
yield my_list[i]
i += 1
if i == len(my_list):
i = 0
return seq_generator
```
The i += 1 is missing

Python - How do I keep returning values from a function with a while statement?

So, the code outlined below sends arguments to a function I've created called bsearch and I want the function main() to send the arguments with the key argument scaled down by 1 from 11 (11,10,9,8,7...) until it reaches 0 an I want the value count outputted each time --- currently it only returns the first count. How do I get it to return after each while loop?
def main():
ilist = [x+1 for x in range(10)]
key = 11
start = 0
end = 10
while key > 0:
count = b(ilist,key,start,end)
key = key -1
return count
I think you might want to look at a few tutorials but I imagine you want something like this:
def main():
count_list = []
for x in range(1,11):
count_list.append(bsearch(x)) # append your results to a list
return count_list # return out of the scope of the loop
or using a list comprehension as suggested in the comments:
def main():
return [bsearch(x) for x in range(1,11)]

Issue with calling a function inside a while loop

I don't know if this is a simple question or not, but I couldn't find anything on it so I figured I would ask it.
I try to call a function in a while loop but it keeps on returning the same result until the condition is completed. The function main() is imported from another file and return a list with two elements [a,b].
Those two elements are generated randomly, therefor they should change after every step. The function works perfectly fine if I call it on its own.
Here is my code so far, I hope someone can help me:
I thought there was something wrong with my list x so I tried to delete it after every step, but it doesn't change anything.
from some_module import main
def loop(variable):
i = 0
while i <= 5 :
x = main(variable)
a ,b = x[0], x[1]
print a, b
del x[:]
i += 1
The code for main() is :
def main(file):
iniciate(file)
obtain_neighbours(initial_solution())
get_all_costs(get_all_solutions())
return get_best_solution()
And the random choice appears in the function initial_solution() :
#those list are being updated at every step
So = []
I_assign = []
I_available = ['1','2','3','4',...,'n']
def initial_solution():
while len(I_available) != 0:
update_I_assign()
random_task = random.choice(I_assign)
So.append(random_task)
I_available.remove(random_task)
return So
def get_best_solution():
if min(i for i in all_cost) < calculate_cost(fill_station(So)):
best_solution = solutions[all_cost.index(min(i for i in all_cost))]
return [min(i for i in all_cost),best_solution]
else:
best_solution = fill_station(So)
return [calculate_cost(fill_station(So)),best_solution]
It's pretty hard for me to show the rest of the code here because it's quite long. Hope the update helps you understand.

how to make variable = the value of a function call?

We have to use a previously made function (the mega_calculator) to calculate the average amount of property damage for 10 buildings. however, we need to find out which building is going to be the most destroyed, but we keep getting error messages about comparing functions to ints. for some reason, the y variable(used to store mega_calculator values) is being labeled as a function, and the if statements aren't being triggered.
We are trying to use a for loop but it doesn't change anything. We also tried asserting inside mega_calculator that the return value must be an integer type, but that didn't do anything. we tried saving the average value as a variable and asserting that as an integer type but that didn't do anything.
What should I do for that?
Any help is loved and appreciated greatly. We must have the weird function setup, so unfortunately I can't just make a nice simple while loop.
def mega_calculator(fn, repeat=1000):
def helper(*args):
total = 0
for _ in range(repeat):
total += fn(*args)
return total / repeat
return helper
def worst_hurricane(odds): """odds is a predefined function that tells us a random amount of property damage"""
index_variable = 1
big_boom = 0
place = 0
while index_variable <= 10:
y = mega_calculator(odds,50) """checking odds of damage for skyscrapers only, and finding the average after 50 times is what the function cal to mega_calculator does"""
print("building", a, "will have", y, "dollars of damage")
if y > big_boom:
big_boom = y
place = index_variable
elif y == big_boom:
place = max(place, index_variable)
index_variable +=
return place
`
mega_calculator is returning a function named helper, that you can call. Try code like this:
calculator = mega_calculator(odds)
y = calculator(50)
You also probably want to unindent index_variable += 4 positions to the left, and change it to index_variable += 1.
Here is what you are trying to do:
I am using some dummy function called, just to make you understand:
>>> def mega_calculator(some_function):
... def helper(*args):
... return some_function(*args)
... return helper
...
>>> def odds(*args):
... print args
...
>>> x = mega_calculator(odds)
>>> x
<function helper at 0x10c8f18c0>
>>>
>>> x = mega_calculator(odds)(['Here', 'are some' , 'argument'])
(['Here', 'are some', 'argument'],)
>>>

Categories