Skip to content

Instantly share code, notes, and snippets.

@jjlumagbas
Created December 6, 2016 03:11
Show Gist options
  • Save jjlumagbas/046aba4263331997c905b1032ad7d48b to your computer and use it in GitHub Desktop.
Save jjlumagbas/046aba4263331997c905b1032ad7d48b to your computer and use it in GitHub Desktop.
Exam solutions
def factorial(n):
"""
Int -> Int
Compute the factorial of n
"""
result = 1
for i in range(1, n + 1):
result = result * i
return result
print(factorial(0)) # 1
print(factorial(1)) # 1
print(factorial(2)) # 2 * 1 = 2
print(factorial(3)) # 3 * 2 * 1 = 6
print(factorial(4)) # 4 * 3 * 2 * 1 = 24
print(factorial(5)) # 5 * 4 * 3 * 2 * 1 = 120
def count_div_2(n):
"""
Counts the number of times n can be divided
by 2 before reaching 1
"""
count = 0
while (n != 1):
count = count + 1
n = n // 2
return count
print(count_div_2(1)) # 0
print(count_div_2(4)) # 2
print(count_div_2(5)) # 2
print(count_div_2(11)) # 3
def palindrome(word):
reverse = ""
for ch in word:
reverse = ch + reverse
return reverse == word
def palindrome1(word):
for i in range(0, len(word) // 2):
if (word[i] != word[len(word) - (i + 1)]):
return False
return True
print(palindrome("MADAM"))
print(palindrome("ABBA"))
print(palindrome("hello"))
print(palindrome1("MADAM"))
print(palindrome1("ABBA"))
print(palindrome1("hello"))
def acronym(phrase):
result = phrase[0].upper()
prev = phrase[0]
for ch in phrase:
if (prev == " "):
result = result + ch.upper()
prev = ch
return result
def acronym1(phrase):
result = phrase[0].upper()
for i in range(1, len(phrase)):
if (phrase[i - 1] == " "):
result = result + phrase[i].upper()
return result
print(acronym1("random access memory"))
print(acronym1("As soon as possible"))
print(acronym1("be right back"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment