Python Function Practice Questions
Python Function Practice Questions
Using *args and **kwargs in Python allows functions to accept arbitrary numbers of positional and keyword arguments, enhancing flexibility. For example, `def add(*args): return sum(args)` can sum an unspecified number of numbers. Similarly, `def print_kwargs(**kwargs):` allows key-value pairs to be passed and printed: `for key, value in kwargs.items(): print(f'{key} = {value}')`. This makes functions more reusable by accommodating varied input patterns .
To create a function that reverses a string in Python, you can define a function that uses slicing: `def reverse_string(s): return s[::-1]`. When reversing strings with special characters, such as Unicode characters, you should consider their representation. Python handles Unicode natively, so the reversal should work correctly as long as the input encoding is properly handled .
To determine if two strings are anagrams, you can sort both strings and check for equality: `sorted(str1) == sorted(str2)`. Alternatively, you can use a frequency count of characters using a dictionary or collections.Counter, comparing the two counts. The sorting approach has a time complexity of O(n log n), while using counts is O(n), making it more efficient for large strings .
To check if a string is a palindrome, you can normalize it by removing non-alphanumeric characters and converting it to lower case, then compare it to its reverse. For example, use `s = ''.join(filter(str.isalnum, s)).lower()` followed by checking `s == s[::-1]`. This approach ensures that case differences and non-letter/number characters do not affect the outcome .
The recursive computation of the nth Fibonacci number (e.g., `def fib(n): return n if n<=1 else fib(n-1) + fib(n-2)`) illustrates recursion's conceptual simplicity and elegance in expressing iterative processes. However, it highlights weaknesses such as exponential time complexity and stack overflow risks for large n, due to repeated calculations. Iterative or memoized recursive solutions can address these inefficiencies .
To convert Celsius to Fahrenheit in Python, use the formula `F = (C * 9/5) + 32`. The function can be defined as `def celsius_to_fahrenheit(c): return (c * 9/5) + 32`. Precision is crucial in this conversion, especially in scientific contexts, as small errors can propagate, affecting further calculations or decisions based on temperature data .
To convert a list to a comma-separated string in Python, use the `join()` method: `','.join(map(str, my_list))`. This process requires that all list elements be strings or are converted to strings, which might alter data representation if not handled carefully. Special characters in list elements, like commas, can inadvertently affect the integrity of the output .
The `zip()` function pairs elements from lists: `zip(list1, list2)`. For example, `zip([1, 2, 3], ['a', 'b', 'c'])` results in `[(1, 'a'), (2, 'b'), (3, 'c')]`. A limitation is that it stops at the shortest list, which can lead to data loss if not all elements are paired; thus, unequal lengths require careful handling, such as using `itertools.zip_longest` to ensure all elements are included .
Using map() with a lambda function to square numbers is concise and functional, as it applies the lambda expression to each element in the list without an explicit loop: `map(lambda x: x**2, my_list)`. This approach increases readability and can be more efficient with large datasets. However, it may reduce clarity for beginners unfamiliar with lambda syntax and map usage, and it returns a map object in Python 3 rather than a list, requiring conversion with `list()` .
Efficiently counting vowels in a string can be achieved by iterating once and using a set to check membership: e.g., `sum(1 for char in s if char.lower() in 'aeiou')`. Computational efficiency is important, especially with large strings, to minimize processing time and resource usage, which is critical for real-time applications or systems with limited resources .