Python Workout 08: Filtering and Calculations

Level of Difficulty:

Objective: This workout provides more practice creating calculations and filters with functions.

Easy

Create a function that takes an integer and returns the factorial of that integer. That is, the integer multiplied by all positive lower integers.

Examples:


factorial(3) ➞ 6

factorial(5) ➞ 120

factorial(13) ➞ 6227020800

Notes:
Assume all inputs are greater than or equal to 0.

Medium:

Write a function that takes a list of numbers and returns a list with two elements:

  1. The first element should be the sum of all even numbers in the list.
  2. The second element should be the sum of all odd numbers in the list.

Examples:

sum_odd_and_even([1, 2, 3, 4, 5, 6]) ➞ [12, 9]

sum_odd_and_even([-1, -2, -3, -4, -5, -6]) ➞ [-12, -9])

sum_odd_and_even([0, 0]) ➞ [0, 0])

Notes:
Count 0 as an even number.

Hard:

Create a function that returns the majority vote in a list. A majority vote is an element that occurs > N/2 times in a list (where N is the length of the list).

Examples:

majority_vote(["A", "A", "B"]) ➞ "A"

majority_vote(["A", "A", "A", "B", "C", "A"]) ➞ "A"

majority_vote(["A", "B", "B", "A", "C", "C"]) ➞ None

Notes
• The frequency of the majority element must be strictly greater than 1/2.
• If there is no majority element, return None.
• If the list is empty, return None.

Simply post your code and a screenshot of your results.

Please format your Python code and blur it or place it in a hidden section.

This workout will be released on Monday April 24, 2023, and the author’s solution will be posted on Wednesday April 30, 2023.

1 Like

My attempt:

def factorial(intNum):
result = 1
i = 1
while i <= intNum:
result = result*i
i+=1
return result

def sum_odd_and_even(intList):
newList = []
evenSum = 0
oddSum = 0
for i in range(len(intList)):
if (((i+1) % 2) == 0):
#even
evenSum = evenSum + intList[i]
else:
#odds
oddSum = oddSum + intList[i]
newList.append(evenSum)
newList.append(oddSum)

return newList

def majority_vote (strList):
majority = len(strList)/2 + 1

unique_votes_set = set(strList)
unique_votes_list = list(unique_votes_set)

vote_Winner = ""
most_votes = 0

for v in unique_votes_list:
    num_votes = strList.count(v)
    if (num_votes >= most_votes):
        most_votes = num_votes
        vote_Winner = v

if most_votes >= majority:
   return ("Vote winner is " + vote_Winner + " with " + str(most_votes) + " votes." )
else:
    return ("None")

1 Like

Here’s my easy submission:

def factorial(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

In this function, we initialize the result variable to 1 since multiplying by 1 doesn’t change the value. Then, we iterate over the range from 2 to n + 1 (inclusive) and multiply each value with result. Finally, we return the result as the factorial of the input integer.

Let’s test the function with the provided examples:

print(factorial(3))   # Output: 6
print(factorial(5))   # Output: 120
print(factorial(13))  # Output: 6227020800

The function should produce the correct factorial values for the given examples.

My medium submission:

def sum_odd_and_even(numbers):
    even_sum = 0
    odd_sum = 0
    for num in numbers:
        if num % 2 == 0:
            even_sum += num
        else:
            odd_sum += num
    return [even_sum, odd_sum]

And my HARD challenge submission.

To solve this problem, you can use a combination of a dictionary and a loop to count the occurrences of each element in the list. Then, you can check if any element has a count greater than half the length of the list to determine the majority vote.

Here’s a Python function that implements this logic:

def majority_vote(lst):
    if not lst:
        return None

    counts = {}
    for item in lst:
        if item in counts:
            counts[item] += 1
        else:
            counts[item] = 1

    length = len(lst)
    for item, count in counts.items():
        if count > length / 2:
            return item

    return None

The function should correctly identify the majority vote or return None when there is no majority element or the list is empty.

I tested this last one out in google collab to work on my bi notebook skills

Enjoyed this one! Learning a ton about how python really works. Very similar to VBA actually

Easy

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

Medium

def sum_even_odd(numbers):
    even_sum = 0
    odd_sum = 0
    for num in numbers:
        if num % 2 == 0:
            even_sum += num
        else:
            odd_sum += num
    return [even_sum, odd_sum]

Hard

def majority_vote(lst):
    counts = {}
    for item in lst:
        counts[item] = counts.get(item, 0) + 1
        if counts[item] > len(lst)/2:
            return item
    return None

Easy:
Don’t re-invent the wheel. Import math.factorial.

Medium:
List comprehension:

def sum_odd_and_even(lst):
    even_sum = sum(i for i in lst if i % 2 == 0)
    odd_sum  = sum(i for i in lst if i % 2 == 1)
    return [even_sum, odd_sum]

Or filter with lambda:

def sum_odd_and_even(lst):
    even_sum = sum(filter(lambda i: i % 2 == 0, lst))
    odd_sum  = sum(filter(lambda i: i % 2 == 1, lst))
    return [even_sum, odd_sum]

Hard:

from collections import Counter
def majority_vote(lst):
    tally = Counter(lst)
    max_votes = max(tally.values())
    candidate = max(tally, key=tally.get)
    if max_votes > len(lst) / 2:
        return candidate
    else:
        return None

@AlexisOlson you can solve it however you want, but the idea behind some of these, even the easy ones, is to avoid using python pre-built functions

1 Like

I understand. It’s just an alternative suggestion since I didn’t have any good ideas not already posted.

1 Like