factorial |
def factorial(n):
factorial = 1
for i in range(2,n+1):
factorial *= i
return factorial
print(factorial(5))
|
def factorial(n):
if (n < 2):
return 1
else:
return n*factorial(n-1)
print(factorial(5))
|
def factorial(n, depth=0):
print(" "*depth, "factorial(",n,"):")
if (n < 2):
result = 1
else:
result = n*factorial(n-1,depth+1)
print(" "*depth, "-->", result)
return result
print(factorial(5))
|
reverse |
def reverse(s):
reverse = ""
for ch in s:
reverse = ch + reverse
return reverse
print(reverse("abcd"))
|
def reverse(s):
if (len(s) < 2):
return s
else:
mid = len(s)//2
return (reverse(s[mid:]) +
reverse(s[:mid]))
print(reverse("abcd"))
|
def reverse(s, depth=0):
print(" "*depth, "reverse(",s,"):")
if (len(s) < 2):
result = s
else:
mid = len(s)//2
result = (reverse(s[mid:], depth+1) +
reverse(s[:mid], depth+1))
print(" "*depth, "-->", result)
return result
print(reverse("abcd"))
|
gcd |
def gcd(x,y):
while (y > 0):
(x, y) = (y, x%y)
return x
print(gcd(500, 420)) # 20
|
def gcd(x,y):
if (y == 0):
return x
else:
return gcd(y,x%y)
print(gcd(500, 420)) # 20
|
def gcd(x,y,depth=0):
print(" "*depth, "gcd(",x, ",", y, "):")
if (y == 0):
result = x
else:
result = gcd(y, x%y, depth+1)
print(" "*depth, "-->", result)
return result
print(gcd(500, 420)) # 20
|