Noche,
Soy una introducción a Python Student teniendo algunos problemas. Estoy tratando de hacer un progtwig factorial de python. Debe solicitar al usuario n y luego calcular el factorial de n A MENOS QUE el usuario ingrese -1. Estoy tan atascado, y el profesor sugirió que usáramos el bucle while. Sé que ni siquiera llegué al caso ‘if -1’ todavía. No sé cómo hacer que Python calcule un factorial sin utilizar simplemente la función math.factorial.
import math num = 1 n = int(input("Enter n: ")) while n >= 1: num *= n print(num)
La función factorial ‘clásica’ en la escuela es una definición recursiva:
def fact(n): rtr=1 if n<=1 else n*fact(n-1) return rtr n = int(input("Enter n: ")) print fact(n)
Si solo quieres una forma de arreglar el tuyo:
num = 1 n = int(input("Enter n: ")) while n > 1: num *= n n-=1 # need to reduce the value of 'n' or the loop will not exit print num
Si quieres una prueba para números menores a 1:
num = 1 n = int(input("Enter n: ")) n=1 if n<1 else n # n will be 1 or more... while n >= 1: num *= n n-=1 # need to reduce the value of 'n' or the loop will not exit print num
O, prueba n después de la entrada:
num = 1 while True: n = int(input("Enter n: ")) if n>0: break while n >= 1: num *= n n-=1 # need to reduce the value of 'n' or the loop will not exit print num
Aquí hay una forma funcional usando reducir :
>>> n=10 >>> reduce(lambda x,y: x*y, range(1,n+1)) 3628800
En realidad estás muy cerca. Solo actualiza el valor de n
con cada iteración:
num = 1 n = int(input("Enter n: ")) while n >= 1: num *= n # Update n n -= 1 print(num)
Soy nuevo en Python y este es mi progtwig factorial.
def factorial (n):
x = [] for i in range(n): x.append(n) n = n-1 print(x) y = len(x) j = 0 m = 1 while j != y: m = m *(x[j]) j = j+1 print(m)
factorial (5)