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
29 changes: 22 additions & 7 deletions BinaryToDecimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,30 @@ def decToBin(decNum): #function created to convert decimal to binary with parame
return binNum

def convert(fromNum, fromBase, toBase): #function for converting from any base to any other base
# Step 1: Convert fromNum (represented as an integer using digits of fromBase) to a standard base 10 integer
val = 0
power = 0
temp = fromNum
while temp > 0:
digit = temp % 10
if digit >= fromBase:
raise ValueError(f"Digit {digit} is invalid for base {fromBase}")
val += digit * (fromBase ** power)
temp //= 10
power += 1

# Step 2: Convert standard base 10 integer to the target base (represented using base 10 digits)
toNum = 0
power = 0
while fromNum > 0:
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
while val > 0:
digit = val % toBase
toNum += digit * (10 ** power)
val //= toBase
power += 1
return toNum

# print (str(binToDec(101011)))
# print (str(decToBin(128)))
print (str(convert(127, 10, 8))) # converts 127 in base 10 to base 8
print (str(convert(101001, 2, 2)))
print("101011 in base 2 to base 10: " + str(binToDec(101011)))
print("128 in base 10 to base 2: " + str(decToBin(128)))
print("127 in base 10 to base 8: " + str(convert(127, 10, 8))) # converts 127 in base 10 to base 8
print("177 in base 8 to base 2: " + str(convert(177, 8, 2))) # converts 177 in base 8 to base 2

17 changes: 8 additions & 9 deletions DepthFirstSearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ def add_neighbor(self, v):
self.neighbors.sort()

class Graph:
vertices = {}
time = 0
def __init__(self):
self.vertices = {}
self.time = 0

def add_vertex(self, vertex):
if isinstance(vertex, Vertex) and vertex.name not in self.vertices:
Expand All @@ -39,20 +40,18 @@ def print_graph(self):
print(key + str(self.vertices[key].neighbors) + " " + str(self.vertices[key].discovery) + "/" + str(self.vertices[key].finish))

def _dfs(self, vertex):
global time
vertex.color = 'red'
vertex.discovery = time
time += 1
vertex.discovery = self.time
self.time += 1
for v in vertex.neighbors:
if self.vertices[v].color == 'black':
self._dfs(self.vertices[v])
vertex.color = 'blue'
vertex.finish = time
time += 1
vertex.finish = self.time
self.time += 1

def dfs(self, vertex):
global time
time = 1
self.time = 1
self._dfs(vertex)

g = Graph()
Expand Down
3 changes: 2 additions & 1 deletion HashMap.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def keys(self):
arr = []
for i in range(0, len(self.map)):
if self.map[i]:
arr.append(self.map[i][0])
for pair in self.map[i]:
arr.append(pair[0])
return arr

def print(self):
Expand Down
20 changes: 12 additions & 8 deletions HexToDec.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
# Python Hexadecimal to Decimal Conversion

def __getDecDigit(digit):
digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F']
for x in range(len(digits)):
if digit == digits[x]:
return x
digits = {
'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15
}
return digits.get(digit.upper())

def hexToDec(hexNum):
decNum = 0
power = 0
for digit in range(len(hexNum), 0, -1):
decNum = decNum + 16 ** power * __getDecDigit(hexNum[digit-1])
val = __getDecDigit(hexNum[digit-1])
if val is None:
raise ValueError(f"Invalid hexadecimal digit: {hexNum[digit-1]}")
decNum = decNum + 16 ** power * val
power += 1
print(str(decNum))
return decNum

hexToDec("A5")
print("A5 in decimal: " + str(hexToDec("A5")))
print("3c in decimal: " + str(hexToDec("3c")))
25 changes: 18 additions & 7 deletions MaxHeap.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,20 @@
# private functions: __swap, __floatUp, __bubbleDown

class MaxHeap:
def __init__(self, items=[]):
def __init__(self, items=None):
super().__init__()
self.heap = [0]
for i in items:
self.heap.append(i)
self.__floatUp(len(self.heap) - 1)
if items is not None:
for i in items:
self.heap.append(i)
self.__floatUp(len(self.heap) - 1)

def push(self, data):
self.heap.append(data)
self.__floatUp(len(self.heap) - 1)

def peek(self):
if self.heap[1]:
if len(self.heap) > 1:
return self.heap[1]
else:
return False
Expand Down Expand Up @@ -56,5 +57,15 @@ def __bubbleDown(self, index):

m = MaxHeap([95, 3, 21])
m.push(10)
print(str(m.heap[0:len(m.heap)]))
print(str(m.pop()))
print("Heap state:", m.heap)
print("Peek top:", m.peek())
print("Popped:", m.pop())
print("Peek top after pop:", m.peek())

# Test empty heap peek
empty_heap = MaxHeap()
print("Empty heap peek:", empty_heap.peek())

# Test heap with 0
heap_with_zero = MaxHeap([0])
print("Zero heap peek:", heap_with_zero.peek())
64 changes: 0 additions & 64 deletions Queues implementaion.py

This file was deleted.

116 changes: 116 additions & 0 deletions Queues_implementation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# Queue Implementation in Python
# This file includes two queue implementations:
# 1. LinkedListQueue: using a custom Node class.
# 2. ArrayQueue: using Python's built-in list.

class Node:
"""A class representing a node in a linked list queue."""
def __init__(self, item=None):
self.item = item
self.next = None
self.previous = None


class LinkedListQueue:
"""A Queue implementation using a doubly linked list."""
def __init__(self):
self.length = 0
self.head = None
self.tail = None

def enqueue(self, x):
"""Add an element to the back of the queue."""
new_node = Node(x)
if self.head is None:
self.head = self.tail = new_node
else:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
self.length += 1

def dequeue(self):
"""Remove and return the front element of the queue."""
if self.is_empty():
raise IndexError("dequeue from empty queue")
item = self.head.item
self.head = self.head.next
if self.head is not None:
self.head.previous = None
self.length -= 1
if self.length == 0:
self.tail = None
return item

def is_empty(self):
"""Return True if the queue is empty, False otherwise."""
return self.length == 0

def size(self):
"""Return the number of elements in the queue."""
return self.length

def display(self):
"""Return a list representation of the queue from front to back."""
arr = []
current = self.head
while current:
arr.append(current.item)
current = current.next
return arr


class ArrayQueue:
"""A Queue implementation using a dynamic array (Python list)."""
def __init__(self):
self.items = []

def is_empty(self):
"""Return True if the queue is empty, False otherwise."""
return len(self.items) == 0

def enqueue(self, data):
"""Add an element to the back of the queue."""
self.items.append(data)

def dequeue(self):
"""Remove and return the front element of the queue."""
if self.is_empty():
raise IndexError("dequeue from empty queue")
return self.items.pop(0)

def size(self):
"""Return the number of elements in the queue."""
return len(self.items)

def display(self):
"""Return a list representation of the queue from front to back."""
return list(self.items)


def main():
print("--- Testing ArrayQueue ---")
que = ArrayQueue()
que.enqueue('google')
que.enqueue('youtube')
que.enqueue('udemy')
que.enqueue('udacity')
print("Initial queue:", que.display())
print("Dequeued:", que.dequeue())
print("Dequeued:", que.dequeue())
print("Remaining queue:", que.display())

print("\n--- Testing LinkedListQueue ---")
ll_que = LinkedListQueue()
ll_que.enqueue('google')
ll_que.enqueue('youtube')
ll_que.enqueue('udemy')
ll_que.enqueue('udacity')
print("Initial queue:", ll_que.display())
print("Dequeued:", ll_que.dequeue())
print("Dequeued:", ll_que.dequeue())
print("Remaining queue:", ll_que.display())


if __name__ == "__main__":
main()
33 changes: 17 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
#This is a open source project.
# Python 3
These files are mainly intended to accompany my series of YouTube tutorial videos here,
# Python 3 Examples

This is an open source project. These files are mainly intended to accompany my series of YouTube tutorial videos here:
https://www.youtube.com/user/joejamesusa
and are mainly intended for educational purposes.
You are invited to subscribe to my video channel-Joe James, and to download and use any code in
this Python repository, according to the MIT License.
Feel free to post any comments on my YouTube channel.
I am very happy to see you there on my you tube channel. excited!!!!!!!!!
## Subscribe to my channel for more tutorial videos.

This source code is easy to understand and reliable for self study and you will learn them easily, try to practice more coding by making algorithms yourself and you can become a better Python programmer, and remember "Try to learn something about everything and everything about something".

Thank you for reviewing my repositories and keep practicing.
Joe James.
Fremont, CA.

The examples are mainly intended for educational purposes. You are invited to subscribe to my video channel (Joe James) and to download and use any code in this Python repository according to the MIT License. Feel free to post any comments on my YouTube channel.

I am very happy to see you there on my YouTube channel!

## Subscribe to my channel for more tutorial videos

This source code is easy to understand and reliable for self-study, helping you learn concepts easily. Try to practice more coding by designing algorithms yourself to become a better Python programmer. Remember: "Try to learn something about everything and everything about something."

Thank you for reviewing my repository, and keep practicing!

Joe James
Fremont, CA
Copyright (C) 2015-2021, Joe James

## Happy coding guys!😀
## Happy coding! 💻
Loading