Appearance
question:Write a Python function that extracts URLs from a given text using regular expressions. The function should be able to handle URLs with different protocols (http, https, ftp), subdomains, and domain extensions. The function should return a list of all URLs found in the text.
answer:import re from typing import List def extract_urls(text: str) -> List[str]: Extracts URLs from a given text using regular expressions. Handles URLs with different protocols (http, https, ftp), subdomains, and domain extensions. Args: text (str): The input text containing URLs. Returns: List[str]: A list of extracted URLs. url_pattern = re.compile(r'b(?:http|https|ftp)://S+b') return url_pattern.findall(text)
question:Write a Python function that takes a string as input and checks if it's an anagram of a palindrome. The function should return `True` if the string is an anagram of a palindrome, and `False` otherwise.
answer:def is_anagram_of_palindrome(s): Checks if the input string is an anagram of a palindrome. A string is an anagram of a palindrome if the number of characters that appear an odd number of times is at most one. from collections import Counter # Count the occurrences of each character count = Counter(s) # Count the number of characters with an odd occurrence odd_count = sum(1 for x in count.values() if x % 2 != 0) # For a string to be an anagram of a palindrome, # it should have at most one odd count character. return odd_count <= 1
question:Write a Python function to calculate the sum of all unique pair sums of a given list of integers. A unique pair sum is defined as the sum of any two distinct elements from the list.
answer:def unique_pair_sums(nums): Given a list of integers, returns the sum of all unique pair sums. Unique pair sum is defined as the sum of any two distinct elements from the list. unique_pairs_sum = 0 n = len(nums) for i in range(n): for j in range(i + 1, n): unique_pairs_sum += nums[i] + nums[j] return unique_pairs_sum
question:How can a Pig Latin translator be implemented using Python?
answer:def pig_latin_translator(word): Translates an English word to Pig Latin. Rules for Pig Latin: - If a word begins with a consonant or consonant cluster, move it to the end of the word and add "ay". Example: "hello" -> "ellohay", "smile" -> "ilesmay" - If a word begins with a vowel, simply add "yay" to the end of the word. Example: "apple" -> "appleyay" vowels = "aeiou" if word[0].lower() in vowels: return word + "yay" else: for i, letter in enumerate(word): if letter.lower() in vowels: return word[i:] + word[:i] + "ay" return word + "ay" # For cases where the word has no vowel at all