Appearance
question:Write a Python function to check if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). For example, "Madam, in Eden, I'm Adam" is a palindrome. The function should return True if the string is a palindrome and False otherwise. Use a stack to implement this function.
answer:def is_palindrome(s): Checks if a given string is a palindrome, ignoring spaces, punctuation, and capitalization. Uses a stack to check the palindrome property. Args: s (str): The string to be checked. Returns: bool: True if the string is a palindrome, False otherwise. # Filter out non-alphanumeric characters and convert to lowercase filtered_chars = [char.lower() for char in s if char.isalnum()] # Initialize stack stack = [] # Push all characters onto the stack for char in filtered_chars: stack.append(char) # Check if the string is a palindrome by popping characters from stack for char in filtered_chars: if char != stack.pop(): return False return True
question:Write a Python function that takes a list of integers and returns the sum of the squares of the even numbers in the list. Use a lambda function to check if a number is even.
answer:def sum_of_squares_of_evens(lst): Returns the sum of the squares of the even numbers in the list. is_even = lambda x: x % 2 == 0 return sum(x ** 2 for x in lst if is_even(x))
question:I need to write a function in Python that converts a binary number, given as a string, to its decimal equivalent. How can I do this?
answer:def binary_to_decimal(binary_str): Converts a binary number, given as a string, to its decimal equivalent. Parameters: binary_str (str): A string representing a binary number (e.g., '1101'). Returns: int: The decimal equivalent of the binary number. return int(binary_str, 2)
question:Write a Python function to find the next greater element for each element in a given list. The next greater element for an element is the first greater element on its right side in the list. If no greater element is found, the next greater element is considered as -1. For example, given the list [2, 7, 3, 5, 4, 6, 8], the next greater elements are [7, 8, 5, 6, 6, 8, -1]. implement the function using a stack.
answer:def next_greater_element(lst): Finds the next greater element for each element in the list. Args: lst (List[int]): The list of integers to find the next greater element for. Returns: List[int]: A list of integers where each element is the next greater element for the corresponding input element. result = [-1] * len(lst) stack = [] for i in range(len(lst)): while stack and lst[stack[-1]] < lst[i]: result[stack.pop()] = lst[i] stack.append(i) return result