diff --git a/H2 Computing Practical (2021 Syllabus)/CODES/1 SORT ALGORITHMS.py b/H2 Computing Practical (2021 Syllabus)/CODES/1 SORT ALGORITHMS.py index f2ee9cb..dff400e 100644 --- a/H2 Computing Practical (2021 Syllabus)/CODES/1 SORT ALGORITHMS.py +++ b/H2 Computing Practical (2021 Syllabus)/CODES/1 SORT ALGORITHMS.py @@ -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] diff --git a/H2 Computing Practical (2021 Syllabus)/CODES/6 FILE OPERATIONS.py b/H2 Computing Practical (2021 Syllabus)/CODES/6 FILE OPERATIONS.py index 07a9f04..15f5275 100644 --- a/H2 Computing Practical (2021 Syllabus)/CODES/6 FILE OPERATIONS.py +++ b/H2 Computing Practical (2021 Syllabus)/CODES/6 FILE OPERATIONS.py @@ -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"] @@ -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: @@ -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))