-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path15_collections.ring
More file actions
74 lines (66 loc) · 1.59 KB
/
15_collections.ring
File metadata and controls
74 lines (66 loc) · 1.59 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
66
67
68
69
70
71
72
73
74
/*
15 - Python Collections & Comprehensions
Demonstrate list/dict comprehensions and collections module.
*/
load "python.ring"
py_init()
# ---- List comprehensions ----
? "=== List Comprehensions ==="
py_exec("squares = [x**2 for x in range(10)]")
? "Squares 0-9: "
squares = py_get("squares")
for s in squares
? " " + s
next
py_exec("evens = [x for x in range(20) if x % 2 == 0]")
? ""
? "Even numbers 0-19:"
evens = py_get("evens")
for e in evens
? " " + e
next
# ---- Dict comprehension ----
? ""
? "=== Dict Comprehension ==="
py_exec("
word = 'abracadabra'
freq = {ch: word.count(ch) for ch in set(word)}
")
freq = py_get("freq")
? "Character frequency in 'abracadabra':"
for pair in freq
if islist(pair) and len(pair) = 2
? " '" + pair[1] + "' → " + pair[2]
ok
next
# ---- collections.Counter ----
? ""
? "=== Counter ==="
py_exec("
from collections import Counter
words = 'the cat sat on the mat the cat'.split()
counts = dict(Counter(words).most_common())
")
counts = py_get("counts")
? "Word counts:"
for pair in counts
if islist(pair) and len(pair) = 2
? " " + pair[1] + ": " + pair[2]
ok
next
# ---- Sorting ----
? ""
? "=== Sorting ==="
py_exec("
data = [
{'name': 'Charlie', 'age': 25},
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 20},
]
by_name = sorted(data, key=lambda x: x['name'])
by_age = sorted(data, key=lambda x: x['age'])
_names = [p['name'] for p in by_name]
_ages = [p['name'] + '(' + str(p['age']) + ')' for p in by_age]
")
? "By name: " + py_eval("', '.join(_names)")
? "By age: " + py_eval("', '.join(_ages)")