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:
ifpredicate():
true_stmt()
else:
false_stmt()
If expression:
true_expr() if predicate() else false_expr()
Putting it together
deff(n, p, k, t):
returnsum(sum(1if n == 3else
(0if k == 1else
(1/36) * f(n-1, p, k-1, t-max(p,i))))
for i inrange(1, 7))
for p inrange(1, 7))
Post a Comment for "How To Write This Sum Of A Sum Recursively In Python?"