0
How to make a code for factorial of a input
10 Respostas
+ 5
Mrunmay dawkhar ,
the presented codes and solutions looks nice and are performing well. but recursion and lambda may not be what a beginner would want to try. i am also missing some explanations to these codes.
i wonder why nobody is showing a for loop, that can do this task also. it may be not look as cool as the other solutions, but here is the try:
number = int(input()) # (1)
res = 1 # (2)
for num in range(1,number +1): #(3)
res = res * num # (4)
print(res)
(1) input that is given has to be converted to int, as input returns a string by default
(2) a variable for the result is declared and initialized with 1. if 0 would be taken to initialize, the result will be 0 as a multiplication is performed
(3) for loop uses a range, starting with 1 and running up to input number. as the last number in range is excluded, we need to add +1
(4) the short version of this is: res *= num and can olso be used.
happy coding and good success!
+ 3
Calvin Thomas As much as I dislike how limited Python lambdas are, this was a super clean solution.
The walrus operator was a nice touch for making this recursively possible using the lambda.
Passing the input as an argument to the immediately self called lambda was brilliant.
Well done đ
+ 1
def fact(n):
if(n == 1 or n == 0):
return 1
return n*fact(n-1)
n = int(input("Enter a number = "))
print("Factorial of ",n," = ",fact(n))
+ 1
Mrunmay dawkhar Here's a one-liner:
print((a:=lambda x: x * a(x-1) if x else 1)(int(input())))
# Hope this helps
+ 1
David Carroll Thank you!
+ 1
Mrunmay dawkhar
I would like to share a code that was shown to me by Atul [Inactive] .
A simple solution, but I agree with Lothar , if you create your own simple code, you gain an understanding of why it works.
https://code.sololearn.com/cL9gw4Q4xAQZ/?ref=app
0
Make a recursion of function which return "num * factorial (num-1)"
Until num is 1 .& set stop condition as "if num ==1: return 1 "
đ
0
Thanks đ
0
Python is first language i am learning so this seems too complex for me
0
To learn python, You can check this out:
https://youtube.com/channel/UC3K2nGS4rvTfPlh-Rzx80OA