1  Python: Data Structures

Esercizio 1.1 Write a function that takes a list of numbers and returns a new list containing: 1. All even numbers from the original list 2. Sorted in descending order 3. With duplicates removed

Example input: [1, 4, 2, 7, 8, 2, 3, 4, 9, 6]

Soluzione. Here’s the solution with explanation:

def process_numbers(numbers):
    # Convert to set to remove duplicates
    # Filter for even numbers
    # Sort in descending order
    result = sorted(
        {num for num in numbers if num % 2 == 0},
        reverse=True
    )
    return result

# Test the function
test_list = [1, 4, 2, 7, 8, 2, 3, 4, 9, 6]
print(f"Original list: {test_list}")
print(f"Processed list: {process_numbers(test_list)}")
Original list: [1, 4, 2, 7, 8, 2, 3, 4, 9, 6]
Processed list: [8, 6, 4, 2]

Explanation: - We use a set comprehension to simultaneously remove duplicates and filter even numbers - The sorted() function with reverse=True handles the descending order requirement - This solution has O(n log n) time complexity due to the sorting operation

Esercizio 1.2 Create a function that takes a string of words and returns a dictionary where: - Keys are the words - Values are dictionaries containing: - ‘length’: length of the word - ‘vowels’: count of vowels in the word - ‘palindrome’: boolean indicating if the word is a palindrome

Example input: “level python noon code”

Soluzione. Here’s the solution with explanation:

def analyze_words(text):
    def count_vowels(word):
        return sum(1 for char in word.lower() if char in 'aeiou')
    
    def is_palindrome(word):
        word = word.lower()
        return word == word[::-1]
    
    words = text.split()
    result = {}
    
    for word in words:
        result[word] = {
            'length': len(word),
            'vowels': count_vowels(word),
            'palindrome': is_palindrome(word)
        }
    
    return result

# Test the function
text = "level python noon code"
analysis = analyze_words(text)
for word, info in analysis.items():
    print(f"\n{word}:")
    for key, value in info.items():
        print(f"  {key}: {value}")

level:
  length: 5
  vowels: 2
  palindrome: True

python:
  length: 6
  vowels: 1
  palindrome: False

noon:
  length: 4
  vowels: 2
  palindrome: True

code:
  length: 4
  vowels: 2
  palindrome: False

Explanation: - We define helper functions for vowel counting and palindrome checking - The main function creates a dictionary comprehension with nested dictionaries - Each word is analyzed only once, making it efficient for large inputs