0

I have been playing around with dictionaries and trying to become more comfortable with them. I came across this post, which got me thinking about potential applications. Before getting ahead of myself, I tried to start with a basic example.

import numpy as np

times = np.linspace(0,20,21)
obs = np.linspace(50,100,21)

def square(x):
    return x**2

def cube(x):
    return x**3

def root_six(x):
    return x**(1/6)

dispatcher = {'sq':square, 'cb':cube, '6th':root_six}

def gimme(func_dict=dispatcher, values=times):
    res = []
    for func in func_dict:
        res.append(func(t) for t in values)
    return res

gg = np.array(list(gimme())) # I tried various combinations
print(gg)

>> [<generator object gimme.<locals>.<genexpr> at 0x101b886d0>
>> <generator object gimme.<locals>.<genexpr> at 0x108fc1678>
>> <generator object gimme.<locals>.<genexpr> at 0x108fc1a40>]

How can I test whether my code is executing correctly?

1 Answers1

3

Don't append a generator expression. I don't see why you'd want to do that here. Use a list comprehension:

res.append([func(t) for t in values])

If you'd like to have a list for every func in func_dict. If not, use extend which will consume the generator.

Not using the brackets creates a generator expression that isn't evaluated. If you evaluated you'd spot another issue with your code too: func is just the string name of the function! You should change your for loop to iterate through the values, instead:

for func in func_dict.values():
    res.append([func(t) for t in values])
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253