Lab Week 2 Binary Counter Factorial (Iterative) Factorial (Recursive) Fibonacci (Iterative) Matrix Multiplier Fibonacci (Matrix Multiplication) String Permutations Imported Code Project Code def binaryCount(N): if N == 0: return 0 if (N % 2) > 0: return 1 + binaryCount(N/2) return binaryCount(N/2) Commands print binaryCount(5) Run Output Imported Code Project Code def factorial(N): if (N % 1) > 0: return 1 base = 1 while (N > 1): base *= N N -= 1 return base Commands print factorial(4) Run Output Imported Code Project Code def factorial(N): if (N % 1) > 0: return 1 if N <= 1: return 1 return factorial(N-1)*N Commands print factorial(4) Run Output Imported Code Project Code def fib(N): A=[1,1] if N < 1: return 0 if N == 1: return 1 for i in range(2, N): A.append(A[i-2]+A[i-1]) return A[N-2]+A[N-1] Commands print fib(5) Run Output Imported Code Project Code def multiply(A, B): Co = [] Ci = [] if len(A[0]) != len(B): print "Matrix A is not as wide as B is tall!" return Co for i in range(len(A)): for j in range(len(B[0])): tmp = 0 for k in range(len(A[0])): tmp += A[i][k] * B[k][j] Ci.append(tmp) Co.append(Ci) Ci = [] return Co Commands print multiply([[1,2,3]], [[4],[5],[6]]) print multiply([[1,2,3]], [[4]]) Run Output Imported Code def multiply(A, B): Co = [] Ci = [] if len(A[0]) != len(B): print "Matrix A is not as wide as B is tall!" return Co for i in range(len(A)): for j in range(len(B[0])): tmp = 0 for k in range(len(A[0])): tmp += A[i][k] * B[k][j] Ci.append(tmp) Co.append(Ci) Ci = [] return Co def matrixPower(A, N): if N <= 1: return A B = matrixPower(A, N/2) C = multiply(B, B) if (N % 2) == 1: return multiply(A, C) return C Project Code def fib(N): if N < 2: return 1 N -= 1 A = multiply(matrixPower([[1,1],[1,0]], N), [[1],[1]]) return A[0][0] Commands print fib(5) Run Output Imported Code Project Code def _StringPerms(Str, A): if len(A) == 0: print ''.join(Str) return for i in range(len(A)): B = A.pop(i) Str.append(B) _StringPerms(Str, A) A.insert(i, B) Str.pop() def StringPerms(A): A = list(A) A.sort() _StringPerms([], A) Commands StringPerms("abcd") Run Output