''' Create another list. (iterative) ''' def interpolate1(l): if l is not list: l = list(l) if len(l) > 2: for i in range(len(l)-1): l[i] = (l[i]+l[i+1])/2 return l[:-1] ''' Create another list. (recursive) ''' def interpolate2(l): def execute(l, r, i): if len(r) < len(l) - 1: r.append((l[i]+l[i+1])/2) return execute(l, r, i+1) return r if len(l) > 2: return execute(l, list(), 0) return l ''' Edit copy list in place. (recursive) ''' def interpolate3(l): def execute(l, i): l[i] = (l[i]+l[i+1])/2 if i < len(l)-2: return execute(l, i+1) return l if len(l) > 2: return execute(list(l), 0)[:-1] return l ''' baavgai's solution. ''' def interpolate4(l): if l is not list: l = list(l) if (len(l) < 2): return l[:-1] # this is the only return instance we'll ever create else: n = l.pop(0) # pop n2 = l.pop(0) # pop l.insert(0, n2) # push the last pop back r = interpolate4(l) # all self, now one number taken from top r.insert(0, (n+n2)/2) # do the math l.insert(0, n) # push the other number back, so we balance return r # return the result def interpolate5(l): if len(l) < 2: return [] else: result = [(l[0]+l[1])/2] result.extend(interpolate5(l[1:])) return result l = (0, 1, 2, 4, 8, 16, 32, 64, 128) print interpolate1(l) print interpolate2(l) print interpolate3(l) print interpolate4(l) print interpolate5(l)
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question