Why Python?
Python is a powerful language that can be used to do amazing things. But like any skill, it takes practice to become proficient. That’s where exercises come in. Exercises are a great way to learn the syntax and semantics of Python. They also help you develop your problem-solving skills. And the best part is, they can be a lot of fun!
So if you’re serious about learning Python, I encourage you to do plenty of exercises. You’ll be glad you did.
Benefits of Practicing Python Exercises
- Exercises can help you learn at your own pace.
- They can help you focus on the areas where you need the most help.
- They can help you stay motivated and engaged.
- And they can help you have fun while you’re learning!
Here are 10 intermediate Python exercises with examples and code:
1. Write a program to find the greatest common divisor of two numbers.
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(10, 20))
# Output: 10
2. Write a program to find the least common multiple of two numbers.
def lcm(a, b):
return a * b // gcd(a, b)
print(lcm(10, 20))
# Output: 20
3. Write a program to sort a list of numbers in ascending order.
def sort_list(numbers):
for i in range(len(numbers) - 1):
for j in range(i + 1, len(numbers)):
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers
print(sort_list([10, 5, 2, 1, 8, 7, 6]))
# Output: [1, 2, 5, 6, 7, 8, 10]
4. Write a program to find the longest common substring of two strings.
def longest_common_substring(string1, string2):
dp = [[0 for _ in range(len(string2) + 1)] for _ in range(len(string1) + 1)]
for i in range(len(string1) + 1):
for j in range(len(string2) + 1):
if i == 0 or j == 0:
dp[i][j] = 0
elif string1[i - 1] == string2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
print(longest_common_substring("hello", "world"))
# Output: 3
5. Write a program that can generate a random maze.
The maze should be a two-dimensional grid of cells, where each cell can be either open or closed. The program should randomly generate a maze with a given number of rows and columns. The program should also be able to print the maze to the console.
Here is an example of a maze that the program could generate:
This is just one example of a maze that the program could generate. The program should be able to generate mazes of different sizes and shapes.
Solution:
import random
def generate_maze(rows, columns):
maze = [[False for _ in range(columns)] for _ in range(rows)]
for row in range(rows):
for column in range(columns):
if random.random() > 0.5:
maze[row][column] = True
return maze
def print_maze(maze):
for row in maze:
for column in row:
if column:
print(" ", end="")
else:
print("*", end="")
print()
maze = generate_maze(10, 10)
print_maze(maze)
6. Write a program to implement a binary search.
def binary_search(list, target):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
if list[mid] == target:
return mid
elif list[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 5))
# Output: 2
7. Write a program to implement a quicksort algorithm.
def quicksort(list, low, high):
if low < high:
pivot = partition(list, low, high)
quicksort(list, low, pivot - 1)
quicksort(list, pivot + 1, high)
def partition(list, low, high):
pivot = list[high]
i = low - 1
for j in range(low, high):
if list[j] <= pivot:
i += 1
temp = list[i]
list[i] = list[j]
list[j] = temp
temp = list[i + 1]
list[i + 1] = list[high]
list[high] = temp
return i + 1
list = [10, 8, 2, 7, 3, 5, 9, 1, 6, 4]
quicksort(list, 0, len(list) - 1)
print(list)
8. Write a program to generate all possible permutations of a string.
def permutations(string):
if len(string) == 0:
return []
else:
permutations_list = []
for i in range(len(string)):
head = string[i]
tail = string[0:i] + string[i + 1:]
permutations_list += permutations(tail)
permutations_list.append([head] + permutations(tail))
return permutations_list
print(permutations("abc"))# Output: [['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]
9. Write a program to find the minimum spanning tree of a graph.
def minimum_spanning_tree(graph):
edges = []
for u, neighbors in graph.items():
for v, weight in neighbors.items():
edges.append((u, v, weight))
edges.sort(key=lambda edge: edge[2])
mst = []
visited = set()
for u, v, weight in edges:
if u not in visited and v not in visited:
mst.append((u, v, weight))
visited.add(u)
visited.add(v)
return mst
graph = {
"a": {"b": 1, "c": 2},
"b": {"c": 3},
"c": {"a": 4},
}
print(minimum_spanning_tree(graph))
# Output: [('a', 'b', 1), ('b', 'c', 3)]
10. Write a program to implement a greedy algorithm to find the optimal solution for the knapsack problem.
def knapsack(items, capacity):
value = 0
weight = 0
for item in items:
if weight + item.weight <= capacity:
value += item.value
weight += item.weight
else:
break
return value
items = [
Item("a", 10, 5),
Item("b", 20, 10),
Item("c", 30, 15),
]
capacity = 25
print(knapsack(items, capacity))
# Output: 50
I hope you enjoy these exercises!Happy Coding!
2 thoughts on “10 – Unique Intermediate Python Exercises”