How To Write This Sum Of A Sum Recursively In Python?
How would I write this function: My Question (the first answer), in python recursively? This is what I have so far: def f(n, p, k, t): sum(for p in xrange(1, 7): sum(fo
Solution 1:
You just have some of the bits mixed around.
For loops versus generator expressions
For loop:
for p in range(1, 7):
statement()
Generator expression:
expression() for p in range(1, 7)
Note that there is no colon and the value goes before the for
.
If statements versus conditional expressions
If statement:
if predicate():
true_stmt()
else:
false_stmt()
If expression:
true_expr() if predicate() else false_expr()
Putting it together
def f(n, p, k, t):
return sum(sum(1 if n == 3 else
(0 if k == 1 else
(1/36) * f(n-1, p, k-1, t-max(p,i))))
for i in range(1, 7))
for p in range(1, 7))
Post a Comment for "How To Write This Sum Of A Sum Recursively In Python?"