From: NilsForssen Date: Mon, 7 Feb 2022 09:27:29 +0000 (+0100) Subject: j X-Git-Url: https://gitweb.forssennils.se/?a=commitdiff_plain;h=9e8ab1e3a217e531218e690df3c96f88e8a40ce6;p=TDDE44.git j --- diff --git a/laboration3/uppgift_2.py b/laboration3/uppgift_2.py new file mode 100644 index 0000000..2d83dd0 --- /dev/null +++ b/laboration3/uppgift_2.py @@ -0,0 +1,71 @@ +# Uppgift 3 + +def sum_of_ints2(value_list): + tot = 0 + for inner in value_list: + for item in inner: + if isinstance(item, int): + tot += item + return tot + + +def flatten_list1(value_list): + return [item for inner in value_list for item in inner] + + +def flatten_list2(value_list): + tot = [] + for inner in value_list: + if isinstance(inner, list): + tot.extend(inner) + else: + tot.append(inner) + + return tot + + +def get_first_column(matrix): + tot = [] + for row in matrix: + tot.append(row[0]) + return tot + + +def get_nth_column(n, matrix): + tot = [] + for row in matrix: + tot.append(row[n - 1]) + return tot + + +def get_all_columns(matrix): + cols = [[] for _ in matrix[0]] + + for row in matrix: + for idx, item in enumerate(row): + cols[idx].append(item) + + return cols + + +def scalar_product(vec1, vec2): + prod = 0 + for row1 ,row2 in zip(vec1, vec2): + if isinstance(row1, list) and isinstance(row2, list): + for item1, item2 in zip(row1, row2): + prod += item1*item2 + else: + prod += row1*row2 + return prod + + +def matrix_square(matrix): + tot = [[] for _ in matrix] + for idx, (row, col) in enumerate(zip(matrix, get_all_columns(matrix))): + tot[idx].append(scalar_product(row, col)) + return tot + +print(matrix_square([[1, 2, 4], + [3, 0, 6], + [0, 5, 1]] +)) \ No newline at end of file diff --git a/laboration3/uppgift_3.py b/laboration3/uppgift_3.py deleted file mode 100644 index e263aed..0000000 --- a/laboration3/uppgift_3.py +++ /dev/null @@ -1,63 +0,0 @@ -# Uppgift 3 - -def sum_of_ints2(value_list): - tot = 0 - for inner in value_list: - for item in inner: - if isinstance(item, int): - tot += item - return tot - - -def flatten_list1(value_list): - return [item for inner in value_list for item in inner] - - -def flatten_list2(value_list): - tot = [] - for inner in value_list: - if isinstance(inner, list): - tot.extend(inner) - else: - tot.append(inner) - - return tot - - -def get_first_column(matrix): - tot = [] - for row in matrix: - tot.append(row[0]) - return tot - - -def get_nth_column(n, matrix): - tot = [] - for row in matrix: - tot.append(row[n]) - return tot - - -def get_all_columns(matrix): - cols = [[] for _ in matrix] - - for row in matrix: - for idx, item in enumerate(row): - cols[idx].append(item) - - return cols - - -def scalar_product(vec1, vec2): - prod = 0 - for row in vec1: - for item1, item2 in zip(vec1, vec2): - prod += item1*item2 - return prod - - -def matrix_square(matrix): - tot = [[] for _ in matrix] - for idx, (row, col) in enumerate(zip(matrix, get_all_columns(matrix))): - tot[idx].append(scalar_product(row, col)) - return tot