Python Slip 17

5f234c4bc9a04e6e89d7fd99be2121ef

Q.1 Write a python program which reverse given string and displays both original and reversed string. (Don’t use built-in function)

my_str = input("Please enter your own String : ")
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:

        mid = low + (high - low)//2

        if arr[mid] == a:
            return mid

        elif array[mid] < a:
            low = mid + 1

        else:
            high = mid - 1

    return -1

arr = [1, 2, 3, 4, 5, 6, 7]
a = 4

print("The given array is", arr)

print("Element to be found is ", a)

index = binary_search(arr, a, 0, len(arr)-1)

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.

one = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
two = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
both=[]
if 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