Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Explaining the solutions so I understand them solution in Clear category for Split List by BootzenKatzen
from typing import Any, Iterable
#This is my solution which, as always, is clunkier
def split_list(items: list[Any]) -> Iterable[list[Any]]:
list1 = list2 = []
if items != []: # I thought I would need this to catch an empy list. I thought it would throw an out of index error
if len(items) > 1: #I thought a list of only 1 would cause an error as well
half = (len(items) + 1) // 2 #These are the things you learn over time I guess
list1 = items[:half] # what will throw errors, and what's fine
list2 = items[half:]
elif len(items) == 1:
list1 = items
list2 = []
return [list1, list2]
#This is their solution
def split_lists(items: list[Any]) -> Iterable[list[Any]]:
ind = (len(items) + 1) // 2
return [items[:ind], items[ind:]] #I guess if a list is just [] this returns [:0] and [0:]
# and instead of throwing an error like I thought it would
# it returns [[],[]]
# for a list of [1] it would be [:1] and [1:]
# which returns [1] and I guess since there's nothing after 1
# it returns an empty list
# Bonus code 1:
from typing import Any, Iterable
import math
def split_list2(items: list[Any]) -> Iterable[list[Any]]:
half = math.ceil(len(items)/2) # math.ciel() rounds to the nearest whole number
# so it's pretty much the same as adding 1 before dividing and rounding down
return [items[:half], items[half:]]
# Bonus code 2:
def split_list3(items: list[Any]) -> Iterable[list[Any]]:
return [[items.pop(0) for _ in range((len(items)+1)//2)], items] #I had to do a lot of reading to figure this one out
# so "pop" removes items from a list eg num = [1, 2, 3] num.pop(0) means our list is now [2, 3]
# the underscore returns the last executed expression value
# so we're returning the popped value into our []
# and we're doing that until we have half
# then the original "items" list only has the other half left, so you can just call that list
print("Example:")
print(list(split_list([1, 2, 3, 4, 5, 6])))
print(list(split_list(["banana", "apple", "orange", "cherry", "watermelon"])))
assert list(split_list([1, 2, 3, 4, 5, 6])) == [[1, 2, 3], [4, 5, 6]]
assert list(split_list([1, 2, 3])) == [[1, 2], [3]]
assert list(split_list(["banana", "apple", "orange", "cherry", "watermelon"])) == [
["banana", "apple", "orange"],
["cherry", "watermelon"]]
assert list(split_list([1])) == [[1], []]
assert list(split_list([])) == [[], []]
print("The mission is done! Click 'Check Solution' to earn rewards!")
March 31, 2023
Comments: