0% found this document useful (0 votes)
11 views5 pages

Essential Python Algorithms and Data Structures

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

Essential Python Algorithms and Data Structures

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# 1.

Binary Search Algorithm for Sorted List

def binary_search(arr, target):

low, high = 0, len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

low = mid + 1

else:

high = mid - 1

return -1

# 2. Rotate a Matrix 90 Degrees Clockwise

def rotate_matrix_90(matrix):

return [list(row) for row in zip(*matrix[::-1])]

# 3. Merge Two Sorted Lists into a Single Sorted List

def merge_sorted_lists(list1, list2):

merged_list = []

i=j=0

while i < len(list1) and j < len(list2):

if list1[i] < list2[j]:

merged_list.append(list1[i])

i += 1

else:

merged_list.append(list2[j])

j += 1

merged_list.extend(list1[i:])

merged_list.extend(list2[j:])
return merged_list

# 4. Check if a Given String is an Anagram of Another String

def is_anagram(str1, str2):

return sorted(str1) == sorted(str2)

# 5. Implement a Caching Mechanism using functools.lru_cache

@lru_cache(maxsize=None)

def fibonacci(n):

if n < 2:

return n

return fibonacci(n - 1) + fibonacci(n - 2)

# 6. Fetch Weather Data from an API and Display it in a User-Friendly Format

def fetch_weather(api_key, city):

base_url = "h p://[Link]/data/2.5/weather"

params = {"q": city, "appid": api_key, "units": "metric"}

response = [Link](base_url, params=params)

if response.status_code == 200:

data = [Link]()

return {

"City": data["name"],

"Temperature": f"{data['main']['temp']} °C",

"Weather": data["weather"][0]["descrip on"].capitalize()

else:

return {"Error": "Unable to fetch weather data."}

# 7. Shape Class with Subclasses Circle and Square Implemen ng Their Area Methods

class Shape:

def area(self):
raise NotImplementedError("Subclass must implement area method")

class Circle(Shape):

def __init__(self, radius):

[Link] = radius

def area(self):

return [Link] * [Link] ** 2

class Square(Shape):

def __init__(self, side):

[Link] = side

def area(self):

return [Link] ** 2

# 8. Singly Linked List Class

class Node:

def __init__(self, value):

[Link] = value

[Link] = None

class SinglyLinkedList:

def __init__(self):

[Link] = None

def append(self, value):

new_node = Node(value)

if not [Link]:

[Link] = new_node

return
current = [Link]

while [Link]:

current = [Link]

[Link] = new_node

def display(self):

current = [Link]

while current:

print([Link], end=" -> ")

current = [Link]

print("None")

# Example usage:

if __name__ == "__main__":

# Binary search

print(binary_search([1, 2, 3, 4, 5], 3))

# Rotate matrix

matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

print(rotate_matrix_90(matrix))

# Merge sorted lists

print(merge_sorted_lists([1, 3, 5], [2, 4, 6]))

# Check anagram

print(is_anagram("listen", "silent"))
# Fibonacci with caching

print(fibonacci(10))

# Fetch weather data

# print(fetch_weather("your_api_key", "London"))

# Shape areas

circle = Circle(5)

square = Square(4)

print([Link]())

print([Link]())

# Singly linked list

linked_list = SinglyLinkedList()

linked_list.append(1)

linked_list.append(2)

linked_list.append(3)

linked_list.display()

You might also like