Python Algorithms
Remove Duplicates from a List
def remove_duplicates(nums: list) -> list:
return list(set(nums))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]
Two Sum
The two sum algorithm works by iterating through the array and for each element, finding its complement (i.e., the other number that adds up to the target value). We use a nested loop to iterate through the remaining elements of the array and check if their sum is equal to the target value. If it is, we return the indices of both elements as the result.
def two_sum(arr, target):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] + arr[j] == target:
return [i, j]
return [-1, -1]
print(two_sum([2, 7, 11, 15], 9))
# Output: [0, 1]
Merge Two Sorted Lists
def merge_sorted_lists(list1: list, list2: list) -> list:
merged = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged.append(list1[i])
i += 1
else:
merged.append(list2[j])
j += 1
merged.extend(list1[i:])
merged.extend(list2[j:])
return merged
print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]
Fibonacci Series
The Fibonacci series algorithm works by defining a recursive function that takes an integer argument n. If n is 0 or 1, we return the value of n as the result. Otherwise, we add the values of fibonacci(n-1) and fibonacci(n-2).
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(5)) # 5