Q.1 Write a python program which reverse given string and displays both original and reversed string. (Don’t use built-in function)
= input("Please enter your own String : ")
my_str str = ''
for i in my_str:
str = i + str
print("\nThe Original String is: ", my_str)
print("The Reversed String is: ", str)
OUTPUT
Please enter your own String : Rahul Sonawane
The Original String is: Rahul Sonawane
The Reversed String is: enawanoS luhaR
Q2. Write a python program to implement binary search to search the given element using function.
def binary_search(arr, a, low, high):
while low <= high:
= low + (high - low)//2
mid
if arr[mid] == a:
return mid
elif array[mid] < a:
= mid + 1
low
else:
= mid - 1
high
return -1
= [1, 2, 3, 4, 5, 6, 7]
arr = 4
a
print("The given array is", arr)
print("Element to be found is ", a)
= binary_search(arr, a, 0, len(arr)-1)
index
if index != -1:
print("The Index of the element is " + str(index))
else:
print("Element Not found")
OUTPUT
The given array is [1, 2, 3, 4, 5, 6, 7]
Element to be found is 4
The Index of the element is 3
Q2. Write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists of different sizes.
= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
one = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
two =[]
bothif len(one) < len(two):
for i in one:
if i in two and i not in both:
both.append(i) if len(one) > len(two):
for i in two:
if i in one and i not in both:
both.append(i)print(both)
OUTPUT
[1, 2, 3, 5, 8, 13]
0 Comments:
Post a Comment