Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-mapping a value while saving intermediate values

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']
like image 922
martineau Avatar asked Apr 09 '15 19:04

martineau


2 Answers

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)
like image 188
shx2 Avatar answered Nov 17 '22 17:11

shx2


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.

like image 34
VHarisop Avatar answered Nov 17 '22 18:11

VHarisop