Skip to content

Instantly share code, notes, and snippets.

@cyyeh
Created March 17, 2017 12:00
Show Gist options
  • Save cyyeh/64cf17586e2a5e3677e1100fd10811d0 to your computer and use it in GitHub Desktop.
Save cyyeh/64cf17586e2a5e3677e1100fd10811d0 to your computer and use it in GitHub Desktop.
# The Three Laws of Recursion
# 1. A recursive algorithm must have a base case.
# 2. A recursive algorithm must change its state and move toward the base case.
# 3. A recursive algorithm must call itself, recursively.
# Reverse String
def reverse(s):
if len(s) == 0 or len(s) == 1: # first law
return s
else:
return s[len(s) - 1] + reverse(s[:-1]) # second, third law
# Palindrome
def removeWhite(s):
newStr = ""
for i in range(len(s)):
if s[i].isalpha():
newStr += s[i].lower()
return newStr
def isPal(s):
if len(s) == 1: # first law
return True
elif len(s) == 2: # first law
return s[0] == s[1]
else:
if s[0] == s[-1]: # second and third law
return isPal(s[1:-1])
else:
return False
def main():
# Reverse String Test
print(reverse("hello"))
print(reverse("l"))
print(reverse("follow"))
print(reverse(""))
# Palindrome Test
print(isPal(removeWhite("I am a boy!")))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment