factorial(n) = n*(n-1)*(n-2)*…1
factorial(n)=1
factorial(n)=n*factorial(n-1)
A procedure, factorial, that takes a natural number as its input, and returns the number of ways to arrange the input number of items.
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
Palindromes:match the first and last string, such as level.
A procedure is_palindrome, that takes as input a string, and returns a Boolean indicating if the input string is a palindrome.
def is_palindrome(s):
if s == "":
return True
else:
if s[1] == s[-1]:
return is_palindrome(s[1:-1])
else:
return false
Another way, using for loop, to write palindrome procedure.
def iter_palindrome(s):
for i in range(0, len(s)/2):
if s[i] != s[-(i + 1)]:
return False
return True