Skip to content

Completed all Data Structure Exercises #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
105 changes: 105 additions & 0 deletions Algorithms/1_BinarySearch/1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
# ### Binary Search Exercise
# 1. When I try to find number 5 in below list using binary search, it doesn't work and returns me -1 index. Why is that?

# ```numbers = [1,4,6,9,10,5,7]```

# This is because the array is not sorted in order from lowest to highest.
# Once it splits the first time, it starts looking in the [1,4,6] range and doesn't find 5

# 1. Find index of all the occurances of a number from sorted list

# ```
# numbers = [1,4,6,9,11,15,15,15,17,21,34,34,56]
# number_to_find = 15
# ```
# This should return 5,6,7 as indices containing number 15 in the array

from util import time_it

@time_it
def linear_search(numbers_list, number_to_find):
for index, element in enumerate(numbers_list):
if element == number_to_find:
return index
return -1

@time_it
def binary_search(numbers_list, number_to_find):
left_index = 0
right_index = len(numbers_list) - 1
mid_index = 0

while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = numbers_list[mid_index]

if mid_number == number_to_find:
return mid_index

if mid_number < number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1

return -1

def binary_search_recursive(numbers_list, number_to_find, left_index, right_index):
if right_index < left_index:
return -1

mid_index = (left_index + right_index) // 2
if mid_index >= len(numbers_list) or mid_index < 0:
return -1

mid_number = numbers_list[mid_index]

if mid_number == number_to_find:
return mid_index

if mid_number < number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1

return binary_search_recursive(numbers_list, number_to_find, left_index, right_index)

#this should run the binary search, find the index, and then recursively run the search on both the right and left side
def binary_search_multiple(numbers_list, number_to_find):

index = binary_search(numbers_list,number_to_find)
result_indices = [index]

# find all indices on the left
i = index - 1
while i>=0:
if numbers_list[i] == numbers_list[index]:
result_indices.append(i)
else:
break
i = i-1

# find all indices on the right
i = index + 1
while i<len(numbers_list):
if numbers_list[i] == numbers_list[index]:
result_indices.append(i)
else:
break
i = i+1

return sorted(result_indices)

numbers_list = [12, 15, 17, 19, 21, 21, 21, 21, 24, 45, 67]
number_to_find = 21

index = binary_search_multiple(numbers_list, number_to_find)
print(f"Number found at index {index} using binary search")

numbers = [1,4,6,9,11,15,15,15,15,17,21,34,34,56]
number_to_find = 15

index = binary_search_multiple(numbers, number_to_find)
print(f"Number found at index {index} using binary search")

#Lesson: I was approaching it wrong. If something isn't working, scratch the approach.
#Lesson #2: Try the simplest solution first. Although in this case it's a bit ugly since you're just doing a linear search after your binary search
Binary file not shown.
14 changes: 14 additions & 0 deletions Algorithms/1_BinarySearch/binary_search_exercise.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
### Binary Search Exercise
1. When I try to find number 5 in below list using binary search, it doesn't work and returns me -1 index. Why is that?

```numbers = [1,4,6,9,10,5,7]```

1. Find index of all the occurances of a number from sorted list

```
numbers = [1,4,6,9,11,15,15,15,17,21,34,34,56]
number_to_find = 15
```
This should return 5,6,7 as indices containing number 15 in the array

[Solution](https://github.com/codebasics/data-structures-algorithms-python/blob/master/algorithms/1_BinarySearch/binary_search_exercise_solution.py)
55 changes: 55 additions & 0 deletions Algorithms/1_BinarySearch/binarysearch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from util import time_it

@time_it
def linear_search(numbers_list, number_to_find):
for index, element in enumerate(numbers_list):
if element == number_to_find:
return index
return -1

@time_it
def binary_search(numbers_list, number_to_find):
left_index = 0
right_index = len(numbers_list) - 1
mid_index = 0

while left_index <= right_index:
mid_index = (left_index + right_index) // 2
mid_number = numbers_list[mid_index]

if mid_number == number_to_find:
return mid_index

if mid_number < number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1

return -1

def binary_search_recursive(numbers_list, number_to_find, left_index, right_index):
if right_index < left_index:
return -1

mid_index = (left_index + right_index) // 2
if mid_index >= len(numbers_list) or mid_index < 0:
return -1

mid_number = numbers_list[mid_index]

if mid_number == number_to_find:
return mid_index

if mid_number < number_to_find:
left_index = mid_index + 1
else:
right_index = mid_index - 1

return binary_search_recursive(numbers_list, number_to_find, left_index, right_index)

numbers_list = [12, 15, 17, 19, 21, 24, 45, 67]
number_to_find = 21

index = binary_search_recursive(numbers_list, number_to_find, 0, len(numbers_list))
print(f"Number found at index {index} using binary search")

9 changes: 9 additions & 0 deletions Algorithms/1_BinarySearch/util.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import time
def time_it(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
print(func.__name__ +" took " + str((end-start)*1000) + " mil sec")
return result
return wrapper
84 changes: 84 additions & 0 deletions Data_Structures/10_Graph/graph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
class Graph:
def __init__(self, edges):
self.edges = edges
self.graph_dict = {}
for start, end in edges:
if start in self.graph_dict:
self.graph_dict[start].append(end)
else:
self.graph_dict[start] = [end]
print("Graph Dict:", self.graph_dict)

def get_paths(self, start, end, path=[]):
path = path + [start]

if start == end:
return [path]

if start not in self.graph_dict:
return []

paths = []
for node in self.graph_dict[start]:
if node not in path:
new_paths = self.get_paths(node, end, path)
for p in new_paths:
paths.append(p)

return paths

def get_shortest_path(self, start, end, path=[]):
path = path + [start]

if start == end:
return path

if start not in self.graph_dict:
return None

shortest_path = None
for node in self.graph_dict[start]:
if node not in path:
sp = self.get_shortest_path(node, end, path)
if sp:
if shortest_path is None or len(sp) < len(shortest_path):
shortest_path = sp

return shortest_path

if __name__ == '__main__':

routes = [
("Mumbai","Pune"),
("Mumbai", "Surat"),
("Surat", "Bangaluru"),
("Pune","Hyderabad"),
("Pune","Mysuru"),
("Hyderabad","Bangaluru"),
("Hyderabad", "Chennai"),
("Mysuru", "Bangaluru"),
("Chennai", "Bangaluru")
]

routes = [
("Mumbai", "Paris"),
("Mumbai", "Dubai"),
("Paris", "Dubai"),
("Paris", "New York"),
("Dubai", "New York"),
("New York", "Toronto"),
]

route_graph = Graph(routes)

start = "Mumbai"
end = "New York"

print(f"All paths between: {start} and {end}: ",route_graph.get_paths(start,end))
print(f"Shortest path between {start} and {end}: ", route_graph.get_shortest_path(start,end))

start = "Dubai"
end = "New York"

print(f"All paths between: {start} and {end}: ",route_graph.get_paths(start,end))
print(f"Shortest path between {start} and {end}: ", route_graph.get_shortest_path(start,end))
60 changes: 60 additions & 0 deletions Data_Structures/2_Arrays/2-1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# # Exercise: Array DataStructure

# 1. Let us say your expense for every month are listed below,
# 1. January - 2200
# 2. February - 2350
# 3. March - 2600
# 4. April - 2130
# 5. May - 2190

# Create a list to store these monthly expenses and using that find out,

# 1. In Feb, how many dollars you spent extra compare to January?
# 2. Find out your total expense in first quarter (first three months) of the year.
# 3. Find out if you spent exactly 2000 dollars in any month
# 4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list
# 5. You returned an item that you bought in a month of April and
# got a refund of 200$. Make a correction to your monthly expense list
# based on this

expenses = [2200,2350,2600,2130,2190]

# 1. In Feb, how many dollars you spent extra compare to January?

extraSpend = expenses[1] - expenses[0]

print(f"In February, you spent ${extraSpend} more than in January")

# 2. Find out your total expense in first quarter (first three months) of the year.

q1_expenses = sum(expenses[0:3])

print(f"In Q1, you spent ${q1_expenses}")

# 3. Find out if you spent exactly 2000 dollars in any month

print("Did I spent 2000$ in any month? ", 2000 in expenses) # False

did_i_spend = False

for e in expenses:
if e == 2000:
did_i_spend = True

if did_i_spend == True:
print('You did spend exactly 2000 in a month')
else:
print('You did not spend exactly 2000 in a month')

#4. June month just finished and your expense is 1980 dollar. Add this item to our monthly expense list

expenses.append(1980)

print(expenses)

# 5. You returned an item that you bought in a month of April and
# # got a refund of 200$. Make a correction to your monthly expense list
# # based on this

expenses[3] = expenses[3] - 200
print(expenses)
47 changes: 47 additions & 0 deletions Data_Structures/2_Arrays/2-2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 2. You have a list of your favourite marvel super heros.
# ```
# heros=['spider man','thor','hulk','iron man','captain america']
# ```

# Using this find out,

# 1. Length of the list
# 2. Add 'black panther' at the end of this list
# 3. You realize that you need to add 'black panther' after 'hulk',
# so remove it from the list first and then add it after 'hulk'
# 4. Now you don't like thor and hulk because they get angry easily :)
# So you want to remove thor and hulk from list and replace them with doctor strange (because he is cool).
# Do that with one line of code.
# 5. Sort the heros list in alphabetical order (Hint. Use dir() functions to list down all functions available in list)


heros=['spider man','thor','hulk','iron man','captain america']

# 1. Length of the list
print("length of heros list:",len(heros))

# 2. Add 'black panther' at the end of this list

heros.append('black panther')
print(heros)

# 3. You realize that you need to add 'black panther' after 'hulk',
# so remove it from the list first and then add it after 'hulk'

heros.remove('black panther')
heros.insert(3,'black panther')
print(heros)

# 4. Now you don't like thor and hulk because they get angry easily :)
# So you want to remove thor and hulk from list and replace them with doctor strange (because he is cool).
# Do that with one line of code.

heros[1:3] = ['doctor stranger']
print(heros)

# 5. Sort the heros list in alphabetical order (Hint. Use dir() functions to list down all functions available in list)

heros.sort()
print(heros)


13 changes: 13 additions & 0 deletions Data_Structures/2_Arrays/2-3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# 3. Create a list of all odd numbers between 1 and a max number.
# Max number is something you need to take from a user using input() function

odd_numbers_list = []

max_number = int(input('What is the max number? '))

for i in range(0,max_number+1):
if i%2 != 0:
odd_numbers_list.append(i)

print(odd_numbers_list)

Loading