1️⃣ Reverse a String
Program:
def reverse_string(s):
return s[::-1]
# Example usage
print(reverse_string("hello")) # Output: "olleh"
Explanation:
s[::-1]
is slicing with a step of -1
which reverses the string.
2️⃣ Check if a Number is Prime
Program:
no = int(input("Enter a number: "))
if no < 2:
print("Not Prime")
else:
div = 2
while div < no:
if no % div == 0:
print("Not Prime")
break
div += 1
else:
print("Prime")
Explanation:
A number is prime if it is only divisible by 1 and itself.
We check if number is divisible by 2 and if remainder is 0 then it is not prime number.
3️⃣ Find the Factorial of a Number
Program:
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
# Example usage
print(factorial(5)) # Output: 120
Explanation:
`Uses recursion: factorial(n) = n * factorial(n-1), base case factorial(1) = 1.`
4️⃣ Check if a String is a Palindrome
Program:
def is_palindrome(s):
return s == s[::-1]
# Example usage
print(is_palindrome("madam")) # Output: True
print(is_palindrome("hello")) # Output: False
Explanation:
Compares the string with its reverse to determine if it is a palindrome.
5️⃣ Fibonacci Series using Recursion
Program:
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
Example usage
print([fibonacci(i) for i in range(6)]) # Output: [0, 1, 1, 2, 3, 5]
Explanation:
Recursively calculates the Fibonacci sequence.
6️⃣ Find the Largest Element in a List
Program:
def find_largest(lst):
return max(lst)
# Example usage
print(find_largest([3, 5, 2, 9, 1])) # Output: 9
Explanation:
Uses Python’s built-in `max()` function.
7️⃣ Swap Two Variables Without a Temporary Variable
Program:
a, b = 5, 10
a, b = b, a
print(a, b) # Output: 10, 5
Explanation:
Swaps values using tuple unpacking.
8️⃣ Count the Number of Vowels in a String
Program:
def count_vowels(s):
return sum(1 for char in s.lower() if char in "aeiou")
# Example usage
print(count_vowels("Hello World")) # Output: 3
Explanation:
Uses list comprehension and `sum()` to count vowels.
9️⃣ Remove Duplicates from a List
Program:
def remove_duplicates(lst):
return list(set(lst))
# Example usage
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5])) # Output: [1, 2, 3, 4, 5]
Explanation:
Converts list to a set to remove duplicates, then back to a list.
🔟 Check if Two Strings are Anagrams
Program:
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
# Example usage
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False
Explanation:
Anagrams have the same letters in different orders, so sorting both strings should yield the same result.