From 641b8a407bc80d4f01820a0c3fbb0ddff8f6cd61 Mon Sep 17 00:00:00 2001 From: Claudio Maggioni Date: Wed, 20 Feb 2019 13:58:39 +0100 Subject: [PATCH] Added 1st lab solutions --- count_in_array.py | 14 ++++++++++++++ histogram.py | 34 ++++++++++++++++++++++++++++++++++ partition_even_odd.py | 24 ++++++++++++++++++++++++ 3 files changed, 72 insertions(+) create mode 100755 count_in_array.py create mode 100755 histogram.py create mode 100755 partition_even_odd.py diff --git a/count_in_array.py b/count_in_array.py new file mode 100755 index 0000000..30a1644 --- /dev/null +++ b/count_in_array.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 + +def count_in_array(x, A): + c = 0 + for elem in A: + if elem == x: + c = c + 1 + return c + +def main(): + print(count_in_array(5, [7, 5, 16, 3, 10, 5, 8, 1, 29, 13, 28])) + +if __name__ == "__main__": + main() diff --git a/histogram.py b/histogram.py new file mode 100755 index 0000000..2a671f8 --- /dev/null +++ b/histogram.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 + +import sys + +def histogram(data): + height_max = max(data) + height_min = min(min(data), 0) + current_line = height_max + + while current_line >= height_min: + to_print = "" + + if current_line == 0: + print("-" * len(data)) + else: + for elem in data: + if current_line > 0 and elem >= current_line: + to_print += "#" + elif current_line > 0: + to_print += " " + elif current_line < 0 and elem <= current_line: + to_print += "#" + else: + to_print += " " + print(to_print) + + current_line = current_line - 1 + +def main(): + args = [int(x) for x in sys.argv[1:]] + histogram(args) + +if __name__ == "__main__": + main() diff --git a/partition_even_odd.py b/partition_even_odd.py new file mode 100755 index 0000000..567873e --- /dev/null +++ b/partition_even_odd.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +# vim: set ts=4 sw=4 et tw=80: + +import sys + +# This is a modified version of BubbleSort that swaps elements only if the first +# is odd and the second one is even +def partition_even_odd(x): + i = len(x) - 1 + while i > 0: + for j in range(0, i): + if x[j] % 2 == 1 and x[j+1] % 2 == 0: + c = x[j] + x[j] = x[j+1] + x[j+1] = c + i = i - 1 + +def main(): + args = [int(x) for x in sys.argv[1:]] + partition_even_odd(args) + print(args) + +if __name__ == "__main__": + main()