Skip to main content
Code Review

Return to Answer

added 55 characters in body
Source Link
Thank you
  • 349
  • 1
  • 7

OrSide-effecting print_pascal function is probably bad – maybe just leave it definedefined in continuation passing style

Or maybe just leave it define in continuation passing style

Side-effecting print_pascal function is probably bad – maybe just leave it defined in continuation passing style

Source Link
Thank you
  • 349
  • 1
  • 7

I don't really have a lot of feedback on your code other than it feels awkward with things like

  1. side effect next(b, None) in pairwise
  2. starmap instead of list comprehension in pascal

They're not wrong but they just feel out of place to me. Here's how I might write your pascal program

def sliding (n,xs):
 if n > len(xs):
 return []
 else:
 return [xs[0:n]] + sliding(n, xs[1:])
 
def pascal (n):
 def loop (m, prev, k):
 if n == m:
 return k([prev])
 else:
 return loop(m + 1, [1] + [x + y for (x,y) in sliding(2, prev)] + [1], lambda rest: k([prev] + rest))
 return loop(1, [1], lambda x: x)
 
def print_pascal (n):
 [print(line) for line in pascal(n)]
print_pascal(10)
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

Or maybe just leave it define in continuation passing style

def sliding (n,xs):
 if n > len(xs):
 return []
 else:
 return [xs[0:n]] + sliding(n, xs[1:])
 
def pascalk (n,k):
 def loop (m, prev, k):
 if n == m:
 return k([prev])
 else:
 return loop(m + 1, [1] + [x + y for (x,y) in sliding(2, prev)] + [1], lambda rest: k([prev] + rest))
 return loop(1, [1], k)
pascalk(10, lambda rows: [print(row) for row in rows])
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
# [1, 7, 21, 35, 35, 21, 7, 1]
# [1, 8, 28, 56, 70, 56, 28, 8, 1]
# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
lang-py

AltStyle によって変換されたページ (->オリジナル) /