Python Coding Questions-1
Python Coding Questions-1
REVERSE A STRING
# Reverse a string using slicing
s = "Python"
print(s[::-1]) # Output: "nohtyP"
PALINDROME CHECKER
@Tajamulkhann
LIST COMPREHENSION CHALLENGE
# Generate squares using list comprehension
squares = [x**2 for x in range(1, 11)]
print(squares) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
FIZZBUZZ IMPLEMENTATION
# Classic FizzBuzz problem
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
@Tajamulkhann
FILTER FUNCTION USAGE
VOWEL COUNTER
ANAGRAM CHECKER
def check_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
print(check_anagram("listen", "silent")) # Output: True
@Tajamulkhann
CHARACTER FREQUENCY IN A STRING
def char_frequency(text):
freq = {}
for char in text.lower():
freq[char] = freq.get(char, 0) + 1
return freq
print(char_frequency("Hello World"))
# Output: {'h':1, 'e':1, 'l':3, 'o':2, ' ':1, 'w':1, 'r':1, 'd':1}
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
print(list(set(list1) & set(list2))) # Output: [3, 4]
REMOVE DUPLICATES
my_list = [1, 2, 3, 4, 2, 5, 3, 6, 3]
from collections import Counter
count = Counter(my_list)
duplicates = {item: freq for item, freq in count.items() if freq > 1} # {2: 2, 3: 3}
@Tajamulkhann
PRINT PYRAMID PATTERN
n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
def second_largest(nums):
nums = list(set(nums)) # Remove duplicates first
nums.sort(reverse=True)
return nums[1] if len(nums) > 1 else None
print(second_largest([10, 20, 40, 30])) # Output: 30
NUMBER REVERSAL
def reverse_number(n):
reversed_num = 0 # Start with 0 as the reversed number
while n > 0: # Repeat until no digits left in n
digit = n % 10 # Get the last digit of n
reversed_num = reversed_num * 10 + digit # Add digit to the reversed number
n = n // 10 # Remove the last digit from n
return reversed_num # Return the reversed number
print(reverse_number(12345)) # Output will be 54321
@Tajamulkhann
Follow for more!
Follow for more!