Skip to content

Instantly share code, notes, and snippets.

View cyyeh's full-sized avatar
👋
Focusing

Chih-Yu Yeh cyyeh

👋
Focusing
View GitHub Profile
# 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.
import turtle
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
class Node:
# constructor
def __init__(self, initdata):
self.data = initdata
self.next = None
# get value from node
def getData(self):
return self.data
class Node:
# constructor
def __init__(self, initdata):
self.data = initdata
self.next = None
# get value from node
def getData(self):
return self.data
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addFront(self, item):
self.items.append(item)
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0, item)
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
# 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:
# Euclid's algoithm
def gcd(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
class LogicGate:
def __init__(self,n):
self.name = n
self.output = None
def getName(self):
return self.name
def getOutput(self):
self.output = self.performGateLogic()
function count(arr, arrLength, target) {
if (target === 0)
return 1;
if (target < 0 || (arrLength <= 0 && target >= 1))
return 0;
return count(arr, arrLength - 1, target) + count(arr, arrLength, target-arr[arrLength - 1]);
}