Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Annotated for Understanding solution in Clear category for Majority by BootzenKatzen
"""
This is my solution without hints -
Funny story - I thought it didn't work for a while
It just kept returning true for everything
Then I realized my if statements were:
for i in items:
if True:
do thing
elif False:
do thing
Which just returns True
I forgot to put 'if i ==' first X-D
"""
def is_majority(items: list[bool]) -> bool:
trues = []
falses = []
result = False
for i in items:
if i == True:
trues.append(i)
elif i == False:
falses.append(i)
return len(trues) > len(falses)
# This is the solution from the hints which is much more compact
# I just get stuck using the same things I know (for loops and if statements)
def is_majority2(items: list[bool]) -> bool:
return items.count(True) > len(items) / 2
# This is simple enough, it counts the number of True values in items
# Then checks if that number is greater than half, by dividing the length of the list by 2
#Bonus solution:
def is_majority3(items: list[bool]) -> bool:
return sum(items) > len(items) / 2
# I thought this was really clever - when trying to sum the list, it values True as 1 and False as 0
# So the sum is essentially the number of True values
# And you compare it to the length of the list divided by 2 like the previous solution
print("Example:")
print(is_majority([True, True, False, False]))
# These "asserts" are used for self-checking
assert is_majority([True, True, False, True, False]) == True
assert is_majority([True, True, False]) == True
assert is_majority([True, True, False, False]) == False
assert is_majority([True, True, False, False, False]) == False
assert is_majority([False]) == False
assert is_majority([True]) == True
assert is_majority([]) == False
print("The mission is done! Click 'Check Solution' to earn rewards!")
April 11, 2023
Comments: