forked from microsoft/PythonProgrammingPuzzles
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuman_eval.py
More file actions
5457 lines (4250 loc) · 169 KB
/
human_eval.py
File metadata and controls
5457 lines (4250 loc) · 169 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Problems inspired by [HumanEval dataset](https://github.com/openai/human-eval) described
in the [codex paper](https://arxiv.org/abs/2107.03374), specifically,
[this](https://github.com/openai/human-eval/blob/fa06031e684fbe1ee429c7433809460c159b66ad/data/HumanEval.jsonl.gz)
version released 7/7/21."""
from puzzle_generator import PuzzleGenerator, Tags
from typing import List
"""
Some came out especially nicely as puzzles:
ParenthesesPermutation, Derivative, Frac, HeronTriangle, RomanNumerals, ClosestPalindrome, WildSort, Intersperse,
SimplifyProductFraction, Fib4, DiffChars, RotateString, EvaluateOperators, Grader, TripleZeroSum, PrimeFib
Some weren't such natural puzzles:
CircularShiftNum, ReplaceMe, MinSubArraySum, Buckets, OddEvenSum, FindStrangeSum, EvenSqure, StrongestExtension
HungryRabbits, ReverseCase, MatchBrackets, ListTotal, BelowThreshold, RemoveVowels
In many cases, the original problem wasn't naturally a puzzle but it inspired a nice loosely-related puzzle:
ZobristCollision, EvenBetween, MinSquaredDeviation, Median
"""
# See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles
class FindCloseElements(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#0"""
@staticmethod
def sat(pair: List[float], nums=[0.17, 21.3, 5.0, 9.0, 11.0, 4.99, 17.0, 17.0, 12.4, 6.8]):
"""
Given a list of numbers, find the two closest distinct numbers in the list.
Sample Input:
[1.2, 5.23, 0.89, 21.0, 5.28, 1.2]
Sample Output:
[5.23, 5.28]
"""
a, b = pair
assert a in nums and b in nums and a != b
return abs(a - b) == min(x - y for x in nums for y in nums if x > y)
@staticmethod
def sol(nums):
s = sorted(set(nums))
return min([[a, b] for a, b in zip(s, s[1:])], key=lambda x: x[1] - x[0])
def gen_random(self):
nums = [self.random.uniform(-10, 10) for _ in range(self.random.randrange(2, 10))]
nums.append(self.random.choice(nums))
self.random.shuffle(nums)
self.add(dict(nums=nums))
class SeparateParenGroups(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#1"""
@staticmethod
def sat(ls: List[str], combined='() (()) ((() () ())) (() )'):
"""
Given a string consisting of whitespace and groups of matched parentheses, split it
into groups of perfectly matched parentheses without any whitespace.
Sample Input:
'( ()) ((()()())) (()) ()'
Sample Output:
['(())', '((()()()))', '(())', '()']
"""
for s in ls:
assert s.count("(") == s.count(")")
assert all(s[:i].count("(") > s[:i].count(")") for i in range(1, len(s))) # s is not further divisible
return ''.join(ls) == combined.replace(' ', '')
@staticmethod
def sol(combined):
cur = ''
ans = []
depth = 0
for c in combined.replace(' ', ''):
cur += c
if c == '(':
depth += 1
else:
assert c == ')'
depth -= 1
if depth == 0:
ans.append(cur)
cur = ''
return ans
def gen_random(self):
depth = 0
combined = ''
while depth > 0 or self.random.random() > 0.2:
c = self.random.choice('()) ' if depth > 0 else '( ')
if c == '(':
depth += 1
elif c == ')':
depth -= 1
combined += c
self.add(dict(combined=combined))
class Frac(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#2"""
@staticmethod
def sat(x: float, v=523.12892):
"""
Given a floating point number, find its fractional part.
Sample Input:
4.175
Sample Output:
0.175
"""
return 0 <= x < 1 and (v - x).is_integer()
@staticmethod
def sol(v):
return v % 1.0
def gen_random(self):
v = self.random.uniform(-100, 100)
self.add(dict(v=v))
class FirstNegCumulative(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#3"""
@staticmethod
def sat(firsts: List[int], balances=[[2, 7, -2, 4, 3, -15, 10, -45, 3], [3, 4, -17, -1], [100, -100, -101], [-1]]):
"""
Given a list of numbers which represent bank deposits and withdrawals, find the *first* negative balance.
Sample Input:
[[12, -5, 3, -99, 14, 88, -99], [-1, 2, 5]]
Sample Output:
[-89, -1]
"""
for i, bals in enumerate(balances):
total = 0
for b in bals:
total += b
if total < 0:
assert total == firsts[i]
break
return True
@staticmethod
def sol(balances):
firsts = []
for bals in balances:
total = 0
for b in bals:
total += b
if total < 0:
firsts.append(total)
break
return firsts
def gen_random(self):
balances = [
[self.random.randrange(-10 ** 10, 10 ** 10) for _ in range(self.random.randrange(1, 11))]
for _ in range(10)
]
balances = [bals for bals in balances if any(sum(bals[:i + 1]) < 0 for i in range(len(bals)))]
self.add(dict(balances=balances))
class MinSquaredDeviation(PuzzleGenerator):
"""
Loosely inspired by [HumanEval](https://github.com/openai/human-eval) \\#4
The HumanEval problem was simply to compute the mean absolute deviation. This problem is more interesting.
It requires minimizing the sum of squared deviations, which turns out to be the mean `mu`. Moreover, if
`mu` is the mean of the numbers then a simple calculation shows that:
`sum((mu - n) ** 2 for n in nums) == sum((m - n) ** 2 for m in nums for n in nums) / (2 * len(nums))`
We use 0.501 rather than 1/2 to deal with rounding errors.
"""
@staticmethod
def sat(x: float, nums=[12, -2, 14, 3, -15, 10, -45, 3, 30]):
"""
Given a list of numbers, find x that minimizes mean squared deviation.
Sample Input:
[4, -5, 17, -9, 14, 108, -9]
Sample Output:
17.14285
"""
return sum((n - x) ** 2 for n in nums) * len(nums) <= sum((m - n) ** 2 for m in nums for n in nums) * .5 + 1e-4
@staticmethod
def sol(nums):
return sum(nums) / len(nums) # mean minimizes mean squared deviation
def gen_random(self):
length = self.random.randrange(1, 11)
nums = [self.random.randrange(-100, 100) for _ in range(length)]
self.add(dict(nums=nums))
class Intersperse(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#5"""
@staticmethod
def sat(li: List[int], nums=[12, 23, -2, 5, 0], sep=4):
"""
Given a list of numbers and a number to inject, create a list containing that number in between each pair of
adjacent numbers.
Sample Input:
[8, 14, 21, 17, 9, -5], 3
Sample Output:
[8, 3, 14, 3, 21, 3, 17, 3, 9, 3, -5]
"""
return li[::2] == nums and li[1::2] == [sep] * (len(nums) - 1)
@staticmethod
def sol(nums, sep):
ans = [sep] * (2 * len(nums) - 1)
ans[::2] = nums
return ans
def gen_random(self):
length = self.random.randrange(10)
nums = [self.random.randrange(100) for _ in range(length)]
sep = self.random.randrange(100)
self.add(dict(nums=nums, sep=sep))
class DeepestParens(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#6"""
@staticmethod
def sat(depths: List[int], parens='() (()) ((()()())) (((((((())))))))'):
"""
Given a string consisting of groups of matched nested parentheses separated by parentheses,
compute the depth of each group.
Sample Input:
'(()) ((()()())) (()) ()'
Sample Output:
[2, 3, 2, 1]
"""
groups = parens.split()
for depth, group in zip(depths, groups):
budget = depth
success = False
for c in group:
if c == '(':
budget -= 1
if budget == 0:
success = True
assert budget >= 0
else:
assert c == ')'
budget += 1
assert success
return len(groups) == len(depths)
@staticmethod
def sol(parens):
def max_depth(s):
m = 0
depth = 0
for c in s:
if c == '(':
depth += 1
m = max(m, depth)
else:
assert c == ')'
depth -= 1
assert depth == 0
return m
return [max_depth(s) for s in parens.split()]
def gen_random(self):
def gen_group():
ans = ''
depth = 0
while depth > 0 or ans == '' or self.random.random() > 0.2:
c = self.random.choice('())') if depth > 0 else '('
if c == '(':
depth += 1
elif c == ')':
depth -= 1
ans += c
return ans
parens = " ".join(gen_group() for _ in range(self.random.randrange(6)))
self.add(dict(parens=parens))
class FindContainers(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#7"""
@staticmethod
def sat(containers: List[str], strings=['cat', 'dog', 'shatter', 'bear', 'at', 'ta'], substring='at'):
"""
Find the strings in a list containing a given substring
Sample Input:
['cat', 'dog', 'bear'], 'a'
Sample Output:
['cat', 'bear']
"""
i = 0
for s in strings:
if substring in s:
assert containers[i] == s
i += 1
return i == len(containers)
@staticmethod
def sol(strings, substring):
return [s for s in strings if substring in s]
def gen_random(self):
substring = self.random.pseudo_word(min_len=0, max_len=3)
def gen():
n = self.random.choice([1, 2])
return substring.join([self.random.pseudo_word(min_len=0, max_len=5) for _ in range(n)])
strings = [gen() for _ in range(self.random.randrange(6))]
self.add(dict(strings=strings, substring=substring))
class SumProduct(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#8"""
@staticmethod
def sat(nums: List[int], tot=14, prod=99):
"""
Find a list of numbers with a given sum and a given product.
Sample Input:
12, 32
Sample Output:
[2, 8, 2]
"""
assert sum(nums) == tot
p = 1
for n in nums:
p *= n
return p == prod
@staticmethod
def sol(tot, prod):
ans = [prod]
while sum(ans) > tot:
ans += [-1, -1]
ans += [1] * (tot - sum(ans))
return ans
def gen_random(self):
tot = self.random.randrange(-100, 100)
prod = self.random.randrange(-100, 100)
self.add(dict(tot=tot, prod=prod))
class RollingMax(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#9"""
@staticmethod
def sat(maxes: List[int], nums=[1, 4, 3, -6, 19]):
"""
Find a list whose ith element is the maximum of the first i elements of the input list.
Sample Input:
[2, 8, 2]
Sample Output:
[2, 8, 8]
"""
assert len(maxes) == len(nums)
for i in range(len(nums)):
if i > 0:
assert maxes[i] == max(maxes[i - 1], nums[i])
else:
assert maxes[0] == nums[0]
return True
@staticmethod
def sol(nums):
return [max(nums[:i]) for i in range(1, len(nums) + 1)]
@staticmethod
def sol2(nums):
ans = []
if nums:
m = nums[0]
for n in nums:
m = max(n, m)
ans.append(m)
return ans
def gen_random(self):
nums = [self.random.randrange(-100, 100) for _ in range(self.random.randrange(10))]
self.add(dict(nums=nums))
class PalindromeContaining(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#10"""
@staticmethod
def sat(ans: str, s="so easy", length=20):
"""
Find a palindrome of a given length containing a given string.
Sample Input:
"abba", 6
Sample Output:
"cabbac"
"""
return ans == ans[::-1] and len(ans) == length and s in ans
@staticmethod
def sol(s, length):
ls = list(s)
for i in range(length - len(s) + 1):
arr = ['x'] * length
arr[i:i + len(s)] = ls
a = length - i - 1
b = length - (i + len(s)) - 1
if b == -1:
b = None
arr[a:b:-1] = ls
if arr == arr[::-1]:
ans = "".join(arr)
if s in ans:
return ans
assert False, "shouldn't reach here"
def gen_random(self):
part = "".join([self.random.choice("ab") for _ in range(self.random.randrange(20))])
pal = part + self.random.choice([part, part[:-1]])[::-1]
n = self.random.randrange(len(pal) + 1)
m = self.random.randrange(n + 1)
s = pal[m:n]
self.add(dict(s=s, length=len(pal)))
class BinaryStrXOR(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#11"""
@staticmethod
def sat(str_num: str, nums=["100011101100001", "100101100101110"]):
"""
Find a the XOR of two given strings interpreted as binary numbers.
Sample Input:
"0001", "1011"
Sample Output:
"1010"
"""
a, b = nums
return int(str_num, 2) == int(a, 2) ^ int(b, 2)
@staticmethod
def sol(nums):
a, b = nums
ans = int(a, 2) ^ int(b, 2)
return format(ans, "b")
def gen_random(self):
nums = [format(self.random.randrange(1024), "b") for _ in range(2)]
self.add(dict(nums=nums))
# In the HumanEval dataset, tie breaking needs to be specified because each problem must have a unique answer
class LongestStr(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#12"""
@staticmethod
def sat(ans: str, words=["these", "are", "some", "pretty", "long", "words"]):
"""
Find the longest of a list of strings
Sample Input:
["cat", "dog", "sheep", "chimp"]
Sample Output:
"sheep"
"""
return ans in words and all(len(ans) >= len(w) for w in words)
@staticmethod
def sol(words):
return max(words, key=len)
def gen_random(self):
words = [self.random.pseudo_word() for _ in range(self.random.randrange(1, 10))]
self.add(dict(words=words))
class CertifiedGCD(PuzzleGenerator):
"""
Inspired by [HumanEval](https://github.com/openai/human-eval) \\#13
"""
@staticmethod
def sat(ans: List[int], m=200004931, n=66679984):
"""
Find the greatest common divisor of two integers m, n and a certificate a, b such that m*a + n*b = gcd
Sample Input:
20, 30
Sample Output:
10, -1, 1
"""
gcd, a, b = ans
return m % gcd == n % gcd == 0 and a * m + b * n == gcd and gcd > 0
@staticmethod
def sol(m, n):
"""
Derivation of solution below
Recursive solution guarantees a * (big % small) + b * small == gcd
Let d = big // small so (big % small) == big - small * d
gives a * (big - small * d) + b * small == gcd
or equivalently (b - a * d) * small + a * big == gcd
"""
def gcd_cert(small, big):
"""Returns gcd, a, b, such that small * a + big * b == gcd"""
assert 0 < small <= big
if big % small == 0:
return [small, 1, 0]
gcd, a, b = gcd_cert(big % small, small)
return [gcd, b - a * (big // small), a]
if m < n:
return gcd_cert(m, n)
gcd, a, b = gcd_cert(n, m)
return [gcd, b, a]
def gen_random(self):
factor, r1, r2 = [1 + self.random.randrange(10 ** self.random.randrange(10)) for _ in range(3)]
m = r1 * factor
n = r2 * factor
self.add(dict(m=m, n=n))
class AllPrefixes(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#14"""
@staticmethod
def sat(prefixes: List[str], s="donesezichethofalij"):
"""
Find all prefixes of a given string
Sample Input:
"aabcd"
Sample Output:
["", "a", "aa", "aab", "aabc", "aabcd"]
"""
return all(s.startswith(p) for p in prefixes) and len(set(prefixes)) > len(s)
@staticmethod
def sol(s):
return [s[:i] for i in range(len(s) + 1)]
def gen_random(self):
s = self.random.pseudo_word(min_len=0, max_len=30)
self.add(dict(s=s))
class SpaceyRange(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#15"""
@staticmethod
def sat(ans: str, n=15):
"""
Find a string consisting of the non-negative integers up to n inclusive
Sample Input:
4
Sample Output:
'0 1 2 3 4'
"""
return [int(i) for i in ans.split(' ')] == list(range(n + 1))
@staticmethod
def sol(n):
return ' '.join(str(i) for i in range(n + 1))
def gen_random(self):
n = self.random.randrange(10 ** 5)
self.add(dict(n=n))
class DistinctChars(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#16"""
@staticmethod
def sat(ans: List[str], s='The quick brown fox jumps over the lazy dog!', n=28):
"""
Find the set of distinct characters in a string, ignoring case
Sample Input:
'HELlo', 4
Sample Output:
['h', 'e', 'l', 'o']
"""
assert all(ans.count(c.lower()) == 1 for c in s)
assert all(c == c.lower() for c in ans)
assert all(c in s.lower() for c in ans)
return True
@staticmethod
def sol(s, n):
return list(set(s.lower()))
def gen_random(self):
s = self.random.string()
s = s[0].upper() + s[1:]
n = len(set(s.lower()))
self.add(dict(s=s, n=n))
class ParseMusic(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#17"""
@staticmethod
def sat(beats: List[int], score="o o o| o| .| .| .| o| o| o o o| .|"):
"""
Parse a string of notes to beats, 'o'=4, 'o|'=2, '.|'=1
Example input:
'o o .| o|'
Example output:
[4, 4, 1, 2]
"""
return " ".join({1: '.|', 2: 'o|', 4: 'o'}[b] for b in beats) == score
@staticmethod
def sol(score):
mapping = {'.|': 1, 'o|': 2, 'o': 4}
return [mapping[note] for note in score.split()]
def gen_random(self):
n = self.random.randrange(12)
score = ' '.join(self.random.choice(['.|', 'o|', 'o']) for _ in range(n))
self.add(dict(score=score))
class OverlappingCount(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#18"""
@staticmethod
def sat(ans: List[int], s='Bananannanaannanaanananananana', sub='anan', count=7):
"""
Find occurrences of a substring in a parent string *including overlaps*
Sample Input:
'helllo', 'll'
Sample Output:
[2, 3]
"""
return all(sub == s[i:i + len(sub)] and i >= 0 for i in ans) and len(set(ans)) >= count
@staticmethod
def sol(s, sub, count):
ans = []
for i in range(len(s) + 1):
if s[i:i + len(sub)] == sub:
ans.append(i)
return ans
def gen_random(self):
s = self.random.pseudo_word(max_len=100)
j = self.random.randrange(1, len(s) + 1)
i = self.random.randrange(j)
sub = s[i:j]
count = len(self.sol(s, sub, None))
self.add(dict(s=s, sub=sub, count=count))
class SortNumbers(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#19"""
@staticmethod
def sat(ans: str, s="six one four three two nine eight"):
"""
Sort numbers based on strings
Sample input
---
"six one four"
Sample output
---
"one four six"
"""
nums = 'zero one two three four five six seven eight nine'.split()
return [nums.index(x) for x in ans.split(" ")] == sorted([nums.index(x) for x in s.split(" ")])
@staticmethod
def sol(s):
nums = 'zero one two three four five six seven eight nine'.split()
arr = [nums.index(x) for x in s.split()]
arr.sort()
ans = " ".join([nums[i] for i in arr])
return ans
def gen_random(self):
nums = 'zero one two three four five six seven eight nine'.split()
n = self.random.randrange(3, 9)
ans = ""
for _ in range(n):
ans += self.random.choice(nums) + " "
ans = ans[:-1]
s = ans
self.add(dict(s=s))
class FindClosePair(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#20"""
@staticmethod
def sat(inds: List[int], nums=[0.31, 21.3, 5.0, 9.0, 11.0, 5.01, 17.2]):
"""
Given a list of numbers, find the indices of the closest pair.
Sample Input:
[1.2, 5.25, 0.89, 21.0, 5.23]
Sample Output:
[4, 1]
"""
a, b = inds
assert a != b and a >= 0 and b >= 0
for i in range(len(nums)):
for j in range(i):
assert abs(nums[i] - nums[j]) >= abs(nums[b] - nums[a])
return True
@staticmethod
def sol(nums):
best = [0, 1]
best_score = abs(nums[1] - nums[0])
for i in range(len(nums)):
for j in range(i):
score = abs(nums[i] - nums[j])
if score < best_score:
best_score = score
best = [i, j]
return best
def gen_random(self):
nums = [self.random.uniform(-10, 10) for _ in range(self.random.randrange(2, 10))]
if self.random.random() < 0.2:
nums.append(nums[0])
self.random.shuffle(nums)
self.add(dict(nums=nums))
class Rescale(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#21"""
@staticmethod
def sat(ans: List[float], nums=[13.0, 17.0, 17.0, 15.5, 2.94]):
"""
Rescale and shift numbers so that they cover the range [0, 1]
Sample input
---
[18.5, 17.0, 18.0, 19.0, 18.0]
Sample output
---
[0.75, 0.0, 0.5, 1.0, 0.5]
"""
assert min(ans) == 0.0 and max(ans) == 1.0
a = min(nums)
b = max(nums)
for i in range(len(nums)):
x = a + (b - a) * ans[i]
assert abs(nums[i] - x) < 1e-6
return True
@staticmethod
def sol(nums):
nums = nums.copy()
a = min(nums)
b = max(nums)
if b - a == 0:
return [0.0] + [1.0] * (len(nums) - 1)
for i in range(len(nums)):
nums[i] = (nums[i] - a) / (b - a)
return nums
def gen_random(self):
nums = [self.random.heavy_tail_float() for _ in range(self.random.randrange(2, 10))]
if self.random.random() < 0.2:
nums = [nums[0]] * len(nums)
self.add(dict(nums=nums))
class FilterInts(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#22"""
@staticmethod
def sat(candidates: List[str], int_indices=[2, 4, 7, 9, 101]):
"""
Find a list of strings where the only valid integers are at the given indices
Sample input
---
[2, 4, 5]
Sample output
---
["cat", "2.7", "2", "", "3", "-17", "free"]
"""
for i in int_indices:
int(candidates[i])
for i, s in enumerate(candidates):
if i not in int_indices:
try:
int(s)
return False
except ValueError:
pass
return True
@staticmethod
def sol(int_indices):
if not int_indices:
return []
ans = [""] * (1 + max(abs(i) for i in int_indices))
for i in int_indices:
ans[i] = "17"
return ans
def gen_random(self):
int_indices = [self.random.randrange(100) for _ in range(self.random.randrange(10))]
self.add(dict(int_indices=int_indices))
class StrLength(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#23"""
@staticmethod
def sat(lengths: List[int], strs=["pneumonoultramicroscopicsilicovolcanoconiosis", " ", "foo", "2.5"]):
"""
Find the lengths of a list of non-empty strings
Sample input
---
["foo", "bars"]
Sample output
---
[3, 4]
"""
for length, s in zip(lengths, strs):
try:
s[length]
return False
except IndexError:
s[length - 1]
return len(lengths) == len(strs)
@staticmethod
def sol(strs):
return [len(s) for s in strs]
def gen_random(self):
strs = [self.random.string(min_len=1, max_len=50) for _ in range(10)]
self.add(dict(strs=strs))
class LargestDivisor(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#24"""
@staticmethod
def sat(d: int, n=123456):
"""
Find the largest integer divisor of a number n that is less than n
Sample input
---
1000
Sample output
---
500
"""
return n % d == 0 and d < n and all(n % e for e in range(d + 1, n))
@staticmethod
def sol(n):
return next(d for d in range(n - 1, 0, -1) if n % d == 0)
def gen_random(self):
n = self.random.randrange(1, 10 ** 5)
self.add(dict(n=n))
class PrimeFactorization(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#25"""
@staticmethod
def sat(factors: List[int], n=123456, num_factors=8):
"""
Factor number n into a given number of non-trivial factors
Sample input
---
1000, 6
Sample output
---
[2, 2, 2, 5, 5, 5]
"""
assert len(factors) == num_factors
prod = 1
for d in factors:
prod *= d
assert d > 1
return prod == n
@staticmethod
def sol(n, num_factors):
if num_factors == 0:
return []
if num_factors == 1:
return [n]
ans = []
for d in range(2, n):
while n % d == 0:
n //= d
ans.append(d)
if len(ans) == num_factors - 1:
ans.append(n)
return ans
assert False
def gen_random(self):
num_factors = self.random.randrange(10)
n = 2 ** num_factors
for _ in range(self.random.randrange(10)):
n *= self.random.choice([3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47])
num_factors += 1
self.add(dict(n=n, num_factors=num_factors))
class Dedup(PuzzleGenerator):
"""Inspired by [HumanEval](https://github.com/openai/human-eval) \\#26"""
@staticmethod
def sat(ans: List[int], li=[2, 19, 2, 53, 1, 1, 2, 44, 17, 0, 19, 31]):
"""
Remove duplicates from a list of integers, preserving order
Sample input
---
[1, 3, 2, 9, 2, 1, 55]
Sample output
---
[1, 3, 2, 9, 55]
"""
return set(ans) == set(li) and all(li.index(ans[i]) < li.index(ans[i + 1]) for i in range(len(ans) - 1))
@staticmethod
def sol(li):
seen = set()
ans = []
for n in li:
if n not in seen:
ans.append(n)
seen.add(n)
return ans