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
111 changes: 111 additions & 0 deletions graphy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@



# Singly Linked List
from typing import no_type_check_decorator


class ListNode:
def __init__(self, value):
self.value = value
self.next = None

# self.prev if DLL

# LL traversal
current = node
while current is not None:
current = current.next


class BinarySearchTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None

# BST Traversal
## BFT or DFT
### Stack, Queue

while node is not None:
recurse(self.left)
recurse(self.right)


class GraphNode:
def __init__(self, value):
self.value = 'B'

# options: dictionary, array, set
# B's connections
self.connections = set('A', 'C', 'D')

# A's connections
self.connections = set('B')

# D's connections - it's a zero - Billy no mates!
self.connections = set()


# outbound vs inbound conections?

# Grpah terminology for 2-way vs 1-way connections
## undirected graph vs directed graph
## (FB, LinkedIn) vs (instagram, Twitter, TikTok)

## Graph Traversals

## DFT, stack
### check every node once, check every connection once

# make a stack
stack = Stack('A', 'B')
# make a set to track visited
visited = set('A', 'B', 'D', 'C')

# put the start node into the stack

# while the stack isn't empty

## pop off the top of the stack, this is the current node
current_node = 'B'
## check if we have visited this node
### if not, add it to our visited set
### and add each of it's neighbors to our stack
#### started with just A as current node and moved on ^^^^

## Time complexity? O(n)
## how many times do we visit each node? once
### how many times did we check each connection? once

## O(number of nodes + number of connections)
### O(n + m)
## so linear!

# BFT, Queue
# ---->>>>
q = Queue('D', 'C')

# make a set to track visited
visited = set('A', 'B')
# enqueue the start node
# while our queue isn't empty
## dequeue from front of line, this is our current node
current_node = 'B' # then move to 'C', add to visited, get neighbors, add to queue
## check if we've visited the node yet
### if not, add to visited
### get it's neighbors, for each add to queue
neighbors = set('C', 'D')
## RIPPLES! A) B) CD) EFG) ')' is the ripple

# Time complexity? O(n)
## visit every node once, visit every edge once
## O(n + m)
## O(node + edge)
## linear as well!

# DFT vs. BFT
## same time complexity, each just as fast
## DFT can be done recursively
## BFT can find shorter path
158 changes: 149 additions & 9 deletions projects/adventure/adv.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,146 @@
# traversal_path = ['n', 'n']
traversal_path = []

def traverse(player):
# create a dict for storage
d = {}
# keep track of visited rooms
visited = []
# get the id of the starting room
starting_room = world.starting_room.id
# create a dict entry for starting room
d[starting_room] = {}
# get starting room exits
exits = world.starting_room.get_exits()
# for each exit, create a dict key for that room with '?' value
for exit in exits:
d[starting_room][exit] = '?'
# choose a random direction to start in
direction = random.choice(exits)
# get next room id
next_room = player.current_room.get_room_in_direction(direction).id
# change the starting room '?' value to room id for that exit
d[starting_room][direction] = next_room
# add both rooms to visited
visited.append([starting_room, next_room])
# create a stack and queue
stack = [[next_room, direction]]
queue = []
# while the dictionary does not have as many entries as rooms
while len(d) < len(room_graph):
# while we have a stack to go through
while stack:
# pop off top of stack (curr includes a room
# and the direction it takes to get there)
curr = stack.pop()
# append direction and then travel
player.travel(curr[-1])
traversal_path.append(curr[-1])
# get exit rooms
exits = player.current_room.get_exits()
# if room not in dictionary, add it
if player.current_room.id not in d:
d[player.current_room.id] = {}
for exit in exits:
d[player.current_room.id][exit] = '?'
# get list of unvisited rooms (this area could be condensed)
list_of_rooms = {}
for exit in exits:
list_of_rooms[exit] = player.current_room.get_room_in_direction(exit).id
unvisited_exits = []
unvisited_exits.append([k for k, v in list_of_rooms.items() if v not in visited])
# if unvisited rooms
try:
unvisited_exits = unvisited_exits[0][0]
# get direction for each unvisited room
for ex in unvisited_exits:
direction = ex[0]
# add the room to visited
visited.append(player.current_room.get_room_in_direction(direction).id)
# add room and direction to stack
stack.append([player.current_room.id, direction])
# add room and direction to dictionary
d[player.current_room.id][direction] = player.current_room.get_room_in_direction(direction).id
# if no unvisited rooms (this are should be condensed), find an exit with a question mark
except:
# empty the stack
stack = []
break
# add current room to queue
queue.append([player.current_room.id])
min_path_length = 999
# while we have a queue
while queue:
# pop off top path
path = queue.pop(0)
# get the last node in the path
last_in_path = path[-1]
# if we found a room with a question mark
if '?' in d[last_in_path].values():
# use the path to travel to the next room and add to traversal path and visited
for i, room in enumerate(path[:-1]):
direction = list(d[room].keys())[list(d[room].values()).index(path[i+1])]
traversal_path.append(direction)
player.travel(direction)
visited.append(room) # last one will be appended in stack
# first, find if any unvisited rooms and get list
exits = player.current_room.get_exits()
list_of_rooms = {}
for exit in exits:
list_of_rooms[exit] = player.current_room.get_room_in_direction(exit).id
# see if there are unvisited rooms before choosing one with a '?'
# get list of unvisited rooms
unvisited_exits = []
unvisited_exits.append([k for k, v in list_of_rooms.items() if v not in visited])
# try getting unvisited rooms
try:
unvisited_exits = unvisited_exits[0][0]
# if multiple unvisited rooms
if len(unvisited_exits) > 1:
# choose one at random and travel, adding to visited and stack and dict
random_exit = random.choice(unvisited_exits)
chosen_exit_room = player.current_room.get_room_in_direction(random_exit).id
visited.append(chosen_exit_room)
d[player.current_room.id][random_exit] = chosen_exit_room
stack.append([chosen_exit_room, random_exit])
queue = []
break
# if one unvisited room
elif len(unvisited_exits) == 1:
#travel there, adding it to visited, stack and dict
exit_room = player.current_room.get_room_in_direction(unvisited_exits).id
visited.append(exit_room)
d[player.current_room.id][unvisited_exits] = exit_room
stack.append([exit_room, unvisited_exits])
# empty the queue
queue = []
# if no unvisited rooms
except:
# find rooms whose exits have a value of '? '
unknown_exits = [key for (key, value) in d[player.current_room.id].items() if value == '?']
# choose one at random , add it to visited, dict, and stack
random_direction = random.choice(unknown_exits)
chosen = player.current_room.get_room_in_direction(random_direction).id
visited.append(chosen)
d[player.current_room.id][random_direction] = chosen
stack.append([chosen, random_direction])
# empty the queue
queue = []
# if this path still contains no rooms with '?' values in its exits
else:
# get exits
exits = world.rooms[last_in_path].get_exits()
# for each exit
for exit in exits:
# create a new path, appending the room leading off the exit
exit_id = world.rooms[last_in_path].get_room_in_direction(exit).id
if exit_id not in path:
new_path = list(path)
new_path.append(exit_id)
queue.append(new_path)
return traversal_path

traverse(player)


# TRAVERSAL TEST
Expand All @@ -51,12 +191,12 @@
#######
# UNCOMMENT TO WALK AROUND
#######
player.current_room.print_room_description(player)
while True:
cmds = input("-> ").lower().split(" ")
if cmds[0] in ["n", "s", "e", "w"]:
player.travel(cmds[0], True)
elif cmds[0] == "q":
break
else:
print("I did not understand that command.")
#player.current_room.print_room_description(player)
#while True:
# cmds = input("-> ").lower().split(" ")
# if cmds[0] in ["n", "s", "e", "w"]:
# player.travel(cmds[0], True)
# elif cmds[0] == "q":
# break
# else:
# print("I did not understand that command.")
46 changes: 45 additions & 1 deletion projects/ancestor/ancestor.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,47 @@

def earliest_ancestor(ancestors, starting_node):
pass
# create a hash table called vertices to store ancestors
vertices = {}
# add all ancestors to vertices dict
for ancestor in ancestors:
vertices[ancestor[1]] = set()
vertices[ancestor[0]] = set()
# add all ancestors' edges (ancestors)
for ancestor in ancestors:
vertices[ancestor[1]].add(ancestor[0])
# if starting vertex has no ancestors
if not vertices[starting_node]:
return -1
# if it has ancestors
else:
# create an empty list for stack
stack = []
# keep track of depth
depth = {starting_node:0}
# add the starting vertex to the stack
stack.append(starting_node)
# while there are ancestors in the stack
while stack:
# pop off the most recently added vertex
current_vert = stack.pop()
# get a list of its ancestors
edges = vertices[current_vert]
# loop through vertex's edges
for edge in edges:
# track the edge's depth as being one greater than the current node's
depth[edge] = depth[current_vert] + 1
# add edge to top of the stack
stack.append(edge)
# return the max depth(s)
max_value = max(depth.values())
# return the minimum key
return min([k for k, v in depth.items() if v == max_value])


if __name__ == '__main__':

# ancestors
test_ancestors = [(1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5),
(4, 8), (8, 9), (11, 8), (10, 1)]

print(earliest_ancestor(test_ancestors, 9))
Loading