Coding solutions
Here are some coding solutions to common problems:
1. Reverse a string
def reverse_string(s):
return s[::-1]
2. Check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
3. Find the maximum value in a list
def max_value(lst):
return max(lst)
4. Check if a string is a palindrome
def is_palindrome(s):
return s == s[::-1]
5. Calculate the factorial of a number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
6. Find the sum of all elements in a list
def sum_list(lst):
return sum(lst)
7. Check if a number is even or odd
def is_even(n):
return n % 2 == 0
8. Find the first duplicate in a list
def first_duplicate(lst):
seen = set()
for item in lst:
if item in seen:
return item
seen.add(item)
return None
9. Check if a string contains a specific substring
def contains_substring(s, sub):
return sub in s
10. Find the longest common prefix in a list of strings
def longest_common_prefix(lst):
if not lst:
return ""
prefix = lst[0]
for s in lst[1:]:
while not s.startswith(prefix):
prefix = prefix[:-1]
return prefix
11. Check if a number is a power of 2
def is_power_of_two(n):
return n > 0 and (n & (n - 1)) == 0
12. Find the median of a list
def median(lst):
lst.sort()
n = len(lst)
if n % 2 == 1:
return lst[n//2]
else:
return (lst[n//2 - 1] + lst[n//2]) / 2
13. Check if a string is a valid email address
import re
def is_valid_email(s):
pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
return re.match(pattern, s) is not None
14. Find the first missing positive integer in a list
def first_missing_positive_integer(lst):
lst = set(lst)
i = 1
while i in lst:
i += 1
return i
15. Check if a number is a perfect square
def is_perfect_square(n):
return int(n ** 0.5) ** 2 == n
These are just a few examples of coding solutions to common problems. There are many more out there, and you can always find more by searching online or practicing coding challenges.