user1476390
user1476390

Reputation: 301

how to make a list of functions execute in python?

I am trying to save the results of 10 function calls into a list. however, when I want to access this numerical data, I keep getting type errors, because the list is really a list of function calls. How do I make it do stuff so I can have numbers to do compare?

I tried setting temp variable to result of each spot in the list, but it still shows as a function.

Output should show the average for different # of dice, and return the best amount of dice to roll

def calculator(fn, num_samples=1000): # this is the function I'm trying to call
    def print_and_return(*args):
            total3 = 0
            for _ in range(num_samples):
                total3 += (fn(*args))
            return float(total3)/num_samples
        return print_and_return

def find_average(dice=six_sided):
    avglist = []
    k, spot = 0, 0
    bob = roll_dice(k+1, dice)
    passed_function = calculator(bob, 1000)

    print(passed_function)
    while k <= 10:
        avglist.append((passed_function)) # <==trying to save the results when I check with 1-10 dice rolls
        if k == 0:
            spot = 1
        else:
            temp = 0
            max = 0
            i = 0
            while i <= len(avglist):
                temp = avglist[i]
                if max > temp:
                    max = temp
                i +=1

            if (avglist[k] > temp):
                spot = k
        print(k, "dice scores", avglist[k], "on average")
        k +=1 
    return spot

Upvotes: 0

Views: 154

Answers (2)

Magnus Reftel
Magnus Reftel

Reputation: 1009

Your calculator function returns a function, not a plain value. You therefore need to call passed_function in order to get your result.

Based on the arguments to your call to roll_dice, it looks like you want the k argument to vary in the loop. As written now, it will not. I suspect you are tripping yourself up a bit. The code could be written a whole lot simpler without so many function references being passed around.

Upvotes: 2

Brave Sir Robin
Brave Sir Robin

Reputation: 1046

You are not calling passed_function. Calling a function with no arguments still reqires the ().

Upvotes: 2

Related Questions