-1
import math


def lista_fact(list, k):
    for n in list:
        result = math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
    return result
    print(res)

lista = [4, 6, 5]
print(lista_fact(lista, 3))

The output of the code about is showing me only the factorial result for the last element from my list. How should I code to take all the elements from that list?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Stefan23
  • 11
  • 1
  • That's because you're calculating result and at the end of for loop, return result, which would be last calculated value. You may create a list of result and return it. – gajendragarg Feb 20 '22 at 09:36

3 Answers3

1

A short answer

def lista_fact(nlist, k): # 0
    fk = math.factorial(k)  # 1
    return [math.factorial(n) // (fk * math.factorial(n - k)) for n in nlist]  # 2
  1. parameter renamed as list is a python word

  2. fk : optimization

  3. integer division

    list comprehension

By the way, the function needs to be optimized for large numbers For instance building on other solutions Statistics: combinations in Python(base function is binomial function) We could use something like :

binomial_reduce = lambda n, k : reduce(int.__mul__, range(n-k+1, n+1)) // math.factorial(k)

def binomial_reduce_list(nlist, k):
    return [binomial_reduce(n, k) for n in nlist]
hpchavaz
  • 1,368
  • 10
  • 16
0

you should change result to a list like this:

def lista_fact(list, k):
    result = []
    for n in list:
        result.append(math.factorial(n) / (math.factorial(k) * math.factorial(n - k)))
    return result
    print(res)
lista = [4, 6, 5]
print(lista_fact(lista, 3))
0
import math


def factorial_list(my_input: list, k: int) -> list:
    results = []
    for n in my_input:
        current_result = math.factorial(n) / (math.factorial(k) * math.factorial(n - k))
        results.append(current_result)
    return results


def factorial_list_one_liner(my_input: list, k: int) -> list:
    results = [math.factorial(n) / (math.factorial(k) * math.factorial(n - k)) for n in my_input]
    return results


def main():
    input_list = [4, 6, 5]
    results_list = factorial_list(my_input=input_list, k=3)
    print(results_list)
    results_list = factorial_list_one_liner(my_input=input_list, k=3)
    print(results_list)
    return


if __name__ == '__main__':
    main()
gilad eini
  • 360
  • 2
  • 6