Using primitive operators to find factorial of N up to K depth

Question:

Having difficulty coming up with a solution using:

  1. iteration/control-flow and
  2. accumulation.

More than just a solution, would prefer having an answer with hints and explanation.

def falling(n, k):
    """Compute the falling factorial of N to depth K.

    >>> falling(6, 3)  # 6 * 5 * 4
    120
    >>> falling(4, 3)  # 4 * 3 * 2
    24
    >>> falling(4, 1)  # 4
    4
    >>> falling(4, 0)
    1
    """
    fact = n
    i = 0    
    while i <= k:
        fact = fact * fact - 1
        i += 1
        n -= 1
    return fact
Asked By: mks

||

Answers:

def falling(n, k):
    """Compute the falling factorial of N to depth K.

    >>> falling(6, 3)  # 6 * 5 * 4
    120
    >>> falling(4, 3)  # 4 * 3 * 2
    24
    >>> falling(4, 1)  # 4
    4
    >>> falling(4, 0)
    1
    """
    
    if k == 0:
        return 1

    return_value = 1

    counter = 0

    while counter < k:
        return_value = return_value * (n-counter)
        counter += 1

    return return_value

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

Answered By: Timbolt

since you dont want a solution, but rather want why the code is failing, ill give you some pointers

Logic is wrong here is why

  • fact is being updated every iteration,
  • double check the while condition i < k or i <= k?
Answered By: hisokareddy

First you need generate numbers to apply multiplication on

e.g # 6 * 5 * 4
we get that by using

range(n, k, -1) => e.g for (n, k) = (6, 3) would be [6, 5, 4]

then accumulating list items products product with reduce.

def falling(n, k):
    return reduce(lambda x, y: x * y, list(range(n, k, -1)))

# more readable

```python
def falling(n, k):
    from operator import mul
    return reduce(mul, list(range(n, k, -1)))

lambda x, y: x * y => just get the product of two number

in python 3.8+

you would use math.prod()

def factorial_with_depth(n, k):
    """Compute the falling factorial of n to depth k."""
    from math import prod  # python 3.8+
    return prod(range(n, k, -1))
Answered By: Yusuf Adel
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.