Python Coding Exercise Algorithms
1. Reverse a String
def reverse_string(s: str) -> str:
return s[::-1]
# Example usage
print(reverse_string("hello")) # Output: "olleh"
2. Find the Largest Number in a List
def find_largest(nums: list) -> int:
return max(nums)
# Example usage
print(find_largest([1, 2, 3, 4, 5])) # Output: 5
3. Check if a Number is a Palindrome
def is_palindrome(n: int) -> bool:
return str(n) == str(n)[::-1]
# Example usage
print(is_palindrome(121)) # Output: True
print(is_palindrome(123)) # Output: False
4. Fibonacci Sequence
def fibonacci(n: int) -> list:
fib_seq = [0, 1]
for i in range(2, n):
fib_seq.append(fib_seq[-1] + fib_seq[-2])
return fib_seq[:n]
# Example usage
print(fibonacci(5)) # Output: [0, 1, 1, 2, 3]
5. Two Sum Problem
def two_sum(nums: list, target: int) -> list:
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
# Example usage
print(two_sum([2, 7, 11, 15], 9)) # Output: [0, 1]
6. Remove Duplicates from a List
def remove_duplicates(nums: list) -> list:
return list(set(nums))
# Example usage
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]
7. Count the Number of Vowels in a String
def count_vowels(s: str) -> int:
vowels = 'aeiouAEIOU'
return sum(1 for char in s if char in vowels)
# Example usage
print(count_vowels("hello world")) # Output: 3
8. 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
# Example usage
print(merge_sorted_lists([1, 3, 5], [2, 4, 6])) # Output: [1, 2, 3, 4, 5, 6]
9. Find the First Non-Repeated Character in a String
def first_non_repeated_char(s: str) -> str:
counts = {}
for char in s:
counts[char] = counts.get(char, 0) + 1
for char in s:
if counts[char] == 1:
return char
return None
# Example usage
print(first_non_repeated_char("swiss")) # Output: "w"
10. Find the Intersection of Two Lists
def list_intersection(list1: list, list2: list) -> list:
return list(set(list1) & set(list2))
# Example usage
print(list_intersection([1, 2, 3, 4], [3, 4, 5, 6])) # Output: [3, 4]