2019-03-05 in class

This commit is contained in:
Claudio Maggioni 2019-03-05 13:23:46 +01:00
parent fd7713fb33
commit 864d111326
4 changed files with 59 additions and 23 deletions

View file

@ -1,30 +1,27 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim: set sw=4 ts=4 et tw=80:
import sys import sys
def histogram(data): def histogram(data):
height_max = max(data) top = max(max(data), 0)
height_min = min(min(data), 0) bottom = min(min(data), 0)
current_line = height_max i = top
while current_line >= height_min: while i >= bottom:
to_print = "" to_print = ""
if current_line == 0:
print("-" * len(data))
else:
for elem in data: for elem in data:
if current_line > 0 and elem >= current_line: if i == 0:
to_print += "#" to_print += "-"
elif current_line > 0: elif (i > 0 and elem >= i) or \
to_print += " " (i < 0 and elem <= i):
elif current_line < 0 and elem <= current_line:
to_print += "#" to_print += "#"
else: else:
to_print += " " to_print += " "
print(to_print) print(to_print)
current_line = current_line - 1 i = i - 1
def main(): def main():
args = [int(x) for x in sys.argv[1:]] args = [int(x) for x in sys.argv[1:]]

View file

@ -1,4 +1,5 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# vim: set ts=4 sw=4 et tw=80:
import sys import sys
@ -10,9 +11,8 @@ def insertionsort(A):
print(A) print(A)
print(A) print(A)
i = j - 1 i = j - 1
tomove = A[j] # while swapping is necessary or at the end of array
while i >= 0 and tomove < A[i]: while i >= 0 and A[i+1] < A[i]:
if A[i] > A[i+1]:
# Swap A[i] and A[j] # Swap A[i] and A[j]
A[i+1], A[i] = A[i], A[i+1] A[i+1], A[i] = A[i], A[i+1]
i = i - 1 i = i - 1

34
mergesort.py Normal file
View file

@ -0,0 +1,34 @@
#!/usr/bin/env python3
# vim: set ts=4 sw=4 et tw=80:
import sys
import math
def find(A,x):
for a in A:
if a == x:
return True
return False
def merge(A,B):
X = []
for a in A:
if not find(X, a):
X.append(a)
for b in B:
if not find(X, b):
X.append(b)
return X
def mergesort(A):
l = len(A)
if l < 2:
return A
else:
lh = len(A) // 2
h1 = mergesort(A[:lh])
h2 = mergesort(A[lh:])
return merge(h1,h2)
args = [int(x) for x in sys.argv[1:]]
print(mergesort(args))

View file

@ -94,3 +94,8 @@ Proof sort of by induction.
An algorithm is correct if given an input the output satisfies the conditions An algorithm is correct if given an input the output satisfies the conditions
stated. The algorithm must terminate. stated. The algorithm must terminate.
### The loop invariant
Invariant condition able to make a loop equivalent to a straight path in an
execution graph.