Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions H2 Computing Practical (2021 Syllabus)/CODES/1 SORT ALGORITHMS.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ def bubble_sort(lst):
result = bubble_sort(result)
print("Bubble sort:", result)

# optimized bubble sort using last exchange index
def optimized_bubble_sort(lst):
n = len(lst) - 1
while n > 0:
last_exchange_index = 0
for i in range(n):
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
last_exchange_index = i
n = last_exchange_index
return lst

result = lst.copy()
result = optimized_bubble_sort(result)
print("Optimized bubble sort:", result)

def insertion_sort(lst):
for i in range(1, len(lst)):
temp = lst[i]
Expand Down
11 changes: 11 additions & 0 deletions H2 Computing Practical (2021 Syllabus)/CODES/6 FILE OPERATIONS.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from csv import DictReader
from random import randint
import json

header = ["Name", "Age"]
name = ["Bob", "Tom", "Jerry", "Jesus", "\"Korean, Jesus\"", "Maple", "Lisa", "Jack", "Moby", "Obama"]
Expand All @@ -10,6 +11,7 @@
print("Person:", person)
print()

# file closes automatically
with open("TEST DATA.txt", "w") as f: # write file
f.write(",".join(header))
for name in person:
Expand Down Expand Up @@ -41,3 +43,12 @@

for row in reader:
print(f"Person: {row['Name']}, Age: {row['Age']}")

# sample code for json files
with open("TEST DATA 2.json", "r") as f:
# json.load returns a json object, similar to python dictionary
data = json.load(f)

print()
# method in json library to print json object in readable format
print(json.dumps(data, indent=2))