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

Nama : Aan Nur Wahidi

Jawaban Test

1. Given an array of consecutive integers. Create a function that counts the


sum of all elements inside the array within O(1) time.

def con_sum(arrs):
try:
a = arrs[0]
n = len(arrs)
last = arrs[n-1]
return int((a+last)*(n/2))
except IndexError as err:
return "List Empty"

2. Given an array of integers (sorted). Create a function that returns the


index of a specific element within O(log(n)) time.

def bst_search(lst, element):


return bst_search_helper(lst, element, 0, len(lst)-1)

def bst_search_helper(lst, element, left, right):


if left > right:
return "Element Not Found"
mid = (left+right)//2
if lst[mid] == element:
return mid
elif lst[mid] < element:
return bst_search_helper(lst, element, mid + 1, right)
elif lst[mid] > element:
return bst_search_helper(lst, element, left, mid - 1)
3. Given an array of integers (unsorted). Create a function that counts the
number of occurrences of each element in the array.

def count_occurr(lst):
data = {}
for i in lst:
if str(i) in data:
data[str(i)] += 1
else:
data[str(i)] = 1

for i in data:
print(i, str(data[i])+"x")

You might also like