def last_pair(lst): if utility.is_null(lst): raise ValueError('empty list') if utility.is_null(utility.cdr(lst)): return utility.car(lst) else: return last_pair(utility.cdr(lst))
def square_list(list): if utility.is_null(list): return utility.list() else: return utility.cons( square(utility.car(list)), square_list(utility.cdr(list)))
def reverse(lst): if utility.is_null(lst): return None elif utility.length(lst) == 1: return lst else: x = utility.car(lst) xs = utility.cdr(lst) return utility.append(reverse(xs), utility.list(x))
def same_parity_iter(a): """ :type a: FunctionType | object :return: """ if is_null(a): return None else: b = car(a) # type: int if is_even(x - b): return cons(b, same_parity_iter(cdr(a))) else: return same_parity_iter(cdr(a))
def deep_reverse(lst): def deep_reverse_element(a): if callable(a): return utility.list(deep_reverse(a)) else: return utility.list(a) def deep_reverse_of_length_one(lst): return deep_reverse_element(utility.car(lst)) # utility.print_list(lst) if utility.is_null(lst): return None elif utility.length(lst) == 1: return deep_reverse_of_length_one(lst) else: x = utility.car(lst) xs = utility.cdr(lst) x_rev = deep_reverse_element(x) xs_rev = deep_reverse(xs) return utility.append(xs_rev, x_rev)
def for_each(f, lst): if not utility.is_null(lst): f(utility.car(lst)) for_each(f, utility.cdr(lst))
def accumulate(op, initial, list): if is_null(list): return initial else: return op(car(list), accumulate(op, initial, cdr(list)))
def subsets(l): if is_null(l): return list(list()) rest = subsets(cdr(l)) return append(rest, map(lambda x: cons(car(l), x) , rest))
def iter(things, answer): if is_null(things): return answer else: iter(cdr(things), cons(answer, square(car(things))))