Practice
- Find pairs in an integer array whose sum is equal to 10 (bonus: do it in linear time)
- Find the most frequent integer in an array
- Find the only element in an array that only occurs once
Find pairs in an integer array whose sum is equal to 10 (bonus: do it in linear time)
There are many variations to this, such as whether or not repeats are allowed, negative numbers being a possibility, etc.
def solution1(test, desired_result):
solution_set = []
for number in test:
needed = desired_result - number
if needed in test:
solution_set.append((number, needed))
return solution_set
#test = [1,2,4,3,1,3,1,4,5,15,5,2,3,5,4] # [(5, 5), (5, 5), (5, 5)]
test = [1, 9, 4] # [(1, 9), (9, 1)]
print(solution1(test, 10))
Find the most frequent integer in an array
test1 = [1, 3, 2, 1, 4, 1] # Expected output: 1
test2 = [10, 20, 10, 20, 30, 20, 20] # Expected output: 20
def solution(test):
counter = {}
for number in test:
if str(number) in counter:
counter[str(number)] += 1
else:
counter[str(number)] = 1
return max(counter, key=counter.get)
print(solution(test1))
print(solution(test2))
Find the only element in an array that only occurs once
def solution(test):
count = {}
for number in test:
if str(number) not in count:
count[str(number)] = 1
else:
count[str(number)] += 1
return min(count, key=count.get)
test1 = [12, 1, 12, 3, 12, 1, 1, 2, 3, 3] # 2
test2 = [10, 20, 10, 30, 10, 30, 30] # 20
print(solution(test2))
programming
]