Factor factor in python,

Asked

Viewed 3,540 times

0

Guys, I’m new to programming, and doing exercises I came across the following question:

Make a program that calculates the factorial of an integer number provided by the user. Ex.: 5!=5.4.3.2.1=120

How to use the pycharm to solve this?

  • f=lambda x :x if x<=2 else x*f(x-1)

2 answers

2

For the factorial problem it is quite simple to solve using a recursive function:

def fatorial(n):
    if n<=1:
        return 1
    else:
        return n*fatorial(n-1)

2

Well, there are several ways to solve your problem. Two very simple ways are using recursion and a simple loop:

def fat1(n):
    if n <= 1:
        return 1
    return n*fat1(n-1)

def fat2(n):
    resultado = 1
    for i in range(1, n+1):
        resultado *= i
    return resultado

Another option, in a more functional style:

from functools import reduce
from operator import mul

def fat3(n):
    return reduce(mul, range(1, n+1), 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.