From f72916516e152aace940d57b846fa8d5da20d97d Mon Sep 17 00:00:00 2001 From: =?utf8?q?Nils=20Forss=C3=A9n?= Date: Wed, 16 Feb 2022 17:30:07 +0100 Subject: [PATCH] linux --- laboration3/uppgift_3.py | 131 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 laboration3/uppgift_3.py diff --git a/laboration3/uppgift_3.py b/laboration3/uppgift_3.py new file mode 100644 index 0000000..dd442b7 --- /dev/null +++ b/laboration3/uppgift_3.py @@ -0,0 +1,131 @@ +# Uppgift 3 + +def fac_rec(n): + if n == 0: + return 1 + else: + return fac_rec(n-1) + + +def fib(n): + if n == 0: + return 0 + elif n == 1: + return 1 + else: + return fib(n-1) + fib(n-2) + + +def pascal(row, col): + if col < 1 or col > row: + return 0 + elif row == 1: + return 1 + else: + return pascal(row-1, col) + pascal(row-1, col - 1) + + +def keep_if_even(lst): + if not lst: + return list() + if not lst[0] % 2: + return [lst[0], *keep_if_even(lst[1:])] + else: + return keep_if_even(lst[1:]) + + +def reverse_rec(lst): + if not lst: + return [] + return [lst[-1], *reverse_rec(lst[:-1])] + + +def keep_if_even_all(lst): + if not lst: + return list() + even_inner = list() + if isinstance(lst[0], list): + even_inner = keep_if_even_all(lst[0]) + elif not lst[0] % 2: + return [lst[0], *keep_if_even_all(lst[1:])] + + return [*even_inner, *keep_if_even_all(lst[1:])] + + +def reverse_rec_all(lst): + if not lst: + return [] + reverse_inner = list() + if isinstance(lst[-1], list): + reverse_inner = reverse_rec_all(lst[-1]) + else: + reverse_inner = [lst[-1]] + + return [*reverse_inner, *reverse_rec(lst[:-1])] + + +def is_in_list(lst, elm): + if not lst: + return False + if isinstance(lst[0], list): + in_inner = is_in_list(lst[0], elm) + else: + in_inner = elm is lst[0] + + return in_inner or is_in_list(lst[1:], elm) + + +def count_all(lst): + if not lst: + return 0 + if isinstance(lst[0], list): + elements = count_all(lst[0]) + else: + elements = 1 + + return elements + count_all(lst[1:]) + + +def subst_all(lst, elm, new_value): + if not lst: + return list() + + if isinstance(lst[0], list): + inner = subst_all([0], elm, new_value) + elif lst[0] == elm: + inner = [new_value] + + return [*inner, *subst_all(lst[1:], elm, new_value)] + + +def linear_search(key, seq): + if not seq: + return False + return seq[0] == key or linear_search(key, seq[1:]) or -1 + + +def binary_search(key, seq): + if len(seq) == 1: + if seq[0] != key: + return -1 + return 0 + print(seq, key) + + mid = len(seq) // 2 + + if key == seq[mid]: + return mid + + elif key > seq[mid]: + res = binary_search(key, seq[mid:]) + if res == -1: + return res + return mid + res + else: + res = binary_search(key, seq[:mid]) + if res == -1: + return res + return res + + +print(binary_search(12, [1, 2, 3, 4, 5, 6, 6.5, 7, 9, 10, 11, 12])) -- 2.30.2