initial commit
This commit is contained in:
commit
39f56a3b10
83 files changed
+3583
No files matched your search
@@ -0,0 +1,108 @@
|
||||
import tkinter as tk
|
||||
|
||||
from my_package.App_window import AppWindow
|
||||
|
||||
|
||||
def is_valid_isbn(entry):
|
||||
clean_isbn = entry.replace("-", "").replace(" ", "").upper()
|
||||
|
||||
if len(clean_isbn) != 10:
|
||||
return False
|
||||
|
||||
total = 0
|
||||
try:
|
||||
for i in range(10):
|
||||
char = clean_isbn[i]
|
||||
if i == 9 and char == 'X':
|
||||
value = 10
|
||||
elif char.isdigit():
|
||||
value = int(char)
|
||||
else:
|
||||
return False
|
||||
total += value * (10 - i)
|
||||
|
||||
return total % 11 == 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def is_valid_iban(entry):
|
||||
clean_iban = entry.replace(" ", "").upper()
|
||||
|
||||
rearranged = clean_iban[4:] + clean_iban[:4]
|
||||
|
||||
numeric_iban = ""
|
||||
for char in rearranged:
|
||||
if char.isdigit():
|
||||
numeric_iban += char
|
||||
else:
|
||||
numeric_iban += str(ord(char) - 55)
|
||||
|
||||
return int(numeric_iban) % 97 == 1
|
||||
|
||||
|
||||
class Checker(AppWindow):
|
||||
def __init__(self):
|
||||
super().__init__(300,300)
|
||||
self.button_1 = tk.Button(self.root, text="check", command= self.check_isbn)
|
||||
self.button_2 = tk.Button(self.root,text="check", command= self.check_iban)
|
||||
self.isbn_label = tk.Label(self.root, text="")
|
||||
self.iban_label = tk.Label(self.root, text="")
|
||||
self.entry_1 = tk.Entry(self.root, width=20)
|
||||
self.entry_2 = tk.Entry(self.root, width=20)
|
||||
|
||||
|
||||
def init_widgets(self):
|
||||
tk.Label(self.root, text="ISBN: ").grid(row=0, column=0)
|
||||
self.entry_1.grid(row=0, column=1)
|
||||
self.button_1.grid(row=1, column=0)
|
||||
self.isbn_label.grid(row=1, column=1)
|
||||
|
||||
tk.Label(self.root, text="IBAN: ").grid(row=2, column=0)
|
||||
self.entry_2.grid(row=2, column=1)
|
||||
self.button_2.grid(row=3, column=0)
|
||||
self.iban_label.grid(row=3, column=1)
|
||||
|
||||
def check_isbn(self):
|
||||
entry = self.entry_1.get()
|
||||
self.entry_1.delete(0, tk.END)
|
||||
if is_valid_isbn(entry):
|
||||
self.isbn_label.configure(text="Valid ISBN")
|
||||
else:
|
||||
self.isbn_label.configure(text="Invalid ISBN")
|
||||
|
||||
def check_iban(self):
|
||||
entry = self.entry_2.get()
|
||||
self.entry_2.delete(0, tk.END)
|
||||
if is_valid_iban(entry):
|
||||
self.iban_label.configure(text="Valid IBAN")
|
||||
else:
|
||||
self.iban_label.configure(text="Invalid IBAN")
|
||||
|
||||
def console_checker():
|
||||
print("Welcome to IBAN / ISBN Checker")
|
||||
while True:
|
||||
usr_input = input("Please enter your Number: ")
|
||||
print("1. Check ISBN")
|
||||
print("2. Check IBAN")
|
||||
print("3. Exit")
|
||||
usr_choice = input("1 / 2 / 3 ?: ")
|
||||
|
||||
if usr_choice == "1":
|
||||
if is_valid_isbn(usr_input):
|
||||
print("Valid ISBN")
|
||||
else:
|
||||
print("Invalid ISBN")
|
||||
if usr_choice == "2":
|
||||
if is_valid_iban(usr_input):
|
||||
print("Valid IBAN")
|
||||
else:
|
||||
print("Invalid IBAN")
|
||||
if usr_choice == "3":
|
||||
break
|
||||
|
||||
def main():
|
||||
app = Checker()
|
||||
app.run()
|
||||
|
||||
console_checker()
|
||||
@@ -0,0 +1,38 @@
|
||||
import tkinter as tk
|
||||
|
||||
from my_package.App_window import AppWindow
|
||||
|
||||
|
||||
class VowelDelete (AppWindow):
|
||||
def __init__(self):
|
||||
super().__init__(300,300)
|
||||
self.vowels = ['a', 'e', 'i', 'o', 'u']
|
||||
self.button = tk.Button(self.root, text="decompose", command=self.on_click)
|
||||
self.label = tk.Label(self.root, text="enter text: ")
|
||||
self.entry = tk.Entry(self.root, width=20)
|
||||
self.list = tk.Listbox(self.root)
|
||||
|
||||
def init_widgets(self):
|
||||
self.label.grid(row=0, column=0)
|
||||
self.entry.grid(row=0, column=1)
|
||||
self.button.grid(row=1, column=0)
|
||||
self.list.grid(row=1, column=1)
|
||||
|
||||
def on_click(self):
|
||||
entry = self.entry.get()
|
||||
self.entry.delete(tk.END)
|
||||
entry_split = list(entry)
|
||||
|
||||
c_entry_split = entry_split.copy()
|
||||
for vowel in c_entry_split:
|
||||
if vowel in self.vowels:
|
||||
entry_split.remove(vowel)
|
||||
result = ''.join(entry_split)
|
||||
|
||||
self.list.insert(tk.END, str(result))
|
||||
|
||||
def main():
|
||||
app = VowelDelete()
|
||||
app.run()
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
class GameServerQueue:
|
||||
def __init__(self, num_player_team: int, queue=None):
|
||||
if queue is None:
|
||||
self.queue = []
|
||||
self._num_player_team = num_player_team
|
||||
|
||||
|
||||
def enqueue(self, player_name):
|
||||
self.queue.append(player_name)
|
||||
|
||||
def dequeue(self):
|
||||
try:
|
||||
dequed_player = self.queue.pop(0)
|
||||
return dequed_player
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
|
||||
def fill_queue_with_names(self):
|
||||
player_names = ["xx_sniperLegend_xx","smorkelo","John Warframe","uriel","helldiver david"]
|
||||
for i in range(len(player_names)):
|
||||
self.enqueue(player_names[i])
|
||||
|
||||
def build_teams(self):
|
||||
teams = []
|
||||
while len(self.queue) >= 2:
|
||||
teams.append((self.dequeue(), self.dequeue()))
|
||||
return teams
|
||||
|
||||
def main():
|
||||
game = GameServerQueue(num_player_team=3)
|
||||
game.fill_queue_with_names()
|
||||
game.enqueue("the_tested_one")
|
||||
game.enqueue("the_tested_two")
|
||||
|
||||
print(game.queue)
|
||||
print(game.build_teams())
|
||||
print(game.queue)
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
Nuremberg > Berlin
|
||||
Nuremberg > Frankfurt
|
||||
Nuremberg > Munich
|
||||
Munich > Nuremberg
|
||||
Hamburg > Berlin
|
||||
Berlin > Hamburg
|
||||
Berlin > Nuremberg
|
||||
@@ -0,0 +1,75 @@
|
||||
class Trains:
|
||||
def __init__(self):
|
||||
self.cities = []
|
||||
self.connections: dict[str, list] = dict()
|
||||
self.f_length = 0
|
||||
self.setup()
|
||||
|
||||
def add_connection(self, city, connection):
|
||||
self.connections[city] = connection
|
||||
|
||||
def setup(self):
|
||||
with open("t_connections.txt", "r") as f:
|
||||
for line in f:
|
||||
self.f_length += 1
|
||||
|
||||
f.seek(0)
|
||||
for _ in range(self.f_length):
|
||||
line = f.readline().strip()
|
||||
split_line = line.split()
|
||||
|
||||
if split_line[0] not in self.cities: self.cities.append(split_line[0])
|
||||
if split_line[2] not in self.cities: self.cities.append(split_line[2])
|
||||
|
||||
for _ in range(len(self.cities)):
|
||||
self.add_connection(self.cities[_], [])
|
||||
|
||||
f.seek(0)
|
||||
for _ in range(self.f_length):
|
||||
line = f.readline().strip()
|
||||
split_line = line.split()
|
||||
if split_line[2] not in self.connections[split_line[0]]:
|
||||
self.connections[split_line[0]].append(split_line[2])
|
||||
|
||||
def get_directions(self,origin):
|
||||
try:
|
||||
return self.connections[origin]
|
||||
except KeyError:
|
||||
return "Origin not Found"
|
||||
|
||||
|
||||
def main():
|
||||
trains = Trains()
|
||||
print(trains.cities)
|
||||
print(trains.connections)
|
||||
|
||||
print("Welcome to Route-Manager")
|
||||
print(f"Known origins {trains.cities}")
|
||||
|
||||
while True:
|
||||
print("1. Proceed to route search")
|
||||
print("2. quit")
|
||||
usr_input = input("1 / 2 ?: ")
|
||||
|
||||
if usr_input == "1":
|
||||
usr_origin = input("Set your origin: ")
|
||||
|
||||
if usr_origin in trains.cities:
|
||||
directions = trains.get_directions(usr_origin)
|
||||
l = len(directions)
|
||||
|
||||
if l != 0:
|
||||
for _ in range(l):
|
||||
print(f"{usr_origin} -> {directions[_]}")
|
||||
|
||||
else:
|
||||
print(f"No connections from {usr_origin}")
|
||||
|
||||
else:
|
||||
print("Origin not Found")
|
||||
|
||||
if usr_input == "2":
|
||||
break
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
import time
|
||||
|
||||
|
||||
def permute(picked: str, remaining: str):
|
||||
if remaining == "" :
|
||||
print(picked + remaining + ", ", end="")
|
||||
|
||||
else:
|
||||
for i in range(len(remaining)):
|
||||
pick = remaining[i]
|
||||
front = remaining[:i]
|
||||
back = remaining[i+1:]
|
||||
permute(picked + pick, front + back)
|
||||
|
||||
def main():
|
||||
start = time.time()
|
||||
permute("","abcdefghijk")
|
||||
end = time.time()
|
||||
print(end - start)
|
||||
#"abcdefghijk" takes 85 sec
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
import math
|
||||
import random
|
||||
from turtle import Turtle
|
||||
|
||||
|
||||
def draw_turtle_line(turtle, start: (float,float), end: (float, float)):
|
||||
turtle.penup()
|
||||
turtle.goto(start[0], start[1])
|
||||
turtle.pendown()
|
||||
turtle.goto(end[0], end[1])
|
||||
|
||||
def draw_branch(turtle, point: (float, float), angle: float, length: float):
|
||||
if length > 10:
|
||||
x1 = round(point[0] - math.sin(angle) * length)
|
||||
y1 = round(point[1] + math.cos(angle) * length)
|
||||
draw_turtle_line(turtle, point, (x1, y1))
|
||||
|
||||
bend_angle = math.radians(random.uniform(-10, 10))
|
||||
branch_angle = math.radians(random.uniform(-40, 40))
|
||||
draw_branch(turtle,(x1, y1), bend_angle - branch_angle, length *
|
||||
random.uniform(0.6, 0.8))
|
||||
draw_branch(turtle,(x1, y1), bend_angle + branch_angle, length *
|
||||
random.uniform(0.6, 0.8))
|
||||
|
||||
sophia = Turtle()
|
||||
draw_branch(sophia, (0, 0), 0.0 ,100)
|
||||
|
||||
sophia.screen.mainloop()
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import time
|
||||
|
||||
list_of_names = ['Alexander', 'Maximilianosohn', 'Peter', 'Jan',
|
||||
'Paul', 'Sabine', 'Franzi von Ulmen']
|
||||
|
||||
def bublesort(lst):
|
||||
for element in range(len(lst) - 1):
|
||||
if element != len(lst):
|
||||
if lst[element] > lst[element+1]:
|
||||
lst[element], lst[element+1] = lst[element+1], lst[element]
|
||||
print(f"'{lst[element]}' is greater then '{lst[element + 1]}', their postions are now swaped")
|
||||
print(f"current state of the list: {lst}")
|
||||
print()
|
||||
time.sleep(3)
|
||||
if lst != sorted(lst):
|
||||
bublesort(lst)
|
||||
print("bubble sort calls itself")
|
||||
print()
|
||||
time.sleep(2)
|
||||
return lst
|
||||
|
||||
print("Bubble sort is a simple sorting algorithm, that recursively iterates over the entire list")
|
||||
print()
|
||||
time.sleep(4)
|
||||
print("Each letter in the alphabet has its own value, the later they appear in the alphabet, the higher their value")
|
||||
print()
|
||||
time.sleep(4)
|
||||
print("If a value is greater then the next value in the list, their positions will be swapped")
|
||||
print()
|
||||
time.sleep(4)
|
||||
print("This Process is repeated until all elements in the list are sorted.")
|
||||
print()
|
||||
time.sleep(4)
|
||||
print("The following messages will show the process in detail")
|
||||
print()
|
||||
time.sleep(3)
|
||||
print(bublesort(list_of_names))
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import random
|
||||
|
||||
import pygame
|
||||
|
||||
from my_package.Game_class import Game
|
||||
from my_package.Spark_class import Spark
|
||||
|
||||
|
||||
class PiDraw(Game):
|
||||
def __init__(self, inner_c=None, outer_c=None):
|
||||
self.inner_c = inner_c if inner_c is not None else []
|
||||
self.outer_c = outer_c if outer_c is not None else []
|
||||
super().__init__()
|
||||
|
||||
def update_game(self):
|
||||
for _ in range(2):
|
||||
x = random.randint(0,500)
|
||||
y = random.randint(0,500)
|
||||
|
||||
if (x**2 + y**2) < 500**2: self.inner_c.append(Spark(x, y, (0,255,0), 1))
|
||||
else: self.outer_c.append(Spark(x, y, (255,0,0), 1))
|
||||
|
||||
try:
|
||||
pi = 4.0 * len(self.inner_c) / (len(self.inner_c) + len(self.outer_c))
|
||||
print(pi)
|
||||
except ZeroDivisionError: print("ZeroDivisionError")
|
||||
|
||||
return True
|
||||
|
||||
def draw_game(self):
|
||||
for particle in self.inner_c + self.outer_c:
|
||||
particle.set_surface(self.set_screen())
|
||||
particle.appear(self.set_screen())
|
||||
pygame.display.flip()
|
||||
|
||||
|
||||
def main():
|
||||
game = PiDraw()
|
||||
game.run()
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,17 @@
|
||||
def gcd():
|
||||
i1 = int(input("enter first number : "))
|
||||
i2 = int(input("enter second number : "))
|
||||
|
||||
while True:
|
||||
i1 // i2
|
||||
r = i1 % i2
|
||||
|
||||
if r == 0:
|
||||
print(f"GCD= {i2}")
|
||||
break
|
||||
|
||||
else:
|
||||
i1 = i2
|
||||
i2 = r
|
||||
|
||||
gcd()
|
||||
@@ -0,0 +1,48 @@
|
||||
import tkinter as tk
|
||||
|
||||
from my_package.App_window import AppWindow
|
||||
|
||||
label_names = ["a:","b:","m:","seed:"]
|
||||
entries = []
|
||||
labels = []
|
||||
|
||||
class LehmerAlg (AppWindow):
|
||||
def __init__(self):
|
||||
super().__init__(300,500)
|
||||
self.button = tk.Button(self.root, text="calculate", command=self.on_click)
|
||||
self.c_button = tk.Button(self.root, text="close", command=self.close)
|
||||
self.list = tk.Listbox(self.root)
|
||||
|
||||
def init_widgets(self):
|
||||
r = 0
|
||||
for _ in range(4):
|
||||
entry = tk.Entry(self.root, width=20)
|
||||
entry.grid(row=r, column=1)
|
||||
entries.append(entry)
|
||||
label = tk.Label(self.root, text=f"{label_names[r]}")
|
||||
label.grid(row=r, column=0)
|
||||
labels.append(label)
|
||||
r +=1
|
||||
self.button.grid(column=2, row=0)
|
||||
self.c_button.grid(column=2, row=1)
|
||||
self.list.grid(column=1, row=5)
|
||||
|
||||
def on_click(self):
|
||||
val = 0
|
||||
for _ in range(4):
|
||||
label_names[val] = entries[val].get()
|
||||
entries[val].delete(0, tk.END)
|
||||
val +=1
|
||||
|
||||
result = (int(label_names[0])*int(label_names[3])+int(label_names[1])) %int(label_names[2])
|
||||
#v_k = (a * v_k + b) % m
|
||||
self.list.insert(tk.END, result)
|
||||
|
||||
def close(self):
|
||||
self.root.destroy()
|
||||
|
||||
def main ():
|
||||
app = LehmerAlg()
|
||||
app.run()
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
r = 50
|
||||
for _ in range (r):
|
||||
print("i like programming")
|
||||
@@ -0,0 +1,57 @@
|
||||
class Node:
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
self.visited = False
|
||||
self.left = None
|
||||
self.right = None
|
||||
|
||||
def __str__(self):
|
||||
return self.data
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
def traverse (node, stack = None):
|
||||
if stack is None:
|
||||
stack = []
|
||||
|
||||
if node.left and node.left.visited == False:
|
||||
stack.append(node.left)
|
||||
print(node.left.data)
|
||||
node.left.visited = True
|
||||
traverse(node.left)
|
||||
|
||||
if node.right and node.right.visited == False:
|
||||
stack.append(node.right)
|
||||
print(node.right.data)
|
||||
node.right.visited = True
|
||||
traverse(node.right)
|
||||
|
||||
else :
|
||||
if len(stack) > 0:
|
||||
traverse(stack[len(stack)-1])
|
||||
stack.pop()
|
||||
|
||||
root = Node(6)
|
||||
node_two = Node(2)
|
||||
node_seven = Node(7)
|
||||
node_one = Node(1)
|
||||
node_four = Node(4)
|
||||
node_three = Node(3)
|
||||
node_five = Node(5)
|
||||
node_six = Node(6)
|
||||
node_nine = Node(9)
|
||||
|
||||
|
||||
root.left = node_two
|
||||
root.right = node_seven
|
||||
|
||||
node_two.left = node_one
|
||||
node_one.right = node_four
|
||||
|
||||
node_four.right = node_three
|
||||
node_three.right = node_five
|
||||
|
||||
node_seven.left = node_six
|
||||
node_six.right = node_nine
|
||||
|
||||
traverse(root)
|
||||
@@ -0,0 +1,52 @@
|
||||
class Node:
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
self.visited = False
|
||||
self.children = []
|
||||
|
||||
def is_internal_external(self):
|
||||
if self.children:
|
||||
return True
|
||||
return False
|
||||
|
||||
def get_children(self):
|
||||
return self.children
|
||||
|
||||
|
||||
|
||||
def __str__(self):
|
||||
return self.data
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
def traverse (node, stack = None):
|
||||
if stack is None:
|
||||
stack = []
|
||||
|
||||
if node.children is not None:
|
||||
for child in node.children:
|
||||
if not child.visited:
|
||||
child.visited = True
|
||||
stack.append(child)
|
||||
print(child.data)
|
||||
traverse(child)
|
||||
else:
|
||||
if len(stack) > 0:
|
||||
traverse(stack[len(stack) - 1])
|
||||
stack.pop()
|
||||
|
||||
root = Node(6)
|
||||
node_two = Node(2)
|
||||
node_seven = Node(7)
|
||||
node_one = Node(1)
|
||||
node_four = Node(4)
|
||||
node_three = Node(3)
|
||||
node_five = Node(5)
|
||||
node_six = Node(6)
|
||||
node_nine = Node(9)
|
||||
|
||||
root.children = [node_two, node_seven, node_one]
|
||||
node_two.children = [node_four, node_three]
|
||||
node_seven.children = [node_five, node_six]
|
||||
|
||||
traverse(root)
|
||||
@@ -0,0 +1,29 @@
|
||||
import numpy as np
|
||||
|
||||
bins = [" 0-9: ","10-19: ","20-29: ","30-39: ","40-49: ","50-59: ","60-69: ","70-79: ","80-89: ","90-99: "]
|
||||
|
||||
def get_distribution():
|
||||
# Generate normal distribution (mean_value, standard_deviation, size)
|
||||
exam_points = np.random.normal(60, 20, 67)
|
||||
# round to integer datatype
|
||||
exam_points = np.rint(exam_points).astype(int)
|
||||
# clip values between 15 and 95
|
||||
exam_points = np.clip(exam_points, 15, 95)
|
||||
|
||||
for points in exam_points:
|
||||
pass
|
||||
|
||||
return exam_points
|
||||
|
||||
def generate_arr():
|
||||
arr = np.ndarray((10,10), dtype=object)
|
||||
|
||||
for pos in range (10):
|
||||
arr[(pos,0)] = bins[pos]
|
||||
|
||||
print(arr)
|
||||
|
||||
def main():
|
||||
generate_arr()
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,45 @@
|
||||
class Student:
|
||||
def __init__(self, number, name, email):
|
||||
self.number = number
|
||||
self.name = name
|
||||
self.email = email
|
||||
self.MAX_HASH =100000
|
||||
|
||||
def __str__(self):
|
||||
return f"Student: {self.name} ({self.email}, {self.number})"
|
||||
|
||||
def __hash__(self):
|
||||
return (id(self.number) + id(self.name) + id(self.email)) % self.MAX_HASH
|
||||
|
||||
|
||||
class HashTable:
|
||||
def __init__(self, elements):
|
||||
self.bucket_size = len(elements) * 3
|
||||
self.buckets = [[] for i in range(self.bucket_size)]
|
||||
self._assign_buckets(elements)
|
||||
self.insertion_order = []
|
||||
|
||||
def __iter__(self):
|
||||
ret_list = []
|
||||
for index, obj_id in self.insertion_order:
|
||||
for obj in self.buckets[index]:
|
||||
if id(obj) == obj_id:
|
||||
ret_list.append(obj)
|
||||
return iter(ret_list)
|
||||
|
||||
def _assign_buckets(self, elements):
|
||||
for obj in elements:
|
||||
hashed_value = hash(obj)
|
||||
index = hashed_value % self.bucket_size
|
||||
self.buckets[index].append(obj)
|
||||
self.insertion_order.insert((index, id(obj)))
|
||||
|
||||
def get_value(self,input_key):
|
||||
return self.buckets[input_key]
|
||||
|
||||
def main():
|
||||
arthur = Student("097", "Arthur", "artur@blade.hex")
|
||||
eleanor = Student("098", "Eleanor", "eleano@plague.hex")
|
||||
aoi = Student("099", "Aoi", "aoi@magnet.hex")
|
||||
hash_table = HashTable([arthur,eleanor,aoi])
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
class Student:
|
||||
|
||||
def __init__(self, number, name, email):
|
||||
self.number = number
|
||||
self.name = name
|
||||
self.email = email
|
||||
self.MAX_HASH =100000
|
||||
|
||||
def __str__(self):
|
||||
return f"Student: {self.name} ({self.email}, {self.number})"
|
||||
|
||||
def __hash__(self):
|
||||
return (id(self.number) + id(self.name) + id(self.email)) % self.MAX_HASH
|
||||
|
||||
def main():
|
||||
student = Student("0975", "Arthur", "arthur@blade.hex")
|
||||
print(hash(student))
|
||||
for _ in range(10):
|
||||
main()
|
||||
@@ -0,0 +1,114 @@
|
||||
|
||||
|
||||
class RouteManager:
|
||||
def __init__(self,file="t_connections.txt"):
|
||||
self.cities = []
|
||||
self.connections: dict[str, list] = dict()
|
||||
self.journey = []
|
||||
self.f_length = 0
|
||||
self.setup(file)
|
||||
|
||||
def add_connection(self, city, connection):
|
||||
self.connections[city] = connection
|
||||
|
||||
|
||||
def setup(self,file):
|
||||
with open(file, "r") as f:
|
||||
for line in f:
|
||||
self.f_length += 1
|
||||
|
||||
f.seek(0)
|
||||
for _ in range(self.f_length):
|
||||
line = f.readline().strip()
|
||||
split_line = line.split()
|
||||
|
||||
|
||||
if split_line[0] not in self.cities:
|
||||
self.cities.append(split_line[0])
|
||||
|
||||
|
||||
if split_line[2] not in self.cities:
|
||||
self.cities.append(split_line[2])
|
||||
|
||||
for _ in range(len(self.cities)):
|
||||
self.add_connection(self.cities[_], [])
|
||||
|
||||
f.seek(0)
|
||||
for _ in range(self.f_length):
|
||||
line = f.readline().strip()
|
||||
split_line = line.split()
|
||||
if split_line[2] not in self.connections[split_line[0]]:
|
||||
self.connections[split_line[0]].append(split_line[2])
|
||||
|
||||
def get_directions(self,origin,):
|
||||
try:
|
||||
return self.connections[origin]
|
||||
except KeyError:
|
||||
return "Origin not Found"
|
||||
|
||||
def create_route(self,origin):
|
||||
if origin in self.cities:
|
||||
directions = self.get_directions(origin)
|
||||
l = len(directions)
|
||||
|
||||
if l != 0:
|
||||
for _ in range(l):
|
||||
print(f"{origin} -> {directions[_]}")
|
||||
print()
|
||||
else:
|
||||
print(f"No connections from {origin}")
|
||||
else:
|
||||
print("Origin not Found")
|
||||
|
||||
def add_to_journey(self,origin,destination):
|
||||
if not self.journey:
|
||||
self.journey.append(origin)
|
||||
self.journey.append(destination)
|
||||
else: self.journey.append(destination)
|
||||
|
||||
def save_journey(self,journey_name):
|
||||
with open(f"{journey_name}.txt", "a") as f:
|
||||
f.writelines(f" > {self.journey[_]}" for _ in range (len(self.journey)))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
rm = RouteManager()
|
||||
print("Welcome to Route-Manager")
|
||||
print(f"Known origins {rm.cities}")
|
||||
|
||||
while True:
|
||||
print("1. New journey")
|
||||
print("2. Load journey")
|
||||
print("3. quit")
|
||||
usr_input = input("1 / 2 / 3?: ")
|
||||
|
||||
if usr_input == "1":
|
||||
while True:
|
||||
usr_origin = input("Set your origin: ")
|
||||
print()
|
||||
rm.create_route(usr_origin)
|
||||
usr_destination = input("Type in your destination: ")
|
||||
rm.add_to_journey(usr_origin, usr_destination)
|
||||
print()
|
||||
|
||||
_usr_input = input("Continue Journey? (y/n): ")
|
||||
|
||||
if _usr_input == "n":
|
||||
usr_save = input("Save journey? (y/n): ")
|
||||
|
||||
if usr_save == "y":
|
||||
file_name = input("Enter file name: ")
|
||||
rm.save_journey(file_name)
|
||||
break
|
||||
|
||||
if usr_input == "2":
|
||||
pass
|
||||
|
||||
if usr_input == "3":
|
||||
break
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
Nuremberg > Berlin
|
||||
Nuremberg > Frankfurt
|
||||
Nuremberg > Munich
|
||||
Munich > Nuremberg
|
||||
Hamburg > Berlin
|
||||
Berlin > Hamburg
|
||||
Berlin > Nuremberg
|
||||
@@ -0,0 +1,3 @@
|
||||
> Nuremberg
|
||||
> Frankfurt
|
||||
> Nuremberg
|
||||
@@ -0,0 +1,106 @@
|
||||
class RouteManager:
|
||||
def __init__(self,file="t_connections.txt"):
|
||||
self.cities = []
|
||||
self.connections: dict[str, list] = dict()
|
||||
self.journey = []
|
||||
self.f_length = 0
|
||||
self.setup(file)
|
||||
|
||||
def add_connection(self, city, connection):
|
||||
self.connections[city] = connection
|
||||
|
||||
def setup(self,file):
|
||||
with open(file, "r") as f:
|
||||
for line in f:
|
||||
self.f_length += 1
|
||||
|
||||
f.seek(0)
|
||||
for _ in range(self.f_length):
|
||||
line = f.readline().strip()
|
||||
split_line = line.split()
|
||||
|
||||
if split_line[0] not in self.cities: self.cities.append(split_line[0])
|
||||
if split_line[2] not in self.cities: self.cities.append(split_line[2])
|
||||
|
||||
for _ in range(len(self.cities)):
|
||||
self.add_connection(self.cities[_], [])
|
||||
|
||||
f.seek(0)
|
||||
for _ in range(self.f_length):
|
||||
line = f.readline().strip()
|
||||
split_line = line.split()
|
||||
if split_line[2] not in self.connections[split_line[0]]:
|
||||
self.connections[split_line[0]].append(split_line[2])
|
||||
|
||||
def get_directions(self,origin,):
|
||||
try:
|
||||
return self.connections[origin]
|
||||
except KeyError:
|
||||
return "Origin not Found"
|
||||
|
||||
def create_route(self,origin):
|
||||
if origin in self.cities:
|
||||
directions = self.get_directions(origin)
|
||||
l = len(directions)
|
||||
|
||||
if l != 0:
|
||||
for _ in range(l):
|
||||
print(f"{origin} -> {directions[_]}")
|
||||
print()
|
||||
else:
|
||||
print(f"No connections from {origin}")
|
||||
else:
|
||||
print("Origin not Found")
|
||||
|
||||
def add_to_journey(self,origin,destination):
|
||||
if not self.journey:
|
||||
self.journey.append(origin)
|
||||
self.journey.append(destination)
|
||||
else: self.journey.append(destination)
|
||||
|
||||
def save_journey(self,journey_name):
|
||||
with open(f"{journey_name}.txt", "a") as f:
|
||||
f.writelines(f" > {self.journey[_]}" for _ in range (len(self.journey)))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
rm = RouteManager()
|
||||
print("Welcome to Route-Manager")
|
||||
print(f"Known origins {rm.cities}")
|
||||
|
||||
while True:
|
||||
print("1. New journey")
|
||||
print("2. Load journey")
|
||||
print("3. quit")
|
||||
usr_input = input("1 / 2 / 3?: ")
|
||||
|
||||
if usr_input == "1":
|
||||
while True:
|
||||
usr_origin = input("Set your origin: ")
|
||||
print()
|
||||
rm.create_route(usr_origin)
|
||||
usr_destination = input("Type in your destination: ")
|
||||
rm.add_to_journey(usr_origin, usr_destination)
|
||||
print()
|
||||
|
||||
_usr_input = input("Continue Journey? (y/n): ")
|
||||
|
||||
if _usr_input == "n":
|
||||
usr_save = input("Save journey? (y/n): ")
|
||||
|
||||
if usr_save == "y":
|
||||
file_name = input("Enter file name: ")
|
||||
rm.save_journey(file_name)
|
||||
break
|
||||
|
||||
if usr_input == "2":
|
||||
pass
|
||||
|
||||
if usr_input == "3":
|
||||
break
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
def palindrome_check(word: str, front: int = 0):
|
||||
|
||||
back = len(word)-1 - front
|
||||
print(word[front], word[back])
|
||||
|
||||
if front >= back:
|
||||
print("Palindrome")
|
||||
|
||||
elif word[front] == word[back]:
|
||||
front += 1
|
||||
palindrome_check(word, front)
|
||||
|
||||
|
||||
|
||||
word = input("Enter a word: ")
|
||||
word = word.casefold()
|
||||
word = word.replace(" ", "")
|
||||
|
||||
palindrome_check(word)
|
||||
@@ -0,0 +1,27 @@
|
||||
import pygame
|
||||
|
||||
from my_package.Game_class import Game
|
||||
|
||||
|
||||
class TriangleTriangle(Game):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.WHITE = (255, 255, 255)
|
||||
self.surface = pygame.Surface((100, 100))
|
||||
|
||||
def draw_triangle(self, screen, x: float, y: float, w: float, h:float):
|
||||
p1 = (x, y)
|
||||
p2 = (x + w, y)
|
||||
p3 = (x + w / 2, y + h)
|
||||
pygame.draw.polygon(screen, self.WHITE, [p1, p2, p3], 1)
|
||||
|
||||
def draw_sierpinski(self, screen, x: float, y: float, w: float, h:float):
|
||||
self.draw_triangle(screen, x, y, w, h)
|
||||
|
||||
# TODO: base case
|
||||
# recursive case
|
||||
h2 = h / 2
|
||||
w2 = w / 2
|
||||
self.draw_sierpinski(screen, x, y, w2, h2)
|
||||
self.draw_sierpinski(screen, x + w2 / 2, y + h2, w2, h2)
|
||||
self.draw_sierpinski(screen, x + w2, y, w2, h2)
|
||||
@@ -0,0 +1,35 @@
|
||||
import time
|
||||
|
||||
|
||||
def _min(lst: list, previous = None):
|
||||
if previous is None:
|
||||
previous = lst[0]
|
||||
for item in lst:
|
||||
previous = min(previous, item)
|
||||
return previous
|
||||
|
||||
def _max(lst: list, previous = None):
|
||||
if previous is None:
|
||||
previous = lst[0]
|
||||
for item in lst:
|
||||
previous = max(previous, item)
|
||||
return previous
|
||||
|
||||
def _avg(lst: list, total = 0):
|
||||
for item in lst:
|
||||
total += item
|
||||
return total / len(lst)
|
||||
|
||||
def main():
|
||||
i_lst = [5, 55, 2, 7, 45, 3, 1, 8, 23, 12]
|
||||
start = time.time()
|
||||
|
||||
for _ in range(100000):
|
||||
_min(i_lst)
|
||||
|
||||
end = time.time()
|
||||
print(end - start)
|
||||
print(_max(i_lst))
|
||||
print(_avg(i_lst))
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
def calc_prime(n: int, d = 2):
|
||||
if n % d == 0:
|
||||
return d
|
||||
else:
|
||||
d += 1
|
||||
calc_prime(n, d)
|
||||
return False
|
||||
|
||||
def power_calc(n: int):
|
||||
p = calc_prime(n)
|
||||
#print(f"{p}^{n/p}")
|
||||
print(f"{n}/{p}")
|
||||
|
||||
power_calc(81)
|
||||
@@ -0,0 +1,16 @@
|
||||
def fibitts(s_population: list, months: int, previous = None):
|
||||
#every 2 months: 1 pair -> 2 pairs
|
||||
#newborn pair can produce a new pair only after 2 months
|
||||
|
||||
if previous is None:
|
||||
previous = s_population[0]
|
||||
|
||||
for month in range(months+1):
|
||||
if month == 0:
|
||||
pass
|
||||
else:
|
||||
s_population.append(s_population[month]+previous)
|
||||
print(f"Month {month}: {s_population[month]}")
|
||||
previous = s_population[month]
|
||||
|
||||
fibitts([1,1], 24)
|
||||
@@ -0,0 +1,22 @@
|
||||
new_lst = ["Alex", "Moin", "ka", "world", "Zh", "lakj"]
|
||||
s_lst = sorted(new_lst)
|
||||
|
||||
def bnr_search(lst, target):
|
||||
low = 0
|
||||
high = len(lst) - 1
|
||||
|
||||
while low <= high:
|
||||
mid = (low + high) // 2
|
||||
|
||||
if lst[mid] == target:
|
||||
print("found target")
|
||||
return mid
|
||||
elif lst[mid] < target:
|
||||
low = mid + 1
|
||||
else:
|
||||
high = mid - 1
|
||||
|
||||
return None, print("not found")
|
||||
|
||||
|
||||
bnr_search(s_lst, "Alex")
|
||||
@@ -0,0 +1,9 @@
|
||||
new_lst = ["Hallo", "Alex", "Moin", "ka", "world", "Zh"]
|
||||
|
||||
def lin_search(lst,target):
|
||||
for element in lst:
|
||||
if element == target:
|
||||
print(f"found '{element}' in {lst}")
|
||||
print("finished search")
|
||||
|
||||
lin_search(new_lst, "Alex")
|
||||
@@ -0,0 +1,7 @@
|
||||
list_of_ints = [5, 55, 2, 7, 45, 3, 1, 8, 23, 12]
|
||||
list_of_ints.sort(reverse=False)
|
||||
print(list_of_ints)
|
||||
l = ['Hallo', 'Alex', 'Moin', 'ka', 'world', 'Zh', 'lakj']
|
||||
new_sorted_list = sorted(l, key= len)
|
||||
print(new_sorted_list)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import random
|
||||
import time
|
||||
|
||||
|
||||
def merge_sort(arr: list[int]) -> list[int]:
|
||||
if len(arr) <= 1:
|
||||
return arr
|
||||
|
||||
mid = len(arr) // 2
|
||||
left_half = arr[:mid]
|
||||
right_half = arr[mid:]
|
||||
|
||||
left_half = merge_sort(left_half)
|
||||
right_half = merge_sort(right_half)
|
||||
|
||||
return merge(left_half, right_half)
|
||||
|
||||
def merge(left: list[int], right: list[int], merged=None) -> list[int]:
|
||||
if merged is None:
|
||||
merged = []
|
||||
l_index = 0
|
||||
r_index = 0
|
||||
|
||||
while l_index < len(left) and r_index < len(right):
|
||||
if left[l_index] <= right[r_index]:
|
||||
merged.append(left[l_index])
|
||||
l_index += 1
|
||||
else:
|
||||
merged.append(right[r_index])
|
||||
r_index += 1
|
||||
|
||||
merged += left[l_index:]
|
||||
merged += right[r_index:]
|
||||
return merged
|
||||
|
||||
NUM_ELEMENTS = 1_000_000
|
||||
l = [random.randint(0, 2*NUM_ELEMENTS) for _ in range(NUM_ELEMENTS)]
|
||||
|
||||
start = time.time()
|
||||
print(merge_sort(l))
|
||||
end = time.time()
|
||||
print(f"time elapsed: {end - start} sec")
|
||||
@@ -0,0 +1,10 @@
|
||||
import random
|
||||
import time
|
||||
|
||||
NUM_ELEMENTS = 1_000_000
|
||||
l = [random.randint(0, 2*NUM_ELEMENTS) for _ in range(NUM_ELEMENTS)]
|
||||
|
||||
start = time.time()
|
||||
sorted(l)
|
||||
end = time.time()
|
||||
print(end - start)
|
||||
@@ -0,0 +1,35 @@
|
||||
class Node:
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
def __str__(self):
|
||||
return self.value
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
class Graph:
|
||||
def __init__(self):
|
||||
self.nodes = []
|
||||
self.connections = {}
|
||||
self.new_node("root")
|
||||
|
||||
def new_node(self,value, connections= None):
|
||||
value = Node(value)
|
||||
self.connections[value] = connections
|
||||
self.nodes.append(value)
|
||||
|
||||
def add_connection(self, node_name, connections):
|
||||
self.connections[node_name] = connections
|
||||
|
||||
|
||||
def create_graph():
|
||||
g = Graph()
|
||||
g.new_node("1")
|
||||
g.add_connection("1", ["root","2","3"])
|
||||
g.new_node("2")
|
||||
g.add_connection("2", ["root","3","4"])
|
||||
g.new_node("3")
|
||||
g.new_node("4")
|
||||
g.add_connection("3", ["5"])
|
||||
g.new_node("5")
|
||||
|
||||
create_graph()
|
||||
@@ -0,0 +1,120 @@
|
||||
from collections import deque
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import networkx as nx
|
||||
|
||||
# ==========================================
|
||||
# 1. THE SEARCH ALGORITHMS (Add new ones here)
|
||||
# ==========================================
|
||||
|
||||
|
||||
def bfs_algorithm(graph, start_node):
|
||||
"""
|
||||
Breadth-First Search
|
||||
"""
|
||||
visited = set()
|
||||
queue = deque([start_node])
|
||||
|
||||
while queue:
|
||||
current = queue.popleft()
|
||||
|
||||
if current not in visited:
|
||||
visited.add(current)
|
||||
|
||||
for neighbor in graph.neighbors(current):
|
||||
if neighbor not in visited:
|
||||
queue.append(neighbor)
|
||||
|
||||
# Send current engine state back to the visualizer
|
||||
yield current, visited
|
||||
|
||||
|
||||
def recursive_dfs_algorithm(graph, start_node):
|
||||
"""
|
||||
Depth-First Search
|
||||
"""
|
||||
visited = set()
|
||||
|
||||
# 1. Define the internal recursive function
|
||||
def dfs_helper(node):
|
||||
if node not in visited:
|
||||
visited.add(node)
|
||||
|
||||
# Send current frame state back up the chain to the visualizer
|
||||
yield node, visited
|
||||
|
||||
for neighbor in graph.neighbors(node):
|
||||
if neighbor not in visited:
|
||||
# 2. 'yield from' intercepts values from deep recursive steps
|
||||
yield from dfs_helper(neighbor)
|
||||
|
||||
# 3. Start the recursion and pass the generator out
|
||||
return dfs_helper(start_node)
|
||||
|
||||
|
||||
# ==========================================
|
||||
# 2. THE VISUALIZER ENGINE
|
||||
# ==========================================
|
||||
|
||||
class GraphVisualizer:
|
||||
def __init__(self, graph):
|
||||
self.graph = graph
|
||||
# Precompute layouts so nodes stay completely still
|
||||
self.pos = nx.spring_layout(graph, seed=42)
|
||||
|
||||
def run_animation(self, algorithm_generator, title="Search Animation", delay=1.5):
|
||||
"""
|
||||
Consumes states from the algorithm generator and updates the frame.
|
||||
"""
|
||||
plt.ion() # Turn on interactive plotting mode
|
||||
fig, ax = plt.subplots(figsize=(6, 5))
|
||||
|
||||
# Pull each state frame out of the search algorithm sequentially
|
||||
for current_node, visited_nodes in algorithm_generator:
|
||||
|
||||
# Build node colors based on current frame data
|
||||
color_map = []
|
||||
for node in self.graph.nodes():
|
||||
if node == current_node:
|
||||
color_map.append('orange') # Current frontier node
|
||||
elif node in visited_nodes:
|
||||
color_map.append('lightgreen') # Already processed
|
||||
else:
|
||||
color_map.append('skyblue') # Unvisited
|
||||
|
||||
# Draw frame
|
||||
ax.clear()
|
||||
nx.draw(
|
||||
self.graph, self.pos, with_labels=True,
|
||||
node_color=color_map, node_size=800,
|
||||
font_weight='bold', ax=ax
|
||||
)
|
||||
ax.set_title(f"{title}\nActive Node: {current_node}")
|
||||
|
||||
plt.draw()
|
||||
plt.pause(delay)
|
||||
|
||||
plt.ioff()
|
||||
plt.show()
|
||||
|
||||
|
||||
# ==========================================
|
||||
# 3. RUNNING THE CODE
|
||||
# ==========================================
|
||||
if __name__ == "__main__":
|
||||
# Define a test graph
|
||||
G = nx.Graph()
|
||||
edges = [('A', 'B'), ('A', 'C'), ('B', 'D'), ('B', 'E'), ('C', 'F'), ('E', 'F')]
|
||||
G.add_edges_from(edges)
|
||||
|
||||
# Initialize visualizer engine
|
||||
viz = GraphVisualizer(G)
|
||||
|
||||
# Easily swap algorithms by passing different generator objects
|
||||
print("Running Breadth-First Search...")
|
||||
bfs_gen = bfs_algorithm(G, 'A')
|
||||
viz.run_animation(bfs_gen, title="Breadth-First Search (BFS)", delay=1.0)
|
||||
|
||||
print("Running Depth-First Search...")
|
||||
dfs_gen = recursive_dfs_algorithm(G, 'A')
|
||||
viz.run_animation(dfs_gen, title="Depth-First Search (DFS)", delay=1.0)
|
||||
@@ -0,0 +1,5 @@
|
||||
a = set("abracadabra")
|
||||
print(a)
|
||||
b = {"a", "b", "c"}
|
||||
print(a & b)
|
||||
print(a | b)
|
||||
Reference in new issue
Block a user