diff --git a/Menu WIP.py b/Menu WIP.py
deleted file mode 100644
index a8e1365..0000000
--- a/Menu WIP.py
+++ /dev/null
@@ -1,17 +0,0 @@
-print("1.Create Account","\n"+"2.Log into Account","\n"+"3.Book a Journey","\n"+"4.Previous Journeys for Account")
-print("Choose an option by typing the number in front")
-nuhuh = True
-while nuhuh:
- choice = input()
- try:
- int(choice)
- except ValueError:
- nuhuh = True
- if nuhuh:
- print("It's not an interger. Try again.")
- else:
- break
-checkchoice = int(choice)
-if checkchoice>4 or checkchoice<1:
- print("Unacceptable input. Try again.")
-Û
diff --git a/README.md b/README.md
index 9042241..9c2f4e6 100644
--- a/README.md
+++ b/README.md
@@ -1,7 +1,36 @@
-Random CS project.
-CS Project has 3 tasks, each task has it's own flowchart.
-Current stage is Pseudocode.
-
-Finished: Overview, FlowCharts, Code( I think)
-
-{Currently not working on this}
+# CS Project Organization
+
+This repository contains various Computer Science tasks, organized into a clean directory structure with a central dispatcher.
+
+## Project Structure
+
+- `main.py`: The main entry point. Run this to access all tasks via a menu.
+- `algorithms/`: Searching and sorting algorithm implementations.
+- `booking_system/`: A transport booking system with account management and price calculation.
+- `data_structures/`: Implementations of Linked Lists and Stacks (both OOP and Procedural).
+- `docs/`: Documentation, including flowcharts and pseudocode.
+- `high_scores/`: A high score tracking system.
+- `shapes/`: Area calculation for various geometric shapes.
+- `student_management/`: OOP implementation for managing student information.
+
+## How to Run
+
+1. Ensure you have Python installed.
+2. Run the main dispatcher from the root directory:
+ ```bash
+ python main.py
+ ```
+3. Follow the on-screen prompts to select the task you want to run.
+
+## Features
+
+- **Menu-Driven Interface:** Easily navigate through different tasks.
+- **Robust Error Handling:** Scripts have been improved to handle invalid inputs gracefully.
+- **Persistent Data:** Booking data and high scores are saved to text files within their respective directories.
+- **Sample Data:** Each task comes with sample data or uses provided data files to demonstrate functionality.
+
+## Documentation
+
+Check the `docs/` folder for:
+- `pseudocode.txt`: Logic descriptions.
+- `flowchart.drawio.html` & `overview.drawio.html`: Visual representations of the project logic.
diff --git a/data.txt b/algorithms/data.txt
similarity index 100%
rename from data.txt
rename to algorithms/data.txt
diff --git a/algorithms/search.py b/algorithms/search.py
new file mode 100644
index 0000000..d9dcb67
--- /dev/null
+++ b/algorithms/search.py
@@ -0,0 +1,48 @@
+import os
+
+
+def search(search_item, search_array):
+ id_item = 0
+ for item in search_array:
+ try:
+ if int(item) == search_item:
+ return id_item, item, True
+ except ValueError:
+ if item == search_item:
+ return id_item, item, True
+ id_item += 1
+ return False
+
+
+def run_search():
+ # Get the directory of the current script
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+ data_file = os.path.join(BASE_DIR, "data.txt")
+
+ try:
+ with open(data_file, "r") as f:
+ farray = f.read().split(',')
+
+ # Clean up whitespace
+ farray = [item.strip() for item in farray]
+
+ print("Array content:", farray)
+
+ try:
+ item_s = int(input("Enter a number to search for: "))
+ except ValueError:
+ print("Invalid input. Searching for default item 10.")
+ item_s = 10
+
+ result = search(item_s, farray)
+ if result:
+ idx, val, found = result
+ print(f"Item found! The item searched is: {val} at index {idx}")
+ else:
+ print(f"Item {item_s} not found!")
+ except FileNotFoundError:
+ print(f"Error: {data_file} not found.")
+
+
+if __name__ == "__main__":
+ run_search()
diff --git a/algorithms/search_hard.py b/algorithms/search_hard.py
new file mode 100644
index 0000000..060690f
--- /dev/null
+++ b/algorithms/search_hard.py
@@ -0,0 +1,69 @@
+import os
+
+
+def search(search_item, search_array):
+ while True:
+ array_length = len(search_array)
+ if array_length == 0:
+ return False
+ midpoint = array_length // 2
+
+ if search_array[midpoint] == search_item:
+ return True
+ elif array_length <= 1:
+ return False
+ elif search_item > search_array[midpoint]:
+ search_array = search_array[midpoint+1:]
+ else:
+ search_array = search_array[0:midpoint]
+
+
+def sort(sort_array):
+ array = list(sort_array)
+ changed = True
+ while changed:
+ changed = False
+ for i in range(len(array) - 1):
+ if array[i] > array[i + 1]:
+ temp = array[i]
+ array[i] = array[i + 1]
+ array[i + 1] = temp
+ changed = True
+ return array
+
+
+def run_search_hard():
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+ data_file = os.path.join(BASE_DIR, "data.txt")
+
+ try:
+ with open(data_file, "r") as f:
+ content = f.read().strip()
+ if content:
+ farray = content.split(',')
+ farray = [int(i.strip()) for i in farray]
+ else:
+ farray = []
+
+ sorted_array = sort(farray)
+ print("Sorted array:", sorted_array)
+
+ try:
+ item_s = int(
+ input("Enter a number to search for (Binary Search): "))
+ except ValueError:
+ print("Invalid input. Searching for 11.")
+ item_s = 11
+
+ if search(item_s, sorted_array):
+ print(f"Item {item_s} found!")
+ else:
+ print(f"Item {item_s} not found!")
+ except FileNotFoundError:
+ print(f"Error: {data_file} not found.")
+ except Exception as e:
+ print(f"An error occurred: {e}")
+
+
+if __name__ == "__main__":
+ run_search_hard()
diff --git a/algorithms/sorting123.py b/algorithms/sorting123.py
new file mode 100644
index 0000000..c6ce2aa
--- /dev/null
+++ b/algorithms/sorting123.py
@@ -0,0 +1,25 @@
+def sort(array):
+ arr = list(array)
+ for i in range(len(arr)):
+ if i == 0:
+ continue
+ if arr[i] < arr[i-1]:
+ for b in range(i, 0, -1):
+ if arr[b] < arr[b-1]:
+ temp = arr[b]
+ arr[b] = arr[b-1]
+ arr[b-1] = temp
+ else:
+ break
+ return arr
+
+
+def run_sorting():
+ unsorted = [1, 3, 7, 8, 23, 0, 4, 5, 6, 2, 12]
+ print(f"Unsorted list: {unsorted}")
+ sorted_list = sort(unsorted)
+ print(f"Sorted list: {sorted_list}")
+
+
+if __name__ == "__main__":
+ run_sorting()
diff --git a/Account.txt b/booking_system/Account.txt
similarity index 100%
rename from Account.txt
rename to booking_system/Account.txt
diff --git a/Bookings.txt b/booking_system/Bookings.txt
similarity index 100%
rename from Bookings.txt
rename to booking_system/Bookings.txt
diff --git a/JourneyPrices.txt b/booking_system/JourneyPrices.txt
similarity index 100%
rename from JourneyPrices.txt
rename to booking_system/JourneyPrices.txt
diff --git a/booking_system/booking.py b/booking_system/booking.py
new file mode 100644
index 0000000..533c252
--- /dev/null
+++ b/booking_system/booking.py
@@ -0,0 +1,194 @@
+# ---- Importing libraries ----
+from random import randint
+import os
+
+# ---- Setting up variables ----
+name = "NoName"
+time = 0
+useless_minutes = 0
+codes = []
+priceHome_val = 0
+priceStart_val = 0
+priceEnd_val = 0
+priceTotal_val = 0
+accounts = []
+bookid = 0
+accid = 0
+
+# Get the directory of the current script
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+
+# ---- Getting the correct name ----
+
+
+def create_account():
+ global name, accid
+ print("Please input your name...")
+ while True:
+ try:
+ input_name = input()
+ if len(input_name) <= 2 or len(input_name) >= 16:
+ raise ValueError
+ else:
+ name = input_name
+ break
+ except ValueError:
+ print("The name should be longer than 2 characters and shorter than 16.")
+ print("Your name is:", name)
+ accid = randint(1, 999999)
+ print("Your account is now created:", name, "ID:", accid)
+
+# ---- Booking a journey ----
+
+
+def get_journey_time():
+ global time, useless_minutes
+ print("Please input the hour of your journey in a 24 hour format.")
+ while True:
+ try:
+ input_time = int(input())
+ if not (0 <= input_time <= 23):
+ raise ValueError
+ time = input_time
+ break
+ except ValueError:
+ print("Please make sure the hour you inputed is correct.")
+ print("The hour of your journey is:", time)
+
+ print("Please input the minutes of your journey.")
+ while True:
+ try:
+ input_minutes = int(input())
+ if not (0 <= input_minutes <= 59):
+ raise ValueError
+ useless_minutes = input_minutes
+ break
+ except ValueError:
+ print("Please make sure the minutes you inputed is correct.")
+ print("The minute of your journey is:", useless_minutes)
+
+
+def get_journey_codes():
+ global codes
+ codes = []
+ parts = [
+ "Home to start station",
+ "Start station to end station",
+ "End station to destination"
+ ]
+ for part in parts:
+ while True:
+ try:
+ print(f"Please input the code (1-5) for the {part}")
+ input_code = int(input())
+ if not (1 <= input_code <= 5):
+ raise ValueError
+ codes.append(input_code)
+ break
+ except ValueError:
+ print("Please make sure the code you inputed is correct (1-5).")
+
+
+def book_journey():
+ global bookid
+ get_journey_time()
+ get_journey_codes()
+
+ print(
+ f"The codes you inputed are: C{codes[0]} --> M{codes[1]} --> F{codes[2]}")
+ bookid = randint(1, 999999)
+ print("Your booking ID: " + str(bookid))
+
+# ----Def function to save data into file Account.txt----
+
+
+def SaveAccountData():
+ try:
+ UserData = os.path.join(BASE_DIR, "Account.txt")
+ with open(UserData, "a") as AccountFile:
+ AccountFile.write(f"{name}\n")
+ AccountFile.write(f"{bookid}\n")
+ AccountFile.write(f"{accid}\n")
+ except Exception as e:
+ print(f"Error saving account data: {e}")
+
+# ----Def function to save bookings data into files Bookings.txt----
+
+
+def BookingsData():
+ try:
+ BookingData = os.path.join(BASE_DIR, "Bookings.txt")
+ with open(BookingData, "a") as BookingFile:
+ BookingFile.write(f"C{codes[0]} M{codes[1]} F{codes[2]}\n")
+ BookingFile.write("--------------------Day Separation\n")
+ except Exception as e:
+ print(f"Error saving bookings data: {e}")
+
+# ----Define the subroutine to calculate prices and totalprice----
+
+
+def calculate_priceHome():
+ global priceHome_val
+ code = codes[0]
+ prices = {1: 1.50, 2: 3.0, 3: 4.50, 4: 6.0, 5: 8.0}
+ priceHome_val = prices.get(code, 0)
+ print(f"The price of start journey is {priceHome_val}$")
+
+
+def calculate_priceStart():
+ global priceStart_val
+ code = codes[1]
+ prices = {1: 5.75, 2: 12.5, 3: 22.25, 4: 34.5, 5: 45.0}
+ priceStart_val = prices.get(code, 0)
+ print(f"The price of middle journey is {priceStart_val}$")
+
+
+def calculate_priceEnd():
+ global priceEnd_val
+ code = codes[2]
+ prices = {1: 1.5, 2: 3.0, 3: 4.5, 4: 6.0, 5: 8.0}
+ priceEnd_val = prices.get(code, 0)
+ print(f"The price of end journey is {priceEnd_val}$")
+
+
+def calculate_priceTotal():
+ global priceTotal_val
+ total = priceHome_val + priceStart_val + priceEnd_val
+ if time == 10 and useless_minutes == 0:
+ priceTotal_val = total * 0.4
+ else:
+ priceTotal_val = total
+ print(f"The total price of your journey is: {priceTotal_val}$")
+
+# ----Defining subroutine to store prices and total prices of each journey----
+
+
+def PricesFile():
+ try:
+ PricesData = os.path.join(BASE_DIR, "JourneyPrices.txt")
+ with open(PricesData, "a") as f:
+ f.write(f"Home: {priceHome_val}\n")
+ f.write(f"Start: {priceStart_val}\n")
+ f.write(f"End: {priceEnd_val}\n")
+ f.write(f"Total: {priceTotal_val}\n")
+ f.write("-------------------- Day Separation\n")
+ except Exception as e:
+ print(f"Error saving prices data: {e}")
+
+
+def run_booking_system():
+ print("--- Transport Booking System ---")
+ create_account()
+ book_journey()
+ calculate_priceHome()
+ calculate_priceStart()
+ calculate_priceEnd()
+ calculate_priceTotal()
+ SaveAccountData()
+ BookingsData()
+ PricesFile()
+ print("Booking complete and data saved.")
+
+
+if __name__ == "__main__":
+ run_booking_system()
diff --git a/chatgpt.py b/chatgpt.py
deleted file mode 100644
index 1c2f826..0000000
--- a/chatgpt.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from UnlimitedGPT import ChatGPT
-
-session_token = "YOUR_SESSION_TOKEN"
-conversation_id = "YOUR_CONVERSATION_ID"
-
-chatbot = ChatGPT(
- session_token,
- conversation_id=conversation_id,
- proxy=None,
- chrome_args=None,
- disable_moderation=False,
- verbose=False,
-)
diff --git a/con.py b/con.py
deleted file mode 100644
index 8bdc63b..0000000
--- a/con.py
+++ /dev/null
@@ -1,34 +0,0 @@
-class student:
- def __init__(self, name, dateOfBirth, examMark):
- self.__name = name
- self.__dateOfBirth = dateOfBirth
- self.__examMark = examMark
- self.__fullTimeStudent = True
-
- def displayExamMark(self):
- return(self.__examMark)
-
- def displayInfo(self):
- if self.__fullTimeStudent:
- self.__x = "FullTime"
- else:
- self.__x = "PartTime"
- return(self.__name,self.__dateOfBirth,self.__examMark, self.__x)
-
-class fullTimeStudent(student):
- def __init__(self, name, dateOfBirth, examMark):
- super().__init__(name, dateOfBirth, examMark)
- self.__fullTimeStudent = True
-
-class partTimeStudent(student):
- def __init__(self, name, dateOfBirth, examMark):
- super().__init__(name, dateOfBirth, examMark)
- self.__fullTimeStudent = False
-
-
-fullstudent = fullTimeStudent("Merka Jojka", "6/6/2666", 64)
-partstudent = partTimeStudent("Tester Makester", "12/12/3666", 101)
-print(fullstudent.displayExamMark())
-print(partstudent.displayExamMark())
-print(fullstudent.displayInfo())
-print(partstudent.displayInfo())
\ No newline at end of file
diff --git a/linkedlist.py b/data_structures/linkedlist.py
similarity index 52%
rename from linkedlist.py
rename to data_structures/linkedlist.py
index b60509d..68e4ecd 100644
--- a/linkedlist.py
+++ b/data_structures/linkedlist.py
@@ -1,10 +1,12 @@
-# OOP
-'''
+# Linked List Implementation
+
+# OOP Implementation
class Node:
def __init__(self, data):
self.data = data
self.next = None
+
class LinkedList:
def __init__(self):
self.head = None
@@ -21,24 +23,20 @@ def append(self, data):
def display(self):
current = self.head
+ elements = []
while current:
- print(current.data, end=" -> ")
+ elements.append(str(current.data))
current = current.next
- print("None")
+ print(" -> ".join(elements) + " -> None")
+# Procedural Implementation
-ll = LinkedList()
-ll.append(1)
-ll.append(2)
-ll.display()
-'''
-
-# Procedural
def create_node(data):
return {"data": data, "next": None}
-def append(head, data):
+
+def append_procedural(head, data):
new_node = create_node(data)
if not head:
return new_node
@@ -48,15 +46,31 @@ def append(head, data):
current["next"] = new_node
return head
-def display(head):
+
+def display_procedural(head):
current = head
+ elements = []
while current:
- print(current["data"], end=" -> ")
+ elements.append(str(current["data"]))
current = current["next"]
- print("None")
+ print(" -> ".join(elements) + " -> None")
+
+
+def run_linkedlist_demo():
+ print("--- Linked List (OOP) ---")
+ ll = LinkedList()
+ ll.append(1)
+ ll.append(2)
+ ll.append(3)
+ ll.display()
+
+ print("\n--- Linked List (Procedural) ---")
+ head = None
+ head = append_procedural(head, 10)
+ head = append_procedural(head, 20)
+ head = append_procedural(head, 30)
+ display_procedural(head)
-head = None
-head = append(head, 1)
-head = append(head, 2)
-display(head)
+if __name__ == "__main__":
+ run_linkedlist_demo()
diff --git a/data_structures/stack.py b/data_structures/stack.py
new file mode 100644
index 0000000..6a5adb6
--- /dev/null
+++ b/data_structures/stack.py
@@ -0,0 +1,72 @@
+# Stack Implementation
+
+# OOP Implementation
+class Stack:
+ def __init__(self, maxlength=5) -> None:
+ self.stack = []
+ self.maxlength = maxlength
+
+ def push(self, element):
+ if len(self.stack) >= self.maxlength:
+ print("Stack is full. Cannot push.")
+ else:
+ self.stack.append(element)
+ print(f"Pushed {element} onto the stack.")
+
+ def pop(self):
+ if not self.stack:
+ print("Stack is empty. Cannot pop.")
+ return None
+ return self.stack.pop()
+
+ def is_empty(self):
+ return len(self.stack) == 0
+
+ def is_full(self):
+ return len(self.stack) == self.maxlength
+
+ def peek(self):
+ if not self.stack:
+ print("Stack is empty.")
+ return None
+ return self.stack[-1]
+
+# Procedural Implementation
+
+
+def push_procedural(stack, element, max_length):
+ if len(stack) >= max_length:
+ print("Stack is full. Cannot push.")
+ else:
+ stack.append(element)
+ print(f"Pushed {element} onto the stack.")
+
+
+def pop_procedural(stack):
+ if not stack:
+ print("Stack is empty. Cannot pop.")
+ return None
+ return stack.pop()
+
+
+def run_stack_demo():
+ print("--- Stack (OOP) ---")
+ MyStack = Stack(maxlength=2)
+ MyStack.push(10)
+ MyStack.push(20)
+ MyStack.push(30) # Should be full
+ print(f"Top element is {MyStack.peek()}")
+ print(f"Is stack full? {MyStack.is_full()}")
+ print(f"Popped element: {MyStack.pop()}")
+ print(f"Is stack empty? {MyStack.is_empty()}")
+
+ print("\n--- Stack (Procedural) ---")
+ stack_list = []
+ max_len = 3
+ push_procedural(stack_list, "A", max_len)
+ push_procedural(stack_list, "B", max_len)
+ print(f"Popped from procedural stack: {pop_procedural(stack_list)}")
+
+
+if __name__ == "__main__":
+ run_stack_demo()
diff --git a/flowchart.drawio.html b/docs/flowchart.drawio.html
similarity index 100%
rename from flowchart.drawio.html
rename to docs/flowchart.drawio.html
diff --git a/overview.drawio.html b/docs/overview.drawio.html
similarity index 100%
rename from overview.drawio.html
rename to docs/overview.drawio.html
diff --git a/pseudocode.txt b/docs/pseudocode.txt
similarity index 100%
rename from pseudocode.txt
rename to docs/pseudocode.txt
diff --git a/HighScore.txt b/high_scores/HighScore.txt
similarity index 100%
rename from HighScore.txt
rename to high_scores/HighScore.txt
diff --git a/high_scores/high_scores.py b/high_scores/high_scores.py
new file mode 100644
index 0000000..f77f248
--- /dev/null
+++ b/high_scores/high_scores.py
@@ -0,0 +1,99 @@
+import os
+
+# Task 1
+HighScore = [["", 0] for i in range(10)]
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
+FILE_PATH = os.path.join(BASE_DIR, "HighScore.txt")
+
+# Task 2
+
+
+def ReadHighScores():
+ if not os.path.exists(FILE_PATH):
+ return
+ try:
+ with open(FILE_PATH, "r") as f:
+ for i in range(0, 10):
+ name = f.readline().strip()
+ score = f.readline().strip()
+ if name and score:
+ HighScore[i][0] = name
+ HighScore[i][1] = int(score)
+ except Exception as e:
+ print(f"Error reading high scores: {e}")
+
+# Task 3
+
+
+def OutputHighScores():
+ print("\n--- High Scores ---")
+ for i in range(len(HighScore)):
+ if HighScore[i][0]:
+ print(f"{i+1}. {HighScore[i][0]}: {HighScore[i][1]}")
+ else:
+ print(f"{i+1}. ")
+
+# Task 5
+
+
+def GetPlayerInput():
+ while True:
+ playername = input("Please input the player name (3 characters): ")
+ if len(playername) != 3:
+ print(
+ "The inputted player name must be exactly 3 characters, please try again.")
+ continue
+ try:
+ score = int(input("Please input the player score: "))
+ if score > 100000:
+ print("The inputted score is too high! Please try again.")
+ continue
+ return playername, score
+ except ValueError:
+ print("Invalid score. Please enter a number.")
+
+# Task 6
+
+
+def calculate_top(playername, score):
+ global HighScore
+ # Add new score to the list
+ HighScore.append([playername, score])
+ # Sort the list by score descending
+ HighScore.sort(key=lambda x: int(x[1]), reverse=True)
+ # Keep only top 10
+ HighScore = HighScore[:10]
+
+ # Check if the new player made it to top 10
+ found = False
+ for entry in HighScore:
+ if entry[0] == playername and entry[1] == score:
+ found = True
+ break
+ return found
+
+
+def SaveHighScores():
+ try:
+ with open(FILE_PATH, "w") as f:
+ for name, score in HighScore:
+ f.write(f"{name}\n")
+ f.write(f"{score}\n")
+ except Exception as e:
+ print(f"Error saving high scores: {e}")
+
+
+def run_high_scores():
+ ReadHighScores()
+ OutputHighScores()
+ playername, score = GetPlayerInput()
+ if calculate_top(playername, score):
+ print(f"Congratulations {playername}! You made it to the Top 10!")
+ else:
+ print(f"Sorry {playername}, you didn't make it to the Top 10.")
+ OutputHighScores()
+ SaveHighScores()
+
+
+if __name__ == "__main__":
+ run_high_scores()
diff --git a/main.py b/main.py
index 6ec5af6..44a0897 100644
--- a/main.py
+++ b/main.py
@@ -1,219 +1,66 @@
-# ---- Importing libraries ----
-import randint from random
-# ---- Setting up variables ----
-name = "NoName"
-time = 0
-useless_minutes = 0
-codes = []
-priceHome = 0
-priceStart = 0
-priceEnd = 0
-priceTotal = 0
-accounts = []
-bookid = 0
-accid = 0
-# ---- Getting the correct name ----
-def create_account():
- print("Please input your name...")
- while True:
- try:
- input_name = input()
- if len(input_name) <= 2 or len(input_name) >=16:
- raise TypeError
- else:
- name = input_name
- break
- except:
- print("The name should be longer than 2 characters and shorter than 16.")
- print("Your name is:",name)
- accid = randint(1,999999)
- print("Your account is now created:",name,"ID:",accid)
-# ---- Booking a journey ----
-def book_journey():
- # ---- Getting the correct hour ----
- print("Please input the hour of your journey in a 24 hour format.")
- while True:
- try:
- input_time = int(input())
- if input_time > 23:
- raise TypeError
- else:
- time = input_time
- break
- except:
- print("Please make sure the hour you inputed is correct.")
- print("The hour of your journey is:",time)
- # ---- Getting the useless minutes ----
- while True:
- try:
- uselesss_minutes = int(input())
- if useless_minutes > 59:
- raise TypeError
- else:
- break
- except:
- print("Please make sure the minutes you inputed is correct.")
- print("The minute of your journey is:",useless_minutes)
- # ---- Inputing the codes of the journey ----
- for i in range(0,2):
- while True:
- try:
- part_journey = ""
- if i == 1:
- part_journey = "Home to start station"
- elif i == 2:
- part_journey = "Start station to end station"
- elif i == 3:
- part_journey = "End station to destination"
- print("Please input the code for the",part_journey)
- input_code = int(input())
- if input_code > 5:
- raise TypeError
- else:
- codes.insert(input_code-1,i)
- break
- except:
- print("Please make sure the code you inputed is correct.")
- print("The codes you inputed are: "+"C"+str(codes[0])+"-->"+"M"+str(codes[1])+"-->"+"F"+str(codes[2]))
- bookid = randint(1,999999)
- print("Your booking ID: "+str(bookid))
-# ----Def function to save data into file Account.txt----
-def SaveAccountData():
-# Try to find Account.txt and append user's name into file
- try:
- UserData = "Account.txt"
- AccountFile = open(UserData,"a")
- AccountFile.write(name)
- AccountFile.write(bookid)
- AccountFile.write(accid)
- AccountFile.close()
-# If file not found print error
- except:
- print("{} was not found".format(UserData))
-
-# ----Def function to save bookings data into files Bookings.txt----
-def BookingsData():
-# Try to find Bookings.txt and append booking codes into file
- try:
- BookingData = "Booking.txt"
- BookingFile = open(BookingData,"a")
- BookingFile.write("C"+str(codes[0]))
- BookingFile.write("M"+str(codes[1]))
- BookingFile.write("F"+str(codes[2]))
- BookingFile.write("--------------------Day Separation")
- BookingFile.close()
-# Output a message if file isn't found
- except:
- print("{} was not found".format(BookingData))
+import os
+
+# Add subdirectories to sys.path to allow imports if needed,
+# but for simple execution, we can just import the run functions.
-def menu()
- print("1. Create account")
- print("2. Log in account")
- print("3. Book journey (Must be logged in)")
- print("4. Find booked journeys")
- choice = int(input())
- if choice.isdigit():
- if choice >= 1 and choice <=4:
- if choice == 1:
- print("Selected 1")
- elif choice == 2:
- print("Selected 2")
- elif choice == 3:
- print("Selected 3")
- else:
- print("Selected 4")
- else:
- print("Wrong input, please try again.")
- menu()
-# ----Define the subroutine to calculate prices and totalprice----
-def priceHome():
- if codes[0] >= 1 and codes[0] <= 5:
- if codes[0] == 1:
- priceHome = 1.50
- print("The price of start journey is" + str(priceHome) + "$")
- elif codes[0] == 2:
- priceHome = 3
- print("The price of start journey is" + str(priceHome) + "$")
- elif codes[0] == 3:
- priceHome = 4.50
- print("The price of start journey is" + str(priceHome) + "$")
- elif codes[0] == 4:
- priceHome = 6
- print("The price of start journey is" + str(priceHome) + "$")
- elif codes[0] == 5:
- priceHome = 8
- print("The price of start journey is" + str(priceHome) + "$")
- else:
- print("Input cannot be processed, please try again")
- priceHome()
+from algorithms.search import run_search
+from algorithms.search_hard import run_search_hard
+from algorithms.sorting123 import run_sorting
+from booking_system.booking import run_booking_system
+from data_structures.linkedlist import run_linkedlist_demo
+from data_structures.stack import run_stack_demo
+from high_scores.high_scores import run_high_scores
+from shapes.shapes import run_shapes_demo
+from student_management.con import run_student_demo
-def priceStart():
- if codes[1] >= 1 and codes[1] <= 5:
- if codes[1] == 1:
- priceStart = 5.75
- print("The price of start journey is" + str(priceStart) + "$")
- elif codes[1] == 2:
- priceStart = 12.5
- print("The price of start journey is" + str(priceStart) + "$")
- elif codes[1] == 3:
- priceStart = 22.25
- print("The price of start journey is" + str(priceStart) + "$")
- elif codes[1] == 4:
- priceStart = 34.5
- print("The price of start journey is" + str(priceStart) + "$")
- elif codes[1] == 5:
- priceStart = 45
- print("The price of start journey is" + str(priceStart) + "$")
- else:
- print("Input cannot be processed, please try again")
- priceStart()
-def priceEnd():
- if codes[2] >= 1 and codes[2] <= 5:
- if codes[2] == 1:
- priceEnd = 1.5
- print("The price of start journey is" + str(priceEnd) + "$")
- elif codes[2] == 2:
- priceEnd = 3
- print("The price of start journey is" + str(priceEnd) + "$")
- elif codes[2] == 3:
- priceEnd = 4.5
- print("The price of start journey is" + str(priceEnd) + "$")
- elif codes[2] == 4:
- priceEnd = 6
- print("The price of start journey is" + str(priceEnd) + "$")
- elif codes[2] == 5:
- priceEnd = 8
- print("The price of start journey is" + str(priceEnd) + "$")
- else:
- print("Input cannot be processed, please try again")
- priceEnd()
+def clear_screen():
+ os.system('cls' if os.name == 'nt' else 'clear')
-def priceTotal():
- if time = 10 and minutes = 0:
- PriceTotal = (priceHome + priceStart + priceEnd) * 0.4
- print("The total price of your journey is:" + str(priceTotal) + "$")
- else:
- PriceTotal = (priceHome + priceStart + priceEnd)
- print("The total price of your journey is:" + str(priceTotal) + "$")
-# ----Defining subroutine to store prices and total prices of each journey----
-def PricesFile():
-# Try to find JourneyPrices.txt and append prices into the file
- try:
- PricesData = "JourneyPrices.txt"
- PricesFile = open(PricesData,"a")
- PricesFile.write(priceHome)
- PricesFile.write(priceStart)
- PricesFile.write(priceEnd)
- PricesFile.write(PriceTotal)
- PricesFile.write("-------------------- Day Separation")
- PricesFile.close()
-# Output error if file not found
- except:
- print("{} was not found".format(PricesData))
-
+def get_choice():
+ print("\n" + "=" * 30)
+ print(" CS PROJECT MAIN MENU ")
+ print("=" * 30)
+ print("1. Transport Booking System")
+ print("2. High Scores Tracker")
+ print("3. Student Management Demo")
+ print("4. Shapes Area Calculation")
+ print("5. Linked List Demo")
+ print("6. Stack Demo")
+ print("7. Simple Search")
+ print("8. Binary Search (Hard Search)")
+ print("9. Sorting Demo")
+ print("0. Exit")
+ print("=" * 30)
+ return input("Select an option (0-9): ")
+
+
+def main_menu():
+ actions = {
+ '1': run_booking_system,
+ '2': run_high_scores,
+ '3': run_student_demo,
+ '4': run_shapes_demo,
+ '5': run_linkedlist_demo,
+ '6': run_stack_demo,
+ '7': run_search,
+ '8': run_search_hard,
+ '9': run_sorting
+ }
+ while True:
+ choice = get_choice()
+ if choice == '0':
+ print("Exiting... Goodbye!")
+ break
+ elif choice in actions:
+ actions[choice]()
+ else:
+ print("Invalid choice, please try again.")
+
+ input("\nPress Enter to return to the menu...")
+ clear_screen()
-# Main program thingy code whatever
-menu()
+if __name__ == "__main__":
+ main_menu()
diff --git a/output.txt b/output.txt
deleted file mode 100644
index e69de29..0000000
diff --git a/program.py b/program.py
deleted file mode 100644
index 3624ded..0000000
--- a/program.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Task 1
-global HighScore
-HighScore = [["",0] for i in range(10)]
-# Task 2
-def ReadHighScores():
- f = open("HighScore.txt", "r")
- for i in range(0,10):
- HighScore[i][0]=f.readline()[:-1]
- HighScore[i][1]=f.readline()[:-1]
-
-# Task 3
-def OutputHighScores():
- for i in range(len(HighScore)):
- print(HighScore[i])
-
-# Task 4
-
-#ReadHighScores()
-#OutputHighScores()
-
-# Task 5
-while True:
- playername = input("Please input the player name:")
- if len(playername) != 3:
- print("The inputted player name is longer than 3, please try again..")
- continue
- score = int(input("Please input the player score:"))
- if score > 100000:
- print("The inputted score is too high! Please try again..")
- continue
- break
-
-# Task 6
-def calculate_top():
- if score > int(HighScore[len(HighScore)-1][1]):
- NewHighScore=HighScore
- NewHighScore.append([playername,score])
- for i in range(len(HighScore)-2,-1,-1):
- if score > int(NewHighScore[i][1]):
- temp = NewHighScore[i]
- NewHighScore[i]=NewHighScore[i+1]
- NewHighScore[i+1]=temp
- else:
- NewHighScore.pop()
- break
- return NewHighScore
- else:
- return False
-
-# Task 7
-ReadHighScores()
-OutputHighScores()
-NewHighScore = calculate_top()
-print(NewHighScore)
-
-
-# Task 8 Final
-
diff --git a/random.py b/random.py
deleted file mode 100644
index e69de29..0000000
diff --git a/requirements.txt b/requirements.txt
deleted file mode 100644
index e69de29..0000000
diff --git a/search.py b/search.py
deleted file mode 100644
index 008be11..0000000
--- a/search.py
+++ /dev/null
@@ -1,21 +0,0 @@
-def search(search_item,search_array):
- id_item=0
- for item in search_array:
- if int(item) == search_item:
- return id_item, item, True
- if item == search_item:
- return id_item, item, True
- else:
- id_item++1
- return False
-
-
-f = open("data.txt", "r")
-farray = f.read().split(',')
-item_s = 10
-print(farray)
-
-if search(item_s,farray):
- print("Item found! The item searched is:", item_s)
-else:
- print("item", item_s, "not found!")
\ No newline at end of file
diff --git a/search_hard.py b/search_hard.py
deleted file mode 100644
index 24ae420..0000000
--- a/search_hard.py
+++ /dev/null
@@ -1,34 +0,0 @@
-f = open("data.txt", "r")
-farray = f.read().split(',')
-farray=[eval(i) for i in farray]
-
-def search(search_item,search_array):
- while True:
- array_length = len(search_array)
- midpoint = int(array_length/2) - 1
- if array_length<=3:
- for i in search_array:
- if i == search_item: return True
- return False
- elif search_item > search_array[midpoint]: search_array = search_array[midpoint:array_length]
- elif search_item < search_array[midpoint]: search_array = search_array[0:midpoint]
- elif search_item == search_array[midpoint]: return True
- else: return False
-
-def sort(sort_array):
- changed = True
- while changed:
- changed = False
- for i in range(len(sort_array) - 1):
- if sort_array[i] > sort_array[i + 1]:
- temp = sort_array[i]
- sort_array[i] = sort_array[i + 1]
- sort_array[i + 1] = temp
- changed = True
- i += 1
- print(sort_array)
-
-
-
-#print(sort(unsorted))
-print(search(11,farray))
\ No newline at end of file
diff --git a/shapes.py b/shapes/shapes.py
similarity index 73%
rename from shapes.py
rename to shapes/shapes.py
index d19aff1..15dd443 100644
--- a/shapes.py
+++ b/shapes/shapes.py
@@ -1,5 +1,6 @@
from math import pi, sqrt
+
class Shape():
def __init__(self):
self.area_value = 0
@@ -7,10 +8,11 @@ def __init__(self):
def calculate_area(self):
self.area_value = self.area()
return self.area_value
-
+
def area(self):
raise NotImplementedError("Not implemented!")
-
+
+
class Square(Shape):
def __init__(self, side):
super().__init__()
@@ -28,6 +30,7 @@ def __init__(self, radius):
def area(self):
return round(pi * self.radius ** 2, 1)
+
class Triangle(Shape):
def __init__(self, base, height):
super().__init__()
@@ -37,6 +40,7 @@ def __init__(self, base, height):
def area(self):
return round(0.5 * self.base * self.height, 1)
+
class Hexagon(Shape):
def __init__(self, side):
super().__init__()
@@ -45,12 +49,20 @@ def __init__(self, side):
def area(self):
return round((3 * sqrt(3) * self.side ** 2) / 2, 1)
-shapes = [
- Square(4),
- Circle(3),
- Triangle(4, 5),
- Hexagon(2)
-]
-for shape in shapes:
- print(f"The area of the {shape.__class__.__name__} is {shape.calculate_area()}")
\ No newline at end of file
+def run_shapes_demo():
+ print("--- Shapes Area Calculation ---")
+ shapes_list = [
+ Square(4),
+ Circle(3),
+ Triangle(4, 5),
+ Hexagon(2)
+ ]
+
+ for shape in shapes_list:
+ print(
+ f"The area of the {shape.__class__.__name__} is {shape.calculate_area()}")
+
+
+if __name__ == "__main__":
+ run_shapes_demo()
diff --git a/sorting123.py b/sorting123.py
deleted file mode 100644
index bd98bc0..0000000
--- a/sorting123.py
+++ /dev/null
@@ -1,15 +0,0 @@
-unsorted = [1,3,7,8,23,0,4,5,6,2,12]
-
-def sort(array):
- for i in range(len(array)):
- if i == 0:
- pass
- if array[i] None:
- self.stack = stack if stack is not None else []
- self.maxlength = maxlength
-
- def push(self, element):
- if len(self.stack) >= self.maxlength:
- print("Stack is full. Cannot push.")
- else:
- self.stack.append(element)
- print(f"Pushed {element} onto the stack.")
-
- def pop(self):
- if not self.stack:
- print("Stack is empty. Cannot pop.")
- return None
- return self.stack.pop()
-
- def is_empty(self):
- return len(self.stack) == 0
-
- def is_full(self):
- return len(self.stack) == self.maxlength
-
- def peek(self):
- if not self.stack:
- print("Stack is empty.")
- return None
- return self.stack[-1]
-
-MyStack=Stack()
-MyStack.push(10)
-MyStack.push(20)
-print(f"Top element is {MyStack.peek()}")
-print(f"Is stack full? {MyStack.is_full()}")
-print(f"Popped element is {MyStack.pop()}")
-print(f"Is stack empty? {MyStack.is_empty()}")
-print(f"Is stack full? {MyStack.is_full()}")
-
-
-# Procedural
-'''
-global max_length
-max_length = 2
-stack = []
-
-def push(stack, element):
- if len(stack) > max_length:
- print("Stack is full. Cannot push.")
- else:
- stack.append(element)
- print(f"Pushed {element} onto the stack.")
-
-def pop(stack):
- if not stack:
- print("Stack is empty. Cannot pop.")
- return None
- return stack.pop()
-
-def is_empty(stack):
- return len(stack) == 0
-
-def is_full(stack):
- return len(stack) == max_length
-
-def peek(stack):
- if not stack:
- print("Stack is empty.")
- return None
- return stack[-1]
-
-push(stack, 10)
-push(stack, 20)
-print(f"Top element is {peek(stack)}")
-print(f"Is stack full? {is_full(stack)}")
-print(f"Popped element is {pop(stack)}")
-print(f"Is stack empty? {is_empty(stack)}")
-print(f"Is stack full? {is_full(stack)}")
-'''
\ No newline at end of file
diff --git a/student_management/con.py b/student_management/con.py
new file mode 100644
index 0000000..0af0c61
--- /dev/null
+++ b/student_management/con.py
@@ -0,0 +1,66 @@
+class student:
+ def __init__(self, name, dateOfBirth, examMark):
+ self.__name = name
+ self.__dateOfBirth = dateOfBirth
+ self.__examMark = examMark
+ self.__fullTimeStudent = True
+
+ def displayExamMark(self):
+ return (self.__examMark)
+
+ def displayInfo(self):
+ if self.__fullTimeStudent:
+ self.__x = "FullTime"
+ else:
+ self.__x = "PartTime"
+ return (self.__name, self.__dateOfBirth, self.__examMark, self.__x)
+
+
+class fullTimeStudent(student):
+ def __init__(self, name, dateOfBirth, examMark):
+ super().__init__(name, dateOfBirth, examMark)
+ # Workaround for name mangling
+ self._student__fullTimeStudent = True
+
+# Fixed version to actually work as intended:
+
+
+class Student:
+ def __init__(self, name, dateOfBirth, examMark):
+ self._name = name
+ self._dateOfBirth = dateOfBirth
+ self._examMark = examMark
+ self._fullTimeStudent = True
+
+ def displayExamMark(self):
+ return self._examMark
+
+ def displayInfo(self):
+ student_type = "FullTime" if self._fullTimeStudent else "PartTime"
+ return (self._name, self._dateOfBirth, self._examMark, student_type)
+
+
+class FullTimeStudent(Student):
+ def __init__(self, name, dateOfBirth, examMark):
+ super().__init__(name, dateOfBirth, examMark)
+ self._fullTimeStudent = True
+
+
+class PartTimeStudent(Student):
+ def __init__(self, name, dateOfBirth, examMark):
+ super().__init__(name, dateOfBirth, examMark)
+ self._fullTimeStudent = False
+
+
+def run_student_demo():
+ print("--- Student Management ---")
+ fullstudent = FullTimeStudent("Merka Jojka", "6/6/2666", 64)
+ partstudent = PartTimeStudent("Tester Makester", "12/12/3666", 101)
+ print(f"Full-time student exam mark: {fullstudent.displayExamMark()}")
+ print(f"Part-time student exam mark: {partstudent.displayExamMark()}")
+ print(f"Full-time student info: {fullstudent.displayInfo()}")
+ print(f"Part-time student info: {partstudent.displayInfo()}")
+
+
+if __name__ == "__main__":
+ run_student_demo()
diff --git a/test.py b/test.py
deleted file mode 100644
index d085cb9..0000000
--- a/test.py
+++ /dev/null
@@ -1,2 +0,0 @@
-print(ord("A"))
-print(ord("Z"))
\ No newline at end of file
diff --git a/test_main.py b/test_main.py
new file mode 100644
index 0000000..f4f5361
--- /dev/null
+++ b/test_main.py
@@ -0,0 +1,2 @@
+def test_dummy():
+ assert True