python - recursive dict comprehension -
i building out complex dictionary unconventional code. i'm curious if there way check current dictionary's value or current list's values while building out avoid duplicates/unwanted values. here code have:
locations = {words[i]: map(lambda x: words[x::].index(words[i]) if words[i] in words[x::] , words[x::].index(words[i]) not in self[words[i]] else none, range(len(words))) in range(len(words))} # important part here , words[x::].index(words[i]) not in self[words[i]]
is above possible without for/while iteration?
i doubt can access list being built comprehension, doesn't exist far.
nevertheless, doesn't mean cannot build list removing duplicates in functional manner. (just keep in mind python doesn't allow tco.)
if want build list list, using lists , not sets, ordered sets or like, 1 way (half-way functional style):
def removeduplicates (inlist, acc): if not inlist: return acc if inlist [0] in acc: return removeduplicates (inlist [1:], acc) return removeduplicates (inlist [1:], acc + [inlist [0] ] ) #even tail-recursive, although doesn't in python print (removeduplicates ( [1,2,3,2,3,5,1], [] ) )
works. let's build lambda-expression out of it:
rd = lambda inlist, acc: acc if not inlist else rd (inlist [1:], acc + ( [] if inlist [0] in acc else [inlist [0] ] ) ) print (rd ( [1,2,3,2,3,5,1], [] ) )
works, too. let's prepare lambda anonymity , recursion:
rd2 = lambda f, inlist, acc: acc if not inlist else f (f, inlist [1:], acc + ( [] if inlist [0] in acc else [inlist [0] ] ) ) rec = lambda f, *a: f (f, *a) print (rec (rd2, [1,2,3,2,3,5,1], [] ) )
still works. let's remove name lambdas , got recursive lambda builds list while removing duplicates (without for
or other imperative loops):
print ( (lambda f, *a: f (f, *a) ) (lambda f, inlist, acc: acc if not inlist else f (f, inlist [1:], acc + ( [] if inlist [0] in acc else [inlist [0] ] ) ), [1,2,3,2,3,5,1], [] ) )
not readable, functional , recursive.
if functional programming, lambda f, *a: f (f, *a)
sure close friend of yours.
inb4 import this
, pep8.
Comments
Post a Comment