Python Code Snippets and Programming Concepts
HW9: Shift String
Function caesar
shifts letters in a string:
def caesar(left, shift):
ref = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
con = ""
letf = left.strip().upper()
for x in range(0, len(left)):
if letf[x] not in ref:
con += letf[x]
else:
con += ref[(ref.find(left[x]) + shift) % 26]
return con
CW10: Recursion
Function fib
calculates Fibonacci numbers recursively:
def fib(n):
if n in [1, 2]:
return 1
else:
return fib(n - 1) + fib(n - 2)
Note: The original code had a typo (n+1) and would cause an infinite loop. It should be (n-2). Use Ctrl + C to stop infinite loops.
HW10: Syntax and Runtime Errors
Syntax Errors
Example of syntax errors.
Runtime Errors
Example of runtime errors (e.g., variable not defined).
Logic Errors
Example of logic errors (e.g., missing parenthesis).
CW11: Classes
Employee Class
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
def initial(self):
return self.first[0] + self.last[0]
def number_letter(self):
return len(self.first) + len(self.last)
Executive Class (Inheritance)
class Executive(Employee):
def __init__(self, first, last, salary, term):
super().__init__(first, last)
self.salary = salary
self.term = term
def pv_salary(self):
pv = round(sum([self.salary / 1.005 ** i for i in range(1, self.term + 1)]))
return f"The present value of {self.first} {self.last}'s {self.term} months of salaries is ${pv}."
Set Operations
{1, 2, 5}.union({2, 3, 5})
>>{1, 2, 3, 5}
{1, 2, 5}.intersection({2, 3, 5})
>>{2, 5}
{2, 3}.symmetric_difference({2, 4, 5})
>>{3, 4, 5}
{2, 3} - {2, 4, 5}
>>{3}
Built-in functions: max(list)
, min(list)
, sum(list)
CW12: File Handling – First Letters
def first_letters(file):
with open(file, 'r') as infile:
lst = [line[0] for line in infile]
return ''.join(lst)
HW13: Set Union from Files
with open("bank1.txt", "r") as infile:
set1 = set()
with open("bank2.txt", 'r') as infile:
table = [line.strip().replace(' ', ',').split(',') for line in infile]
for x in table:
x[-1], x[-2] = x[-2], x[-1]
set2 = {','.join(x) + "\n" for x in table}
merged = sorted(set1.union(set2))
with open("bank_merged.txt", 'w') as outfile:
outfile.writelines(merged)
HW12: People Names – Initials
with open("people.txt", 'r') as infile:
table = [line.split() for line in infile]
mixed = sorted([x[0][0] + x[1][0] for x in table])
with open("inital.txt", 'w') as outfile:
outfile.writelines("\n".join(mixed))
Recursion – Sum Up
def recur_sum(lst):
if len(lst) == 0:
return 0
else:
return lst[0] + recur_sum(lst[1:])
File – First Letter
def first_letter(file):
with open(file, 'r') as infile:
lst = [line[0] for line in infile]
return ''.join(lst)
Caesar Cipher Function
def casear(message, action, shift):
ref = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
converted = ""
for x in message.upper().replace(" ", ''):
if action == 'E':
converted += ref[(ref.find(x) + shift) % 26]
elif action == "D":
converted += ref[(ref.find(x) - shift) % 26]
return converted
Note: The original code had a typo in the decryption part. It should be (ref.find(x) – shift) % 26.
Prime Factorization
def factorization(n):
lst = []
for i in range(2, n):
if n % i == 0:
j = 0
while n % i == 0:
j += 1
n /= i
lst.append((i, j))
return lst
HW4: Matrix Operations
matrix = eval(input("Enter"))
a = matrix[0]
b = matrix[1]
c = matrix[2]
d = matrix[3]
det = a * d - b * c
inverse = [[d / det, -b / det], [-c / det, a / det]]
print(inverse)
Note: The input is expected to be a tuple like (1,2,3,4).