Project
Project
Pathfinder
🎯 Project Summary:
A Python program that:
✅ Features Implemented:
Feature Concept Used
Menu system + input Loops, Functions
City data management Lists, Sets, Arrays
Saving/Loading data File Handling
City population stats Dataset Handling (pandas)
Pathfinding BFS, DFS, A*, Hill Climbing
Searching cities Binary Search
Robust input Exception Handling
🛠️Folder Structure:
project/
│
├── city_data.csv
├── main.py
def save_graph(graph):
with open("graph.txt", "w") as f:
f.write(str(graph))
while open_list:
f, g, node = heapq.heappop(open_list)
if node == goal:
path = []
while node:
path.append(node)
node = came_from.get(node)
return path[::-1]
if node in visited:
continue
visited.add(node)
def score(city):
return len(city_graph.get(city, []))
while True:
print("\n==== Smart City System ====")
print("1. Show City List")
print("2. Search City (Binary Search)")
print("3. Analyze Populations")
print("4. Traverse (BFS/DFS)")
print("5. Hill Climb Best City (by connections)")
print("6. A* Shortest Route")
print("7. Add City Connection")
print("8. Exit")
try:
choice = int(input("Enter choice: "))
if choice == 1:
print("Cities:", list(city_graph.keys()))
elif choice == 2:
target = input("Enter city to search: ")
sorted_cities = sorted(city_graph.keys())
index = binary_search(sorted_cities, target)
if index != -1:
print(f"{target} found at position {index}")
else:
print(f"{target} not found.")
elif choice == 3:
print("\nCity Populations:")
print(city_df[['City', 'Population']])
print("Average Population:", city_df['Population'].mean())
elif choice == 4:
algo = input("Choose algorithm (BFS/DFS): ").strip().upper()
start = input("Enter starting city: ")
if algo == "BFS":
bfs(city_graph, start)
elif algo == "DFS":
dfs(city_graph, start)
print("END")
elif choice == 5:
start = input("Enter starting city: ")
result = hill_climbing(start, get_neighbors, score)
print("Hill Climbing stopped at:", result)
elif choice == 6:
start = input("From city: ")
goal = input("To city: ")
heuristic = {city: 1 for city in city_graph} # Dummy heuristic
path = a_star(city_graph, start, goal, heuristic)
print("Shortest Path:", " → ".join(path) if path else "No path
found")
elif choice == 7:
a = input("From city: ")
b = input("To city: ")
city_graph.setdefault(a, []).append(b)
city_graph.setdefault(b, []).append(a)
save_graph(city_graph)
print("Connection added.")
elif choice == 8:
print("Exiting...")
break
else:
print("Invalid option.")
except Exception as e:
print("Error:", e)
🧠 Concepts in Action:
Concept Where it's used
Lists Storing city names
Sets In BFS/DFS visited tracking
Loops Menu system and traversals
Arrays (You can add array instead of list for efficiency)
Functions All modular blocks
BFS / DFS Traverse city routes
Binary Search Efficient city search
Hill Climbing Select city with most connections
A* Route-finding
File Handling Graph saving and loading
Dataset Handling Analyzing populations from CSV
Exception Handling Safe inputs and file reading
✅ SETS IN PYTHON - LINE BY LINE EXPLANATION
my_set = {1, 2, 3} # Set declaration: unordered, unique
elements
print(my_set) # Print the set
# Set operations
set_a = {1, 2, 3}
set_b = {3, 4, 5}
# Set comprehension
squares = {x**2 for x in range(5)} # Create a set of squares from 0 to
4
print(squares) # Output: {0, 1, 4, 9, 16}
✅ LISTS IN PYTHON - LINE BY LINE EXPLANATION
my_list=[1,2,3]#list declaration
my_list.append(4)#Add to list
print(my_list)#print list
nest_list=[[my_list],[1,2,3]]#nested list
print(nest_list)#print nested list
print(my_list[-4])#prints the first in list
my_list.insert(3,5)#inserts in the middle of list
print(my_list)#print new list
my_list.extend([6,7])
print(my_list)
my_list.pop(1)#removes the first occurence
print(my_list)#print list after pop
my_list.remove(1)
print(my_list)#print list after remove
my_list.clear()#clears or empties list
print(my_list)#prints cleared list
new_list=[10,20,30]
if 30 in new_list:
print("found!")
sliced_new_list=new_list[0:1]#slicing list
print(sliced_new_list)#print sliced list
for i in range(len(new_list)):#for loop
print(new_list[i])
for i in new_list:
print(30)
unsorted_list=[10,50,72,41,13,9,208] #unsorted list
print(unsorted_list)
unsorted_list.sort()#sort list
print(unsorted_list)
unsorted_list.reverse()#reverse list
print(unsorted_list)
copy=unsorted_list.copy()#copy list
print(copy)
sum_list_copy=sum(copy)#sum the copy list
print(sum_list_copy)#print the sum
print(len(copy))#check list length
print(min(copy))#check list minimum
print(max(copy))#check list maximum
✅ LOOPS IN PYTHON - LINE BY LINE EXPLANATION
numbers = [10, 20, 30, 40, 50] # Sample list
arr = array('i', [10, 20, 30, 40]) # Create an integer array using 'i'
print(arr) # Output: array('i', [10, 20, 30, 40])
📄 Let's assume a CSV file called students.csv with the following content:
Name,Age,Score
Alice,20,85
Bob,22,90
Cathy,19,78
David,21,88
while open_list:
f, g, node = heapq.heappop(open_list)
if node == goal:
path = []
while node:
path.append(node)
node = came_from.get(node)
return path[::-1]
if node in visited:
continue
visited.add(node)
return None
def score_func(node):
return len(graph.get(node, [])) # You can customize scoring logic