Skip to content

Instantly share code, notes, and snippets.

@TheRayTracer
Last active October 3, 2015 13:58
Show Gist options
  • Save TheRayTracer/2464043 to your computer and use it in GitHub Desktop.
Save TheRayTracer/2464043 to your computer and use it in GitHub Desktop.
Examples of handy functions including Factorial, Fibonacci and palindrome finding functions using both recursion and loops.
def get_factorial_recursively(i):
f = 1
if i > 1:
f = f * i * get_factorial_recursively(i - 1)
return f
def get_factorial_iteratively(i):
f = 1
for j in range(2, i + 1):
f = f * j
return f
def get_factorial_string_iteratively(i):
s = "1"
for j in range(2, i + 1):
s = s + ", " + str(j)
return s
def get_fibonacci_series_term_recursively(i):
f = i
if i > 1:
f = get_fibonacci_series_term_recursively(i - 1) + get_fibonacci_series_term_recursively(i - 2)
return f
def get_fibonacci_series_term_iteratively(i):
f, f1, f2 = 0, 0, 1
for j in range(0, i):
f = f1 + f2
f2 = f1
f1 = f
return f
def get_fibonacci_series_string_iteratively(i):
s = "0"
f, f1, f2 = 0, 0, 1
for j in range(0, i):
f = f1 + f2
f2 = f1
f1 = f
s = s + ", " + str(f)
return s
def reverse(str):
return str[::-1]
def palindrome_recursively(str):
r = True
i = len(str)
if i > 1:
if str[:1] == str[i - 1:]:
r = palindrome_recursively(str[1:i - 1])
else:
r = False
return r
def palindrome_iteratively(str):
r = True
i = len(str)
if i > 1:
half = i // 2
for j in range(0, half):
if str[j:j + 1] != str[i - j - 1:i - j]:
r = False
return r
if __name__ == "__main__":
answer = get_factorial_recursively(6)
assert(answer == 720)
answer = get_factorial_iteratively(6)
assert(answer == 720)
answer = get_fibonacci_series_term_recursively(7)
assert(answer == 13)
answer = get_fibonacci_series_term_iteratively(7)
assert(answer == 13)
answer = get_fibonacci_series_string_iteratively(4)
assert(answer == "0, 1, 1, 2, 3")
hw = "Hello World!"
answer = reverse(hw)
assert(answer == "!dlroW olleH")
assert(palindrome_recursively("helloolleh") != False)
assert(palindrome_recursively("helolleh") == False)
assert(palindrome_iteratively("helloolleh") != False)
assert(palindrome_iteratively("helolleh") == False)
input("Press <Enter>")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment