Home > Enterprise >  take all elements from the list with python
take all elements from the list with python

Time:02-20

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?

CodePudding user response:

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))

CodePudding user response:

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()

CodePudding user response:

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]
  • Related