Recursion
def fact(n):
if n == 1:
return 1
else:
return n*fact(n-1)
a = fact(5)
print(a)
## This is a Recursion
Binary Search
## linear search -> bruteforce
##linear search first
def sqrt(p):
for i in range(p):
if i * i == p:
return i
a = sqrt(25)
##Here is binary search
def sqrt2(n):
low = 0
high = n
while low <= high:
mid = (low + high) // 2
if mid * mid == n:
return mid
if mid * mid > n:
high = mid - 1
else:
low = mid + 1
a = sqrt2(25)
print(a)
Print fibnacci numbers in 3 ways
##ordinary method
def f1(n):
if n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return f1(n-1) + f1(n-2)
##using dictionary(with notebook)
def f2(n, nb = {}):
##look up f2(n) in notebook first
if n in nb:
return nb[n]
if n == 0:
return 0
if n == 1:
return 1
#if not in notebook, then put it in
ans = f2(n-1, nb) + f2(n-2, nb)
nb[n] = ans
return ans
##using iteration
def f3(n):
a = 0
b = 1
for i in range(n):
a, b = b, a+b
return a
print(f1(9))
print(f2(9))
print(f3(9))
Stack in python
##stack
##First in last out
##plates = [ ]
##plate.append(1) -> contain [1]
##plate.append(2) -> contain [1, 2]
##x = plate.pop() -> x = 2
##plate.append(4) -> [1,4]
##y = plate.pop() -> y = 4
##len(plates) = 1
def rev(nums):
ans = []
while len(nums) > 0:
x = nums.pop()
ans.append(x)
return ans
nums = [1, 2, 4, 6, 8]
y = rev(nums)
print(y)
Queue in python
##Queue
##First in first out
##using the list in python like stack
##stack = [] queue = []
q = []
q.append(1)
q.append(2)
q.append(5)
q.append(14)
##q[-1] -> last item
##peek -> q[0] while queue
##pop -> pop(0) pop first item
##peek -> q[-1] while stack
##pop -> pop() pop last item
def sqr(nums):
ans= []
while len(nums) > 0:
x = nums.pop(0)
##if want to reverse:
## x = nums.pop( )
## *
ans.append(x*x)
return ans
print(sqr(q))