This is the program that I wrote:
count_occur()callsfirst_occur()to get the first occurrence of an element.- Then
count_occur()callslast_occur()to get the last occurrence - Then the index of the first and last occurrence is subtracted to get the number of occurrences.
# calculates the first occurrence of the element
def first_occur(lists, k, low, high):
mid = (low+high)//2
if low > high:
return -1
# condition to calculate the first occurrence
if lists[mid]==k:
if mid==0 or lists[mid-1]!=lists[mid]:
return mid
else:
return first_occur(lists,k,low,mid-1)
elif lists[mid]<k:
first_occur(lists,k,mid+1,high)
else:
first_occur(lists,k,low,mid-1)
# calculates the last occurrence of the element
def last_occur(lists,k,low,high):
mid = (low + high)//2
if low > high:
return -1
#condition to check the last occurrence
if lists[mid] == k:
if mid == len(lists)-1 or lists[mid+1] != lists[mid]:
return mid
else:
return first_occur(lists,k,mid+1,high)
elif lists[mid]<k:
first_occur(lists,k,mid+1,high)
else:
first_occur(lists,k,low,mid-1)
# called via the input
def count_occur(lists,k):
l = len(lists)
fo = first_occur(lists,k,0,l)
print(fo)
lo = last_occur(lists,k,0,l)
print(lo)
if fo == -1:
print('Not found')
else:
# checks for the number of occurrences
print("Found",(fo-lo+1),"times.")
# getting input via the user of the list.
a = list(map(int, input().split()))
print(a)
k = int(input("Enter the number, the occurences of which to be found."))
count_occur(a, k)
This is the output I am getting. It should have consisted of the number of times the element occurs in the list. But that didn't happen:
12 34 56
[12, 34, 56]
Enter the number, the occurrences of which to be found.12
None
None
Traceback (most recent call last):
File "/Users/somilsharma/Desktop/DSA/14.py", line 79, in <module>
count_occur(a,k)
File "/Users/somilsharma/Desktop/DSA/14.py", line 70, in count_occur
print("Found",(fo-lo+1),"times.")
~~^~~
TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'