Final Review: Problem Sets 2

For each of the following questions, you will define a lambda function that returns the stated desired result. You are not allowed to create and use helper functions.

Problem 1: Transform Strings Lambda

Write a lambda function transform_strings that accepts a list of strings and returns a new list where each string is reversed if its length is even, otherwise it should be converted to uppercase.

Example Usage:

transform_strings = # define your lambda here
print(transform_strings(["hello", "world", "python", "is", "fun"]))
# Expected Output: ['HELLO', 'WORLD', 'nohtyp', 'si', 'FUN']
Solution
transform_strings = lambda strings: [s[::-1] if len(s) % 2 == 0 else s.upper() for s in strings]

Explanation: The lambda uses a list comprehension to iterate through each string. For each string, if its length is even (len(s) % 2 == 0), the string is reversed using slice notation s[::-1]. Otherwise, the string is converted to uppercase. The result is a new list with the transformed strings.

The above expression is equivalent to the following function definition:

def transform_strings(strings):
    return [s[::-1] if len(s) % 2 == 0 else s.upper() for s in strings]

Bonus: Would the below alternative approach work the same way?

def transform_strings():
    return lambda strings: [s[::-1] if len(s) % 2 == 0 else s.upper() for s in strings]

Answer to bonus: No, this would not be the same. This function returns a function reference (a lambda) rather than returning the expression result directly (the transformed list). When you call transform_strings(["hello", "world"]), it returns a reference to a function, not the transformed list. To get the actual result, you would need to call the returned function separately:

transform_func = transform_strings()
result = transform_func(["hello", "world"])  # Call the returned lambda

Problem 2: Filter and Transform Lambda

Write a lambda function filter_and_transform that accepts a list of integers, an integer threshold, and returns a new list where:

print(filter_and_transform([5, 12, 8, 15, 3, 20], 10))
# Expected Output: [25, 24, 16, 225, 40]
Solution
filter_and_transform = lambda nums, threshold: [n**2 if n % 2 == 1 else n * 2 for n in nums if (n**2 if n % 2 == 1 else n * 2) >= threshold]

Explanation: The lambda uses a list comprehension that first transforms each number (odd numbers are squared, even numbers are doubled), then filters the result to keep only numbers >= 10. Since the transformation needs to be checked in the filter condition, the transformation logic is repeated.

Problem 3: Count Vowels Lambda

Write a lambda function count_vowels that accepts a string and returns the count of vowels (a, e, i, o, u) in the string.

print(count_vowels("Hello, World!"))
# Expected Output: 3
Solution
count_vowels = lambda s: sum(1 for c in s.lower() if c in 'aeiou')

Explanation: The lambda converts the string to lowercase and uses a generator expression within sum() to count characters that are vowels. The expression 1 for c in s.lower() if c in 'aeiou' yields 1 for each vowel found, and sum() adds them up to get the total count.

Problem 4: Filter Dictionary Lambda

Write a lambda function filter_dict that accepts a dictionary and returns a new dictionary containing only key-value pairs where the key’s paired value is greater than a given threshold.

Example Usage:

print(filter_dict({'apple': 10, 'dog': 2, 'banana': 7}, 4))
# Expected Output: {'apple': 10, 'banana': 7}
Solution
filter_dict = lambda d, threshold: {k: v for k, v in d.items() if v > threshold}

Explanation: The lambda uses a dictionary comprehension to iterate through the key-value pairs in the dictionary. It keeps only the pairs where the value (v) is greater than the threshold. The result is a new dictionary containing only the filtered key-value pairs.

Problem 5: Common Elements Lambda

get_Write a lambda function common_elements that accepts two lists and returns the sorted intersection of the two lists.

Example Usage:

get_print(common_elements([1, 2, 3, 4], [3, 4, 5, 6]))
# Expected Output: [3, 4]
Solution
get_common_elements = lambda list1, list2: sorted(list(set(list1) & set(list2)))

Explanation: The lambda converts both lists to sets and finds their intersection using the & operator. The result is converted back to a list and then sorted in ascending order. This gives the common elements between the two lists in sorted order.

Problem 6: Alternate Case Lambda

Write a lambda function alternate_case that accepts a string and returns a new string where characters at even indices are uppercase and odd indices are lowercase.

Example Usage:

print(alternate_case("python"))
# Expected Output: "PyThOn"
Solution
alternate_case = lambda s: ''.join(c.upper() if i % 2 == 0 else c.lower() for i, c in enumerate(s))

Explanation: The lambda uses enumerate() to get both the index and character from the string. For each character, if its index is even, it’s converted to uppercase; otherwise, it’s converted to lowercase. The join() method concatenates all transformed characters back into a single string.

Problem 7: Group by Parity Lambda

Write a lambda function group_by_parity that accepts a list of integers and returns a tuple of two lists: the first containing all even numbers, the second containing all odd numbers, both sorted in ascending order.

Example Usage:

print(group_by_parity([3, 1, 4, 1, 5, 9, 2, 6]))
# Expected Output: ([2, 4, 6], [1, 1, 3, 5, 9])
Solution
group_by_parity = lambda nums: (sorted([n for n in nums if n % 2 == 0]), sorted([n for n in nums if n % 2 == 1]))

Explanation: The lambda returns a tuple of two lists. The first list comprehension filters for even numbers (n % 2 == 0) and sorts them. The second list comprehension filters for odd numbers (n % 2 == 1) and sorts them. Both lists are returned as a tuple.