-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplp_1_p3.py
More file actions
executable file
·65 lines (52 loc) · 1.36 KB
/
plp_1_p3.py
File metadata and controls
executable file
·65 lines (52 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#! /usr//bin/env python
def _sort_list(l):
"""
Sorts a list of (key, value) pairs
"""
for i in range(len(l) - 1):
for j in range(i + 1, len(l)):
if (l[i][0] > l[j][0]):
l[i], l[j] = l[j], l[i]
return l
def _compare_dict(dict_a, dict_b):
"""
Compares two dictionaries and returns >0 if dict_a > dict_b
0 if dict_a = dict_b
<0 if dict_a < dict_b
"""
list_a = _sort_list(dict_a.items())
list_b = _sort_list(dict_b.items())
i = t = 0
while i < len(list_a) and i < len(list_b) and t == 0:
t = list_a[i][1] - list_b[i][1]
i += 1
if (i == len(list_a)): t = -1
if (i == len(list_b)): t = 1
return t;
def sort_dict(file):
"""
Reads a list of dictionaries from 'file' and sorts them
"""
f = open(file)
dict_list = []
i = 0
dict_list.append({})
for line in f:
if (line == '\n'):
i += 1
dict_list.append({})
else:
dict_list[i][line[0]] = int(line[2])
f.close()
idx_list = range(len(dict_list));
for i in range(len(dict_list) - 1):
for j in range(i + 1, len(dict_list)):
if (_compare_dict(dict_list[i], dict_list[j]) > 0):
idx_list[i], idx_list[j] = idx_list[j], idx_list[i]
f = open('result', 'r+')
for i in idx_list:
f.write(str(i))
f.write(' ')
f.write('\n')
f.close()
sort_dict('file')