|
1.
Finding the factorial of a number
|
# to find the factorial of a number. program loops, asking the user a
# number, which it uses to find the factorial. Enter -1 to quit the loop
# and exit the program
myfactorial = 0 #final factorial value
what_factorial = 0 #the factorial number the user wants to find
print "Finding e...."
def myfact (n) :
if (n == 1):
return 1
f_value = n * myfact(n-1)
return f_value
while (1) :
what_factorial = int(raw_input("Factorial : [enter -1
to quit] "))
if (what_factorial == -1) :
break;
else :
myfactorial = myfact(what_factorial)
print "e = ", myfactorial
|
|
2.
Generate the Fibonacci series
|
#Recursive fibonacci series
#
def fibonacci(n):
if (n < 0) :
print "Cannot find the fibonacci of a negative
number..."
if (n ==0) or (n == 1) : #base case
return n
else :
#two recursive calls
return fibonacci(n-1) + fibonacci(n-2)
number = int(raw_input("Enter an integer to generate the Fibonacci
series :"))
result = fibonacci(number)
print "Fibonacci (%d) = %d" % (number, result)
|