Having difficulty coming up with a solution using:
- iteration/control-flow and
- accumulation.
More than just a solution, would prefer having an answer with hints and explanation.
JavaScript
x
20
20
1
def falling(n, k):
2
"""Compute the falling factorial of N to depth K.
3
4
>>> falling(6, 3) # 6 * 5 * 4
5
120
6
>>> falling(4, 3) # 4 * 3 * 2
7
24
8
>>> falling(4, 1) # 4
9
4
10
>>> falling(4, 0)
11
1
12
"""
13
fact = n
14
i = 0
15
while i <= k:
16
fact = fact * fact - 1
17
i += 1
18
n -= 1
19
return fact
20
Advertisement
Answer
JavaScript
1
26
26
1
def falling(n, k):
2
"""Compute the falling factorial of N to depth K.
3
4
>>> falling(6, 3) # 6 * 5 * 4
5
120
6
>>> falling(4, 3) # 4 * 3 * 2
7
24
8
>>> falling(4, 1) # 4
9
4
10
>>> falling(4, 0)
11
1
12
"""
13
14
if k == 0:
15
return 1
16
17
return_value = 1
18
19
counter = 0
20
21
while counter < k:
22
return_value = return_value * (n-counter)
23
counter += 1
24
25
return return_value
26
Ignoring k=0 you have want to multiply k numbers starting with n and ending with n-k. The above loops k times and since i will increment by 1 starting from 0, you can simply subtract it from n to get the next number to multiply by.
Edit: Making sure k=0 is returning 1 always by returning early
Edit2: Removing built in range function
Edit3: making sure to go k deep