I'd like to map a value through a dictionary multiple times, and record the intermediate values. Since list.append() doesn't return a value, below is the best I've been able to come up with. Is there a better way to do this in Python, perhaps using a list comprehension or recursion?
def append(v, seq):
    seq.append(v)
    return v
def multimap(value, f, count):
    result = []
    for _ in range(count):
        value = append(f[value], result)
    return result
print( multimap('a', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'a'}, 4) )
Output:
['b', 'c', 'd', 'a']
                Another solution, inspired by functional programming. This solution is recursive and utterly inefficient.
def multimap(value, f, count):
    if count <= 0:
        return []
    return [ f[value] ] + multimap(f[value], f, count - 1)
                        You can also do this:
def multimap(val, f, count):
    result = []
    _ = [result.append(f[result[-1]] if result else f[val]) for _ in range(count)]
    return result
>>> multimap('a', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'a'}, 4)
['b', 'c', 'd', 'a']
But i don't think this counts as a python-esque solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With