Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Part B Programs

1. Linear Search

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return i
return -1

my_list = [2, 4, 6, 8, 10, 12]

target_element = 8

result = linear_search(my_list, target_element)


if result != -1:
print(f"Element {target_element} found at index {result}")
else:
print(f"Element {target_element} not found in the list")

2. Binary Search

def binary_search(arr, target):


left, right = 0, len(arr) - 1
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
my_list = [2, 4, 6, 8, 10, 12]
target_element = 8

result = binary_search(my_list, target_element)


if result != -1:
print(f"Element {target_element} found at index {result}")
else:
print(f"Element {target_element} not found in the list")

3. Fibonacci Sequence

def fibonacci(n):
fib = [0, 1]
while len(fib) < n:
fib.append(fib[-1] + fib[-2])
return fib
n = 10
result = fibonacci(n)
print(result)
4. List creation and 5 list operations

my_list = [1, 2, 3, 4, 5]

my_list.append(6)

my_list.remove(3)

element_exists = 4 in my_list

list_length = len(my_list)

for item in my_list:


print(item)

print("Updated List:", my_list)


print("Element 4 exists:", element_exists)
print("Length of the list:", list_length)

5. Dictionary creation and 5 dictionary operations

# Dictionary creation
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Adding a key-value pair


my_dict['occupation'] = 'Engineer'

# Removing a key-value pair


my_dict.pop('city', None) # Remove 'city' key if it exists

# Checking if a key exists


key_exists = 'age' in my_dict

# Getting the value associated with a key


value = my_dict.get('name', 'Name not found')

# Iterating through the dictionary


for key, value in my_dict.items():
print(f'{key}: {value}')

print("Updated Dictionary:", my_dict)


print("Key 'age' exists:", key_exists)
print("Value for key 'name':", value)

You might also like