Call functions from list - Python

10,056

Solution 1

You're pretty close. You should just map your characters to the functions, as opposed to assigning to specific variables.

import random

def make_s():
    result = ''

    # Here we have a mapping between the characters you see,
    # and the functions you want to call.
    my_funcs = {"V": make_v,
                "C": make_c,
                "P": make_p,
                "B": make_b}

    structs = ['VPCVBCC', 'VCVVC', 'VVPCC', 'VCVBCC', 'VPCCVBC', 'VCVCC', 'VPCBC', \
            'VVPCVBCC', 'VCVC', 'VPCVVBC']

    struct = random.choice(structs)

    for elem in struct:
        # Lookup the function in your dictionary
        func_to_call = my_funcs[elem]
        # And call it!
        result += func_to_call()

    return result

Solution 2

Similar approach using dictionary to map characters to function calls, a bit more concise using list comprehension & the string join function:

import random
def make_s():
    fDict = {'V': make_v(), 'C': make_c(), 'P': make_p(), 'B': make_b()}
    structs = ['VPCVBCC', 'VCVVC', 'VVPCC', 'VCVBCC', 'VPCCVBC', 'VCVCC', 'VPCBC', \
            'VVPCVBCC', 'VCVC', 'VPCVVBC']
    struct = random.choice(structs)
    return ''.join([fDict[elem] for elem in struct])
Share:
10,056
ggordon
Author by

ggordon

Updated on June 04, 2022

Comments

  • ggordon
    ggordon almost 2 years

    I have a list of strings, and I want to call a function for every character in a string. When I assign variables to each function I do not want them to run, I only want to call them when iterating over the string. Here is my code:

    import random
    
    def make_s():
        result = ''
    
        V = make_v
        C = make_c
        P = make_p
        B = make_b
    
        structs = ['VPCVBCC', 'VCVVC', 'VVPCC', 'VCVBCC', 'VPCCVBC', 'VCVCC', 'VPCBC', \
                'VVPCVBCC', 'VCVC', 'VPCVVBC']
    
        struct = random.choice(structs)
    
        for elem in struct:
            /* Call function defined above and add the result to the result string */
            result += elem()
    
        return result
    

    What's the best way to go about doing this?

    Many thanks :)