Multi-display values ​​while storing intermediate values

I would like to match a value through a dictionary several times and write down intermediate values. Since list.append() does not return a value, this is the best I could come up with. Is there a better way to do this in Python, perhaps using 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'] 
+6
source share
4 answers

Instead of dealing with lists, you can simply use the generator:

 def multimap(value, f, count): for _ in range(count): value = f[value] yield value print(list(multimap('a', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'a'}, 4))) 
+5
source

Another solution inspired by functional programming. This solution is recursive and completely inefficient.

 def multimap(value, f, count): if count <= 0: return [] return [ f[value] ] + multimap(f[value], f, count - 1) 
+1
source

Shortly after I submitted my question and left for a while to grab the byte, I thought of one answer that is different from all the others published so far ... and after a bit of optimization, apart from some initialization, is relatively simple.

One of the function’s arguments is count , which allows you to partially initialize the resulting list in advance, eliminating the need to grow it with a few append calls:

 def multimap(value, f, count): result = [] if count < 1 else [f[value]] + [None]*(count-1) for i in range(1, count): result[i] = f[result[i-1]] return result 
+1
source

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 is considered a python-esque solution.

0
source

Source: https://habr.com/ru/post/984917/


All Articles