Python Coding Interview Questions (Beginner to Advanced)
#Find Squares in Array
nums = [1, 2, 3]
squared = [n ** 2 for n in nums]
print(squared)
—------------------Write a function that takes a string and returns it reversed.
def FirstReverse(s: str) -> str:
return s[::-1] # Reverses the string using slicing, slice syntax is: s[start:stop:step]
print(FirstReverse("hello")) # Output: "olleh"
—-------------
# Get input from the user
user_string = input("Enter a string to reverse: ").strip() #.strip() removes any leading/trailing whitespace
# Check if input is empty
if not user_string:
print("Error: You entered an empty string. Please try again.")
else:
# Reverse the string using slicing
reversed_string = user_string[::-1]
print("The reversed string is:", reversed_string)
—---------------- Find the Second Largest Number
def SecondLargest(nums: list[int]) -> int:
nums = list(set(nums)) # remove duplicates
nums.sort()
return nums[-2] if len(nums) >= 2 else None
# Example
print(SecondLargest([10, 20, 4, 45, 99])) # Output: 45
—----------------------Balanced Parentheses
def BalancedParentheses(s: str) -> bool:
stack = []
for char in s:
if char == '(':
stack.append('(')
elif char == ')':
if not stack:
return False
stack.pop()
return not stack
# Example
print(BalancedParentheses("(())")) # Output: True
print(BalancedParentheses("(()")) # Output: False
—-----------------------------------
def reverse_input_string():
while True:
user_string = input("Enter a string to reverse: ").strip()
if not user_string:
print("Error: You entered an empty string. Please try again.")
else:
reversed_string = user_string[::-1]
print("The reversed string is:", reversed_string)
return reversed_string # Optional, useful if you want to use it later
# Call the function
reverse_input_string()
—---------------------------------
Comments
Post a Comment