Files
exercism_puzzles/python/list-ops/list_ops.py
T

74 lines
1.9 KiB
Python

from typing import Callable
# return the length of list
def length(list: list) -> int:
length: int = 0
for _ in list:
length += 1
return length
# append list2 at the end of list1
def append(list1: list, list2: list) -> list:
new_list: list = []
for index, item in enumerate(list1, 0):
new_list.insert(index, item)
for index, item in enumerate(list2, length(list1)):
new_list.insert(index, item)
return new_list
def concat(lists: list[list]):
new_list: list = []
for item_list in lists:
new_list = append(new_list, item_list)
return new_list
def filter(function: Callable, list_of_items: list):
filtered_list: list = []
insert_index: int = 0
for item in list_of_items:
if function(item):
filtered_list.insert(insert_index, item)
insert_index += 1
return filtered_list
def map(function, list_of_items):
mapped_list: list = []
for index, item in enumerate(list_of_items):
mapped_list.insert(index, function(item))
return mapped_list
def foldl(
function: Callable, list_of_items: list[int | str], initial: int | str
) -> int | str:
result: int | str = initial
if len(list_of_items) == 0:
return result
for index in range(0, len(list_of_items)):
result = function(result, list_of_items[index])
return result
def foldr(function: Callable, list_of_items: list, initial: int | str) -> int | str:
result: int | str = initial
if len(list_of_items) == 0:
return result
for index in range(len(list_of_items) - 1, -1, -1):
result = function(result, list_of_items[index])
return result
# reverse the order of the elements in the list
def reverse(list_of_items: list) -> list:
# not doing this
# return list[::-1]
reversed_list: list = []
for item in list_of_items:
reversed_list.insert(0, item)
return reversed_list