Added 1st lab solutions

This commit is contained in:
Claudio Maggioni 2019-02-20 13:58:39 +01:00
parent bf94a2b282
commit 641b8a407b
3 changed files with 72 additions and 0 deletions

14
count_in_array.py Executable file
View file

@ -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()

34
histogram.py Executable file
View file

@ -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()

24
partition_even_odd.py Executable file
View file

@ -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()