5. Sets of numbers

VC2M5N10: level 5: Follow a mathematical algorithm involving branching and repetition (iteration); create and use algorithms involving a sequence of steps and decisions and digital tools to experiment with factors, multiples and divisibility; identify, interpret and describe emerging patterns
  • manipulating sets of numbers using a given rule, for example, if a number is even, halve it; or if a number is odd, subtract 1 then halve it


5.1. Simple rule

Return a set of numbers using the rule: if a number is even, halve it; if a number is odd, subtract 1 then halve it.
 1def manipulate_numbers(numbers):
 2    """
 3    Takes a set of numbers and applies the following rule to each number:
 4    If the number is even, halve it.
 5    If the number is odd, subtract 1 then halve it.
 6    Returns a new set of manipulated numbers.
 7    """
 8    result = set()
 9    for num in numbers:
10        if num % 2 == 0:
11            result.add(num // 2)
12        else:
13            result.add((num - 1) // 2)
14    return result
15
16numbers = set(range(1, 11))
17manipulated_numbers = manipulate_numbers(numbers)
18print(manipulated_numbers)
19# {0, 1, 2, 3, 4, 5}

5.2. Even numbers

Return a set of even numbers.
 1def even_numbers(numbers):
 2    """
 3    Takes a set of numbers and returns a new set containing only the even numbers.
 4    """
 5    result = set()
 6    for num in numbers:
 7        if num % 2 == 0:
 8            result.add(num)
 9    return result
10
11numbers = set(range(1,11))
12even_nums = even_numbers(numbers)
13print(even_nums)

5.3. Sum numbers in sequence

Return a list of numbers that are a running total as each member of the set is added to the running total.
 1def sequential_addition(numbers):
 2    """
 3    Takes a set of numbers and forms a new list by sequentially adding them.
 4    Returns the new list of numbers.
 5    """
 6    result = list()
 7    current_sum = 0
 8    for num in numbers:
 9        current_sum += num
10        result.append(current_sum)
11    return result
12
13numbers = set(range(1,11))
14new_numbers = sequential_addition(numbers)
15print(new_numbers)
16# [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]