python 7-9
python 7-9
PRACTICAL - 7
Aim: Write a program to perform linear search and binary search.
Software Used: IDLE
Theory:
1. Linear Search:
• Definition: It is a simple search algorithm where each element in the list is checked
sequentially until the desired element is found or the list ends.
• Time Complexity: O(n), where n is the number of elements in the list.
• When to use: Suitable for unsorted or small datasets.
2. Binary Search:
• Definition: A more efficient search algorithm that works on sorted lists. It repeatedly
divides the search interval in half and checks the middle element.
• Time Complexity: O(logn), where n is the number of elements in the list.
• When to use: Ideal for sorted datasets.
Source Code:
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Element found, return index
return -1 # Element not found
Output:
2323007
PRACTICAL - 8
Aim: Write a program to perform Insertion sort and bubble sort.
Software Used: IDLE
Theory:
Insertion Sort: This algorithm builds the sorted list one element at a time. It picks elements from
the unsorted portion and inserts them into their correct position in the sorted portion. The
process is repeated until the entire array is sorted. It has a time complexity of O(n²) in the worst
case but performs well on small or nearly sorted data.
Bubble Sort: Bubble Sort repeatedly compares adjacent elements and swaps them if they are in
the wrong order. The largest element "bubbles" to the end with each pass. It has a time
complexity of O(n²) and is inefficient for large datasets.
Source Code:
def insertion_sort(arr):
for i in range(1, len(arr)): # Start from the second element
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]: # Move elements of arr[0..i-1], that are greater than key, to one
position ahead
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key # Place key after the last smaller element
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False # To optimize and stop if no swapping happens
arr[j], arr[j + 1] = arr[j + 1], arr[j] # Swap if elements are in wrong order
swapped = True
2323007
break data1 = [64, 34, 25, 12, 22, 11, 90] data2 = data1.copy()
print("Sorted array using Insertion Sort:", data1)
print("Sorted array using Bubble Sort:", data2)
Output:
2323007
PRACTICAL – 9
Aim: Write a program to use split and join methods in the string and trace a birthday of a
person with dictionary data structure.
Software Used: IDLE
Theory:
1. split() Method:
• Purpose: The split() method is used to divide a string into a list of substrings based on a specified
delimiter (separator).
• Syntax: string.split(separator, maxsplit) o separator: The character or substring used to split the
string (default is whitespace).
o maxsplit: The maximum number of splits to do (optional).
• Example: "12-25-1995".split("-") results in ['12', '25', '1995'].
• Use Case: It is commonly used when processing data in a specific format, such as dates, CSV files,
or logs.
2. join() Method:
• Purpose: The join() method is used to concatenate a list or iterable of strings into a single string,
with a specified separator between each element.
• Syntax: separator.join(iterable) o separator: The string used to join elements of the iterable
(e.g., "-").
o iterable: The sequence of strings to join (e.g., a list or tuple).
• Example: "-".join(['12', '25', '1995']) results in "12-25-1995".
• Use Case: It is helpful for creating a formatted string by joining elements, such as in CSV generation
or constructing structured data.
In the given program:
• The split() method extracts the month, day, and year from a birthdate string.
• The join() method then recombines these parts into a formatted string. These methods help
manipulate strings efficiently and are commonly used in data processing and formatting tasks.
2323007
Source Code:
person_birthday = {
"name": "John Doe",
"birthdate": "12-25-1995", # Date format: MM-DD-YYYY
"city": "New York",
"favorite_color": "Blue"
}
birthdate_parts = person_birthday["birthdate"].split("-") month, day, year
=birthdate_parts # Splitting the date into month, day, and year
formatted_date = "-".join([month, day, year])
print(f"Person's Name: {person_birthday['name']}")
print(f"Birthday: {formatted_date}")
print(f"City: {person_birthday['city']}")
print(f"Favorite Color: {person_birthday['favorite_color']}")
print("\nTrace of Birthday:")
print(f"Month: {month}")
print(f"Day: {day}")
print(f"Year: {year}")
Output: