python-typehint-playground/string_operations.py

63 lines
1.5 KiB
Python
Raw Normal View History

2024-10-18 10:09:24 +02:00
"""Playground module for practicing adding type hints to
Python code.
You may assume that the functions in this module operate on
strings. Your type hints should be as generic as possible.
Disclaimer: This module was generated by https://claude.ai/.
"""
def reverse_string(s):
return s[::-1]
def count_vowels(s):
vowels = 'aeiouAEIOU'
return sum(1 for char in s if char in vowels)
def is_palindrome(s):
s = ''.join(char.lower() for char in s if char.isalnum())
return s == s[::-1]
def find_longest_word(sentence):
words = sentence.split()
return max(words, key=len) if words else ''
def remove_duplicates(lst):
return list(dict.fromkeys(lst))
def merge_sorted_lists(list1, list2):
result = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] <= list2[j]:
result.append(list1[i])
i += 1
else:
result.append(list2[j])
j += 1
result.extend(list1[i:])
result.extend(list2[j:])
return result
def flatten_list(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_list(item))
else:
flat_list.append(item)
return flat_list
def calculate_average(numbers):
return sum(numbers) / len(numbers) if numbers else 0
def find_common_elements(list1, list2):
return list(set(list1) & set(list2))
def rotate_list(lst, k):
if not lst:
return lst
k = k % len(lst)
return lst[-k:] + lst[:-k]