sr-zero 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,489 @@
1
+ """Puzzles that can be computed: a state that poses one, read by a parser written for its kind, solved, and the option
2
+ the solution makes true picked. Each kind proposes an answer only when its parse is complete and exactly one option
3
+ fits; anything else is left to the rules.
4
+
5
+ - boolean: an expression of True, False, not, and, or and parentheses
6
+ - liars: who tells the truth, from "X lies" and "Y says X tells the truth"
7
+ - route: whether a walk of steps and turns ends where it began
8
+ - swaps: who holds what after a sequence of pairwise swaps
9
+ - order: the one arrangement of N objects that satisfies every statement about their order
10
+ - free_time: the slot of a day that no sighting covers
11
+ - adjectives: the sentence whose adjectives come in English order (opinion, size, age, shape, colour, origin,
12
+ material, purpose), from a hand-written table of adjectives by kind
13
+ """
14
+ import functools
15
+ import itertools
16
+ import json
17
+ import re
18
+
19
+ from .. import text
20
+
21
+ NAME = "puzzles"
22
+ CASES = {
23
+ "boolean": "the value of the Boolean expression, evaluated with not before and before or",
24
+ "liars": "the answer that follows from who lies and who tells the truth",
25
+ "route": "whether the steps and turns, traced one by one, end on the starting point",
26
+ "swaps": "who holds what after every swap, traced in order",
27
+ "order": "the statement true in the only arrangement that satisfies every given order",
28
+ "free_time": "the only time slot between waking and closing that no sighting covers",
29
+ "adjectives": "the only sentence whose adjectives come in English order: opinion, size, age, shape, colour, "
30
+ "origin, material, purpose",
31
+ }
32
+ YES = {"yes", "true", "valid"}
33
+ NO = {"no", "false", "invalid"}
34
+ ORDINALS = {"first": 1, "second": 2, "third": 3, "fourth": 4, "fifth": 5, "sixth": 6, "seventh": 7, "last": -1}
35
+ NUMBERS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7} | {str(i): i for i in range(2, 8)}
36
+
37
+
38
+ def options_of(question):
39
+ return [(k, text.flatten(d) if d is not None else k) for k, d in (question.get("criteria") or {}).items()]
40
+
41
+
42
+ def pick_truth(question, value):
43
+ """The option meaning True (yes) or False (no)."""
44
+ found = [k for k, d in options_of(question) if (d or k).strip().strip(".").lower() in (YES if value else NO)]
45
+ if not found:
46
+ found = [k for k, d in options_of(question) if k.strip("()").lower() in (YES if value else NO)]
47
+ return found[0] if len(found) == 1 else None
48
+
49
+
50
+ def body(request):
51
+ """The puzzle text: the state, without a trailing list of options."""
52
+ return request.once("puzzles.body", _body)
53
+
54
+
55
+ def _body(request):
56
+ raw = request.state_text if isinstance(request.state, str) else text.flatten(request.state)
57
+ return re.split(r"\nOptions:\n", raw)[0].strip()
58
+
59
+
60
+ # ---- boolean expressions ----------------------------------------------------------------------------------------
61
+
62
+ BOOLEAN_TOKEN = re.compile(r"\(|\)|\w+")
63
+ BOOLEAN_WORDS = frozenset(("(", ")", "True", "False", "not", "and", "or"))
64
+
65
+
66
+ def boolean(request, question):
67
+ source = body(request)
68
+ m = re.search(r'expression:\s*"([^"]+)"', source)
69
+ expression = m.group(1) if m else re.sub(r"\s+is\s*$", "", source)
70
+ tokens = []
71
+ for found in BOOLEAN_TOKEN.finditer(expression):
72
+ if found.group(0) not in BOOLEAN_WORDS:
73
+ return None
74
+ tokens.append(found.group(0))
75
+ if not tokens:
76
+ return None
77
+ position = [0]
78
+
79
+ def peek():
80
+ return tokens[position[0]] if position[0] < len(tokens) else None
81
+
82
+ def take():
83
+ position[0] += 1
84
+ return tokens[position[0] - 1]
85
+
86
+ def atom():
87
+ t = take()
88
+ if t == "not":
89
+ return not atom()
90
+ if t == "(":
91
+ value = disjunction()
92
+ if take() != ")":
93
+ raise ValueError("unbalanced")
94
+ return value
95
+ if t in ("True", "False"):
96
+ return t == "True"
97
+ raise ValueError(t)
98
+
99
+ def conjunction():
100
+ value = atom()
101
+ while peek() == "and":
102
+ take()
103
+ right = atom()
104
+ value = value and right
105
+ return value
106
+
107
+ def disjunction():
108
+ value = conjunction()
109
+ while peek() == "or":
110
+ take()
111
+ right = conjunction()
112
+ value = value or right
113
+ return value
114
+
115
+ try:
116
+ value = disjunction()
117
+ except (ValueError, IndexError):
118
+ return None
119
+ if position[0] != len(tokens):
120
+ return None
121
+ return pick_truth(question, value)
122
+
123
+
124
+ # ---- who lies ---------------------------------------------------------------------------------------------------
125
+
126
+ def liars(request, question):
127
+ source = body(request).replace("Question:", " ")
128
+ sentences = [s.strip() for s in re.split(r"(?<=[.?])\s+", source) if s.strip()]
129
+ truth = {}
130
+ asked = None
131
+ for s in sentences:
132
+ m = re.fullmatch(r"(\w+) (lies|tells the truth)\.", s)
133
+ if m:
134
+ truth[m.group(1)] = m.group(2) == "tells the truth"
135
+ continue
136
+ m = re.fullmatch(r"(\w+) says (\w+) (lies|tells the truth)\.", s)
137
+ if m:
138
+ speaker, subject, claim = m.groups()
139
+ if subject not in truth:
140
+ return None
141
+ said = truth[subject] == (claim == "tells the truth")
142
+ truth[speaker] = said
143
+ continue
144
+ m = re.fullmatch(r"Does (\w+) tell the truth\?", s)
145
+ if m:
146
+ asked = m.group(1)
147
+ continue
148
+ return None
149
+ if asked is None or asked not in truth:
150
+ return None
151
+ return pick_truth(question, truth[asked])
152
+
153
+
154
+ # ---- routes -----------------------------------------------------------------------------------------------------
155
+
156
+ def walk(moves):
157
+ """Whether moves [(kind, steps)] end on the start: turns rotate in place, sidesteps keep the facing."""
158
+ x = y = 0
159
+ dx, dy = 0, 1
160
+ for kind, n in moves:
161
+ if kind == "turn_left":
162
+ dx, dy = -dy, dx
163
+ elif kind == "turn_right":
164
+ dx, dy = dy, -dx
165
+ elif kind == "turn_around":
166
+ dx, dy = -dx, -dy
167
+ elif kind == "forward":
168
+ x, y = x + n * dx, y + n * dy
169
+ elif kind == "backward":
170
+ x, y = x - n * dx, y - n * dy
171
+ elif kind == "left":
172
+ x, y = x - n * dy, y + n * dx
173
+ elif kind == "right":
174
+ x, y = x + n * dy, y - n * dx
175
+ else:
176
+ return None
177
+ return x == 0 and y == 0
178
+
179
+
180
+ def moves_in(source):
181
+ """The moves of a route written as data: an object with a list of {kind, steps}, inside the text."""
182
+ decoder = json.JSONDecoder()
183
+ for i, ch in enumerate(source):
184
+ if ch != "{":
185
+ continue
186
+ try:
187
+ value, _ = decoder.raw_decode(source, i)
188
+ except ValueError:
189
+ continue
190
+ if isinstance(value, dict) and isinstance(value.get("moves"), list):
191
+ moves = []
192
+ for m in value["moves"]:
193
+ if not isinstance(m, dict) or "kind" not in m:
194
+ return None
195
+ moves.append((str(m["kind"]), int(m.get("steps", 0) or 0)))
196
+ return moves
197
+ return None
198
+
199
+
200
+ def route(request, question):
201
+ source = body(request)
202
+ moves = moves_in(source) if '"moves"' in source else None
203
+ if moves is not None:
204
+ back = walk(moves)
205
+ return None if back is None else pick_truth(question, back)
206
+ if "starting point" not in source and "starting spot" not in source:
207
+ return None
208
+ steps = re.findall(r"(Always face forward\.|Turn (?:left|right|around)\.|Take (\d+) steps?(?: (forward|backward|"
209
+ r"left|right))?\.)", source)
210
+ words = re.sub(r"[^.?]*\bstarting (?:point|spot)\b[^.?]*\?", "", source)
211
+ leftover = re.sub(r"Always face forward\.|Turn (?:left|right|around)\.|Take \d+ steps?(?: (?:forward|backward|left|"
212
+ r"right))?\.", "", words).strip()
213
+ if not steps or leftover:
214
+ return None
215
+ moves = []
216
+ for whole, count, direction in steps:
217
+ if whole.startswith("Turn"):
218
+ moves.append(("turn_" + whole.split()[1].rstrip("."), 0))
219
+ elif whole.startswith("Take"):
220
+ moves.append((direction or "forward", int(count)))
221
+ back = walk(moves)
222
+ return None if back is None else pick_truth(question, back)
223
+
224
+
225
+ # ---- swaps ------------------------------------------------------------------------------------------------------
226
+
227
+ def swaps(request, question):
228
+ source = body(request)
229
+ start = re.search(r"At the start of [^:]*?, (?:they are each|each one is|they each|they are all)[^:]*?: (.+?)\.\s",
230
+ source + " ")
231
+ if not start:
232
+ return None
233
+ clauses = [c.strip() for c in re.split(r",\s*(?:and\s+)?|\s+and\s+(?=[A-Z])", start.group(1)) if c.strip()]
234
+ holders = {}
235
+ options = options_of(question)
236
+ for clause in clauses:
237
+ m = re.match(r"([A-Z]\w*)\s+(.*)", clause)
238
+ if not m:
239
+ return None
240
+ name, rest = m.groups()
241
+ held = [k for k, d in options if re.search(r"\b" + re.escape(d.strip().lower()) + r"\b", rest.lower())]
242
+ if len(held) != 1:
243
+ return None
244
+ holders[name] = held[0]
245
+ if len(set(holders.values())) != len(holders):
246
+ return None
247
+ after = source[start.end():]
248
+ trades = re.findall(r"([A-Z]\w*) and ([A-Z]\w*) (?:swap|switch|trade)", after)
249
+ if not trades:
250
+ return None
251
+ for a, b in trades:
252
+ if a not in holders or b not in holders:
253
+ return None
254
+ holders[a], holders[b] = holders[b], holders[a]
255
+ end = re.search(r"At the end of [^,]*, ([A-Z]\w*)\b", after)
256
+ if not end or end.group(1) not in holders:
257
+ return None
258
+ return holders[end.group(1)]
259
+
260
+
261
+ # ---- orders -----------------------------------------------------------------------------------------------------
262
+
263
+ # (relation between two names, whether the first comes earlier on the scale): left to right, best placed first,
264
+ # oldest, cheapest, lightest and earliest first, the bottom floor first
265
+ PAIRS = (
266
+ (r"(?:is|are|hangs?|sits?|stands?) (?:to the )?left of", True),
267
+ (r"(?:is|are|hangs?|sits?|stands?) (?:to the )?right of", False),
268
+ (r"finished (?:above|ahead of)", True), (r"finished (?:below|behind)", False),
269
+ (r"(?:is|are) older than", True), (r"(?:is|are) newer than", False),
270
+ (r"(?:is|are) (?:cheaper|less expensive) than", True), (r"(?:is|are) more expensive than", False),
271
+ (r"(?:is|are) lighter than", True), (r"(?:is|are) heavier than", False),
272
+ (r"(?:departs|leaves|arrives) earlier than", True), (r"(?:departs|leaves|arrives) later than", False),
273
+ (r"lives below", True), (r"lives above", False),
274
+ )
275
+ EARLY = {"oldest", "cheapest", "least expensive", "lightest", "earliest"}
276
+ LATE = {"newest", "most expensive", "heaviest", "latest"}
277
+ ORDINAL = r"(\w+(?:-to-last)?)"
278
+
279
+
280
+ def _norm(name):
281
+ return re.sub(r"^(?:a|an|the)\s+", "", name.strip().lower())
282
+
283
+
284
+ @functools.lru_cache(maxsize=256)
285
+ def _objects(source):
286
+ """(names, end of their list) of the paragraph's objects: 'N things ...: a, b, and c.' with N names."""
287
+ counts = "|".join(sorted(NUMBERS, key=len, reverse=True))
288
+ for m in re.finditer(r"\b(" + counts + r") ([a-z][a-z\s-]*?): (.+?)\.(?=\s|$)", source, re.I):
289
+ count = NUMBERS[m.group(1).lower()]
290
+ names = [_norm(n) for n in re.split(r",\s*(?:and\s+)?|\s+and\s+", m.group(3)) if n.strip()]
291
+ if len(names) == count and len(set(names)) == count:
292
+ return names, m.end()
293
+ return None
294
+ return None
295
+
296
+
297
+ def _position(word, n):
298
+ """The 1-based place an ordinal names, counted from the given end ('second-to-last' from the far end)."""
299
+ word = word.lower()
300
+ m = re.fullmatch(r"(\w+)-to-last", word)
301
+ if m:
302
+ k = ORDINALS.get(m.group(1))
303
+ return None if k is None or k < 1 else n + 1 - k
304
+ k = ORDINALS.get(word)
305
+ if k is None:
306
+ return None
307
+ return n if k == -1 else k
308
+
309
+
310
+ def _place(a, k):
311
+ return None if k is None else (lambda o: o.index(a) + 1 == k)
312
+
313
+
314
+ def _statement(sentence, names, read=False):
315
+ """A test of an arrangement (a tuple of names from the early end of the scale) for one sentence; None if the
316
+ sentence cannot be read, and True if it names no object at all. `read`: the names are already marked."""
317
+ n = len(names)
318
+ s = sentence.strip().rstrip(".").lower()
319
+ if not read:
320
+ for name in sorted(names, key=len, reverse=True):
321
+ s = re.sub(r"\b(?:the\s+)?" + re.escape(name) + r"\b", "<" + name + ">", s)
322
+ subjects = re.findall(r"<([^>]+)>", s)
323
+ if not subjects:
324
+ return True
325
+ negated = re.fullmatch(r"(<[^>]+> (?:is|are)) not (.+)", s)
326
+ if negated:
327
+ test = _statement(negated.group(1) + " " + negated.group(2), names, read=True)
328
+ return None if test is None or test is True else (lambda o: not test(o))
329
+ a = subjects[0]
330
+ if len(subjects) == 2:
331
+ b = subjects[1]
332
+ for relation, earlier in PAIRS:
333
+ if re.fullmatch(r"<[^>]+> " + relation + r" <[^>]+>", s):
334
+ return (lambda o: o.index(a) < o.index(b)) if earlier else (lambda o: o.index(a) > o.index(b))
335
+ return None
336
+ if len(subjects) != 1:
337
+ return None
338
+ m = re.fullmatch(r"<[^>]+> (?:is|are) the (leftmost|rightmost)", s)
339
+ if m:
340
+ return _place(a, 1 if m.group(1) == "leftmost" else n)
341
+ m = re.fullmatch(r"<[^>]+> (?:is|are|hangs?|sits?|stands?) (?:the )?" + ORDINAL + r" from the (left|right)", s)
342
+ if m:
343
+ k = _position(m.group(1), n)
344
+ return _place(a, None if k is None else (k if m.group(2) == "left" else n + 1 - k))
345
+ m = re.fullmatch(r"<[^>]+> (?:finished|departs|leaves|arrives) " + ORDINAL, s)
346
+ if m:
347
+ return _place(a, _position(m.group(1), n))
348
+ m = re.fullmatch(r"<[^>]+> lives on the (top|bottom) floor", s)
349
+ if m:
350
+ return _place(a, n if m.group(1) == "top" else 1)
351
+ m = re.fullmatch(r"<[^>]+> lives on the " + ORDINAL + r" floor from the (bottom|top)", s)
352
+ if m:
353
+ k = _position(m.group(1), n)
354
+ return _place(a, None if k is None else (k if m.group(2) == "bottom" else n + 1 - k))
355
+ m = re.fullmatch(r"<[^>]+> (?:is|are) the (?:(\w+)-)?(" + "|".join(sorted(EARLY | LATE, key=len, reverse=True)) +
356
+ ")", s)
357
+ if m:
358
+ k = 1 if m.group(1) is None else _position(m.group(1), n)
359
+ return _place(a, None if k is None else (k if m.group(2) in EARLY else n + 1 - k))
360
+ return None
361
+
362
+
363
+ def order(request, question):
364
+ source = body(request)
365
+ found = _objects(source)
366
+ if not found:
367
+ return None
368
+ names, end = found
369
+ sentences = [s for s in re.split(r"(?<=\.)\s+", source[end:]) if s.strip()]
370
+ tests = []
371
+ for s in sentences:
372
+ test = _statement(s, names)
373
+ if test is None:
374
+ return None
375
+ if test is not True:
376
+ tests.append(test)
377
+ if not tests:
378
+ return None
379
+ arrangements = [o for o in itertools.permutations(names) if all(t(o) for t in tests)]
380
+ if len(arrangements) != 1:
381
+ return None
382
+ only = arrangements[0]
383
+ true = []
384
+ for key, description in options_of(question):
385
+ test = _statement(re.sub(r"^\(?[A-Za-z]\)\s*:?\s*", "", description), names)
386
+ if test is None or test is True:
387
+ return None
388
+ if test(only):
389
+ true.append(key)
390
+ return true[0] if len(true) == 1 else None
391
+
392
+
393
+ # ---- free time ----------------------------------------------------------------------------------------------------
394
+
395
+ def _hour(value):
396
+ m = re.fullmatch(r"(\d{1,2})(?::(\d\d))?\s*(am|pm)", value.strip().lower())
397
+ if not m:
398
+ return None
399
+ hour = int(m.group(1)) % 12 + (12 if m.group(3) == "pm" else 0)
400
+ return hour + int(m.group(2) or 0) / 60
401
+
402
+
403
+ def free_time(request, question):
404
+ source = body(request)
405
+ woke = re.search(r"woke up at (\d{1,2}(?::\d\d)?\s*[ap]m)", source)
406
+ closed = re.search(r"was closed after (\d{1,2}(?::\d\d)?\s*[ap]m)", source)
407
+ if not woke or not closed:
408
+ return None
409
+ begin, finish = _hour(woke.group(1)), _hour(closed.group(1))
410
+ spans = re.findall(r"from (\d{1,2}(?::\d\d)?\s*[ap]m) to (\d{1,2}(?::\d\d)?\s*[ap]m)", source)
411
+ busy = [(_hour(a), _hour(b)) for a, b in spans]
412
+ if begin is None or finish is None or not busy or any(a is None or b is None for a, b in busy):
413
+ return None
414
+ free = []
415
+ for key, description in options_of(question):
416
+ m = re.fullmatch(r"\s*(\d{1,2}(?::\d\d)?\s*[ap]m) to (\d{1,2}(?::\d\d)?\s*[ap]m)\s*", description)
417
+ if not m:
418
+ return None
419
+ a, b = _hour(m.group(1)), _hour(m.group(2))
420
+ if a is None or b is None:
421
+ return None
422
+ if begin <= a and b <= finish and all(b <= s or a >= e for s, e in busy):
423
+ free.append(key)
424
+ return free[0] if len(free) == 1 else None
425
+
426
+
427
+ # ---- adjective order ---------------------------------------------------------------------------------------------
428
+
429
+ KINDS = (
430
+ ("opinion", "good bad nice lovely wonderful terrible awful obnoxious repulsive silly ridiculous mysterious "
431
+ "adorable beautiful ugly fantastic awesome terrific excellent fine gorgeous horrible pleasant strange "
432
+ "weird"),
433
+ ("size", "big small tiny enormous huge massive large little midsize medium-size short tall long wide giant"),
434
+ ("age", "old new ancient old-fashioned brand-new archaic vintage young modern antique"),
435
+ ("shape", "square circular triangular rectangular spherical prismlike pyramidal round oval flat"),
436
+ ("colour", "red blue green yellow black white gray grey brown purple pink orange aqua cyan magenta teal violet tan "
437
+ "maroon indigo crimson beige"),
438
+ ("origin", "american chinese japanese german french brazilian mexican indian russian egyptian ethiopian filipino "
439
+ "turkish vietnamese thai nigerian pakistani iranian congolese bangladeshi indonesian polish british "
440
+ "english italian spanish canadian korean swedish norwegian danish dutch greek irish scottish "
441
+ "australian argentine argentinian chilean peruvian colombian cuban kenyan ghanaian moroccan "
442
+ "portuguese swiss austrian belgian hungarian czech ukrainian israeli syrian iraqi saudi lebanese "
443
+ "malaysian singaporean"),
444
+ ("material", "wool woolen plastic glass paper leather cloth wood wooden steel iron rubber fiberglass silver gold "
445
+ "lead cardboard cotton silk stone metal brass copper bronze ceramic"),
446
+ ("purpose", "smoking hiking drinking eating exercise walking typing snorkeling whittling cooking driving "
447
+ "swimming sleeping reading writing cleaning"),
448
+ )
449
+ RANK = {word: i for i, (_, words) in enumerate(KINDS) for word in words.split()}
450
+
451
+
452
+ def adjectives(request, question):
453
+ source = body(request)
454
+ if "adjective order" not in source.lower():
455
+ return None
456
+ ordered = []
457
+ for key, description in options_of(question):
458
+ words = description.strip().rstrip(".").split()
459
+ if len(words) < 3:
460
+ return None
461
+ ranks = [RANK.get(w.lower()) for w in words[:-1]]
462
+ if any(r is None for r in ranks):
463
+ return None
464
+ if all(a <= b for a, b in zip(ranks, ranks[1:])):
465
+ ordered.append(key)
466
+ return ordered[0] if len(ordered) == 1 else None
467
+
468
+
469
+ SOLVERS = (("boolean", boolean), ("liars", liars), ("route", route), ("swaps", swaps), ("order", order),
470
+ ("free_time", free_time), ("adjectives", adjectives))
471
+
472
+
473
+ def propose(request, key):
474
+ """(option key, case) or None."""
475
+ if not isinstance(request.state, str) and not isinstance(request.data, dict):
476
+ return None
477
+ question = request.questions[key]
478
+ for case, solve in SOLVERS:
479
+ try:
480
+ found = solve(request, question)
481
+ except (ValueError, KeyError, IndexError, TypeError, AttributeError, re.error):
482
+ found = None
483
+ if found is not None:
484
+ return found, case
485
+ return None
486
+
487
+
488
+ def describe(case):
489
+ return CASES.get(case, case)