-
Notifications
You must be signed in to change notification settings - Fork 47
/
interpreter.py
2786 lines (2644 loc) · 67.4 KB
/
interpreter.py
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
import cmath, copy, functools, itertools, locale, math, operator, re, sys, time
from .utils import attrdict, lazy_import
random, sympy, urllib_request = lazy_import('random sympy urllib.request')
code_page = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶'''
code_page += '''°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''
# Unused symbols for single-byte atoms/quicks: ()kquƁƇƘⱮƬȤɦɱɲƥʠɼʂȥẈẒŻḥḳṇụṿẉỵẓḋėġṅẏ
str_digit = '0123456789'
str_lower = 'abcdefghijklmnopqrstuvwxyz'
str_upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
inf = float('inf')
nan = float('nan')
sys.setrecursionlimit(1 << 30)
def arities(links):
return [link.arity for link in links]
def at_index(index, array):
array = iterable(array)
if not array:
return 0
low_index = math.floor(index) - 1
high_index = math.ceil(index) - 1
if low_index == high_index:
return array[low_index % len(array)]
return [array[low_index % len(array)], array[high_index % len(array)]]
def at_index_ndim(indices, array):
retval = array
for index in indices:
retval = at_index(index, retval)
return retval
def base_decompression(integer, digits):
digits = iterable(digits, make_range=True)
return [digits[i-1] for i in to_base(integer, len(digits))]
def bounce(array):
return array[:-1] + array[::-1]
def carmichael(n):
n = int(n)
if n < 1:
return 0
c = 1
for p, k in sympy.ntheory.factor_.factorint(n).items():
c = lcm(c, 2 ** (k - 2) if p == 2 < k else (p - 1) * p ** (k - 1))
return c
def create_chain(chain, arity = -1, isForward = True):
return attrdict(
arity = arity,
chain = chain,
call = lambda x = None, y = None: variadic_chain(chain, isForward and (x, y) or (y, x))
)
def create_literal(string):
return attrdict(
arity = 0,
call = lambda: python_eval(string, False)
)
def conv_dyadic_integer(link, larg, rarg):
try:
iconv_larg = int(larg)
try:
iconv_rarg = int(rarg)
return link(iconv_larg, iconv_rarg)
except:
return iconv_larg
except:
try:
return int(rarg)
except:
return 0
def conv_monadic_integer(link, arg):
try:
return link(int(arg))
except:
return 0
def convolve(left, right):
left, right = iterable(left, make_range = True), iterable(right, make_range = True)
result = [0]*(len(left)+len(right)-1)
for i,x in enumerate(left):
for j,y in enumerate(right):
result[i+j] += x*y
return result
def copy_to(atom, value):
atom.call = lambda: value
return value
def determinant(matrix):
matrix = sympy.Matrix(matrix)
if matrix.is_square:
return simplest_number(matrix.det())
return simplest_number(math.sqrt((matrix * matrix.transpose()).det()))
def div(dividend, divisor, floor = False):
if divisor == 0:
return dividend * inf
if divisor == inf:
return 0
if floor or (type(dividend) == int and type(divisor) == int and not dividend % divisor):
return int(dividend // divisor)
return dividend / divisor
def depth(link):
if type(link) != list:
return 0
if not link:
return 1
return 1 + max(map(depth, link))
def diagonals(matrix):
shifted = [None] * len(matrix)
for index, row in enumerate(map(iterable, reversed(matrix))):
shifted[~index] = index * [None] + row
return rotate_left(zip_ragged(shifted), len(matrix) - 1)
def distinct_sieve(array):
array = iterable(array, make_digits = True)
result = []
for (i, x) in enumerate(array):
result.append(1 if i == array.index(x) else 0)
return result
def dot_product(left, right):
left, right = iterable(left), iterable(right)
if complex in map(type, left + right):
right = [complex(t).conjugate() for t in right]
product = sum(dyadic_link(atoms['×'], (left, right)))
if product.imag == 0:
product = product.real
if type(product) != int and product.is_integer():
product = int(product)
return product
def dyadic_chain(chain, args):
larg, rarg = args
for link in chain:
if link.arity < 0:
link.arity = 2
if chain and arities(chain[0:3]) == [2, 2, 2]:
ret = dyadic_link(chain[0], args)
chain = chain[1:]
elif leading_nilad(chain):
ret = niladic_link(chain[0])
chain = chain[1:]
else:
ret = larg
while chain:
if arities(chain[0:3]) == [2, 2, 0] and leading_nilad(chain[2:]):
ret = dyadic_link(chain[1], (dyadic_link(chain[0], (ret, rarg)), niladic_link(chain[2])))
chain = chain[3:]
elif arities(chain[0:2]) == [2, 2]:
ret = dyadic_link(chain[0], (ret, dyadic_link(chain[1], args)))
chain = chain[2:]
elif arities(chain[0:2]) == [2, 0]:
ret = dyadic_link(chain[0], (ret, niladic_link(chain[1])))
chain = chain[2:]
elif arities(chain[0:2]) == [0, 2]:
ret = dyadic_link(chain[1], (niladic_link(chain[0]), ret))
chain = chain[2:]
elif chain[0].arity == 2:
ret = dyadic_link(chain[0], (ret, rarg))
chain = chain[1:]
elif chain[0].arity == 1:
ret = monadic_link(chain[0], ret)
chain = chain[1:]
else:
output(ret)
ret = niladic_link(chain[0])
chain = chain[1:]
return ret
def dyadic_link(link, args, conv = True, lflat = False, rflat = False):
larg, rarg = args
lflat = lflat or not hasattr(link, 'ldepth')
rflat = rflat or not hasattr(link, 'rdepth')
larg_depth = lflat or depth(larg)
rarg_depth = rflat or depth(rarg)
if (lflat or link.ldepth == larg_depth) and (rflat or link.rdepth == rarg_depth):
if conv and hasattr(link, 'conv'):
return link.conv(link.call, larg, rarg)
return link.call(larg, rarg)
conv = conv and hasattr(link, 'conv')
if not lflat and larg_depth < link.ldepth:
return dyadic_link(link, ([larg], rarg))
if not rflat and rarg_depth < link.rdepth:
return dyadic_link(link, (larg, [rarg]))
if not rflat and (lflat or larg_depth - rarg_depth < link.ldepth - link.rdepth):
return [dyadic_link(link, (larg, y)) for y in rarg]
if not lflat and (rflat or larg_depth - rarg_depth > link.ldepth - link.rdepth):
return [dyadic_link(link, (x, rarg)) for x in larg]
return [dyadic_link(link, (x, y)) for x, y in zip(*args)] + larg[len(rarg) :] + rarg[len(larg) :]
def equal(array):
array = iterable(array)
return int(all(item == array[0] for item in array))
def extremes(min_or_max, link, array):
x,y = array
x = iterable(x, make_range=True)
if not x:
return []
results = [variadic_link(link, (t, y)) for t in x]
best = min_or_max(results)
return [t for t, ft in zip(x, results) if ft == best]
def filter_array(sand, mesh, is_in = True):
mesh = {repr(element) for element in iterable(mesh)}
return [element for element in iterable(sand) if (repr(element) in mesh) == is_in]
def flatten(argument):
flat = []
if type(argument) == list:
for item in argument:
flat += flatten(item)
else:
flat.append(argument)
return flat
def foldl(*args):
return reduce(*args, arity = 2)
def from_base(digits, base):
integer = 0
for digit in digits:
integer = base * integer + digit
return integer
def from_diagonals(diagonals):
upper_right = 1
while len(diagonals[upper_right - 1]) > 1:
upper_right += 1
diagonals = rotate_left(diagonals, upper_right)
shift = len(diagonals) - upper_right
index = 0
while shift:
diagonals[index] = shift * [None] + diagonals[index]
index += 1
shift -= 1
return zip_ragged(diagonals)
def from_exponents(exponents):
integer = 1
for index, exponent in enumerate(exponents):
integer *= sympy.ntheory.generate.prime(index + 1) ** exponent
return integer
def from_factorial_base(digits):
placeValue = 1
integer = 0
for nextPlaceIndex, digit in enumerate(digits[::-1], 1):
integer += digit * placeValue
placeValue *= nextPlaceIndex
return integer
def from_primorial_base(digits):
integer = digits and digits[-1] or 0
for placeIndex, digit in enumerate(digits[-2::-1], 1):
integer += digit * sympy.ntheory.generate.primorial(placeIndex)
return integer
def simplest_number(number):
if abs(number ** 2) != number ** 2:
return number
if number % 1:
return float(number)
return int(number)
def get_request(url):
url = ''.join(map(str, url))
url = (re.match(r"[A-Za-z][A-Za-z0-9+.-]*:https://", url) == None and "https://" or "") + url
response = urllib_request.request.urlopen(url).read()
try:
return response.decode('utf-8')
except:
return response.decode('latin-1')
def grid(array):
if depth(array) == 1:
return join(array, ' ')
if depth(array) == 2 and equal(map(len, array)):
array = [[str(entry) for entry in row] for row in array]
width = max(max([len(entry) for entry in row]) if row else 0 for row in array)
array = [[list(entry.rjust(width)) for entry in row] for row in array]
return join([join(row, ' ') for row in array], '\n')
if depth(array) == 3 and all(type(item) == str for item in flatten(array)):
array = [[''.join(entry) for entry in row] for row in array]
width = max(max([len(entry) for entry in row]) if row else 0 for row in array)
array = [[list(entry.ljust(width)) for entry in row] for row in array]
return join([join(row, ' ') for row in array], '\n')
return join(array, '\n')
def group(array):
array = iterable(array, make_digits = True)
grouped = {}
for index, item in enumerate(array):
item = repr(item)
if item in grouped:
grouped[item].append(index + 1)
else:
grouped[item] = [index + 1]
try:
return [grouped[key] for key in sorted(grouped, key = eval)]
except TypeError:
return [grouped[key] for key in sorted(grouped)]
def group_equal(array):
array = iterable(array, make_digits = True)
groups = []
for x in array:
if groups and groups[-1][0] == x:
groups[-1].append(x)
else:
groups.append([x])
return groups
def identity(argument):
return argument
def iterable(argument, make_copy = False, make_digits = False, make_range = False):
the_type = type(argument)
if the_type == list:
return copy.deepcopy(argument) if make_copy else argument
if the_type != str and make_digits:
return to_base(argument, 10)
if the_type != str and make_range:
return list(range(1, int(argument) + 1))
return [argument]
def index_of(haystack, needle):
for index, item in enumerate(iterable(haystack)):
if item == needle:
return 1 + index
return 0
def isqrt(number):
a = number
b = (a + 1) // 2
while b < a:
a = b
b = (a + number // a) // 2
return int(a)
def is_palindrome(argument):
argument = iterable(argument, make_digits = True)
return int(argument == argument[::-1])
def is_string(argument):
if type(argument) != list:
return False
return all(map(lambda t: type(t) == str, argument))
def jelly_eval(code, arguments):
return variadic_chain(parse_code(code)[-1] if code else '', arguments)
def jelly_uneval(argument, top = True):
the_type = type(argument)
if the_type in (float, int):
return jelly_uneval_real(argument)
if the_type == complex:
return jelly_uneval_real(argument.real) + 'ı' + jelly_uneval_real(argument.imag)
if the_type == str:
return '”' + argument
if all(map(is_string, argument)):
strings = [''.join(string) for string in argument]
if all(map(lambda t: code_page.find(t) < 250, ''.join(strings))):
return '“' + '“'.join(strings) + '”'
if is_string(argument):
string = ''.join(argument)
if all(map(lambda t: code_page.find(t) < 250, string)):
return '“' + string + '”'
middle = ','.join(jelly_uneval(item, top = False) for item in argument)
return middle if top else '[' + middle + ']'
def jelly_uneval_real(number):
string = str(number if number % 1 else int(number))
return string.lstrip('0') if number else string
def jellify(element, dirty = False):
if element is None:
return []
if type(element) == str and dirty:
return list(element)
if type(element) in (int, float, complex) or (type(element) == str and len(element) == 1):
return element
try:
return [jellify(item, dirty) for item in element]
except:
if element.is_integer:
return int(element)
if element.is_real:
return float(element)
return complex(element)
def join(array, glue):
array = iterable(array, make_copy = True)
last = array.pop() if array else []
glue = iterable(glue)
ret = []
for item in array:
ret += iterable(item) + glue
return ret + iterable(last)
def last_input():
if len(sys.argv) > 3:
return python_eval(sys.argv[-1])
return python_eval(input())
def leading_nilad(chain):
return chain and arities(chain) + [1] < [0, 2] * len(chain)
def lcm(x, y):
return x * y // (math.gcd(x, y) or 1)
def loop_until_loop(link, args, return_all = False, return_loop = False):
ret, rarg = args
cumret = []
while True:
cumret.append(ret)
larg = ret
ret = variadic_link(link, (larg, rarg))
rarg = larg
if ret in cumret:
if return_all:
return cumret
if return_loop:
return cumret[index_of(cumret, ret) - 1 :]
return larg
def nfind(links, args):
larg, rarg = args
larg = larg or 0
matches = variadic_link(links[1], args) if len(links) == 2 else last_input()
found = []
while len(found) < matches:
if variadic_link(links[0], (larg, rarg)):
found.append(larg)
larg += 1
return found
def matrix_to_list(matrix):
return [[simplest_number(entry) for entry in row] for row in matrix.tolist()]
def max_arity(links):
return max(arities(links)) if min(arities(links)) > -1 else (~max(arities(links)) or -1)
def maximal_indices(iterable):
maximum = max(iterable or [0])
return [u + 1 for u, v in enumerate(iterable) if v == maximum]
def median(array):
array = sorted(array)
return div(array[(len(array) - 1) // 2] + array[len(array) // 2], 2)
def mode(array):
frequencies = {}
maxfreq = 0
retval = []
for element in array:
string = repr(element)
frequencies[string] = frequencies.get(string, 0) + 1
maxfreq = max(frequencies[string], maxfreq)
for element in array:
string = repr(element)
if frequencies[string] == maxfreq:
retval.append(element)
frequencies[string] = 0
return retval
def modinv(a, m):
i, _, g = sympy.numbers.igcdex(a, m)
return i % m if g == 1 else 0
def modulus(dividend, divisor):
try:
return dividend % divisor
except:
return nan
def mold(content, shape):
for index in range(len(shape)):
if type(shape[index]) == list:
mold(content, shape[index])
else:
item = content.pop(0)
shape[index] = item
content.append(item)
return shape
def monadic_chain(chain, arg):
init = True
ret = arg
larg_save = atoms['⁸'].call
while True:
if init:
for link in chain:
if link.arity < 0:
link.arity = 1
if leading_nilad(chain):
ret = niladic_link(chain[0])
chain = chain[1:]
init = False
if not chain:
break
if arities(chain[0:2]) == [2, 1]:
ret = dyadic_link(chain[0], (ret, monadic_link(chain[1], arg)))
chain = chain[2:]
elif arities(chain[0:2]) == [2, 0]:
ret = dyadic_link(chain[0], (ret, niladic_link(chain[1])))
chain = chain[2:]
elif arities(chain[0:2]) == [0, 2]:
ret = dyadic_link(chain[1], (niladic_link(chain[0]), ret))
chain = chain[2:]
elif chain[0].arity == 2:
ret = dyadic_link(chain[0], (ret, arg))
chain = chain[1:]
elif chain[0].arity == 1:
if not chain[1:] and hasattr(chain[0], 'chain'):
arg = ret
chain = chain[0].chain
atoms['⁸'].call = lambda literal = arg: literal
init = True
else:
ret = monadic_link(chain[0], ret)
chain = chain[1:]
else:
output(ret)
ret = niladic_link(chain[0])
chain = chain[1:]
atoms['⁸'].call = larg_save
return ret
def monadic_link(link, arg, flat = False, conv = True):
flat = flat or not hasattr(link, 'ldepth')
arg_depth = flat or depth(arg)
if flat or link.ldepth == arg_depth:
if conv and hasattr(link, 'conv'):
return link.conv(link.call, arg)
return link.call(arg)
conv = conv and hasattr(link, 'conv')
if link.ldepth > arg_depth:
return monadic_link(link, [arg], conv = conv)
return [monadic_link(link, z, conv = conv) for z in arg]
def multiset_difference(left, right):
result = iterable(left)[::-1]
for element in iterable(right):
if element in result:
result.remove(element)
return result[::-1]
def multiset_intersect(left, right):
right = iterable(right, make_copy = True)
result = []
for element in iterable(left):
if element in right:
result.append(element)
right.remove(element)
return result
def multiset_symdif(left, right):
return multiset_union(multiset_difference(left, right), multiset_difference(right, left))
def multiset_union(left, right):
return iterable(left) + multiset_difference(right, left)
def nCr(left, right):
if type(left) == int and type(right) == int:
if right < 0:
right = left - right
if right < 0 or (left > 0 and right > left):
return 0
if left > 0:
right = min(right, left - right)
result = 1
for i in range(right):
result = result * (left - i) // (i + 1)
return result
return div(Pi(left), Pi(left - right) * Pi(right))
def niladic_chain(chain):
while len(chain) == 1 and hasattr(chain[0], 'chain'):
chain = chain[0].chain
if not chain or chain[0].arity > 0:
return monadic_chain(chain, 0)
return monadic_chain(chain[1:], chain[0].call())
def niladic_link(link):
return link.call()
def ntimes(links, args, cumulative = False):
ret, rarg = args
repetitions = variadic_link(links[1], args) if len(links) == 2 else last_input()
repetitions = overload((int, bool), repetitions)
if cumulative:
cumret = [0] * repetitions
for index in range(repetitions):
if cumulative:
cumret[index] = ret
larg = ret
ret = variadic_link(links[0], (larg, rarg))
rarg = larg
return cumret + [ret] if cumulative else ret
def order(number, divisor):
if number == 0 or abs(divisor) == 1:
return inf
if divisor == 0:
return 0
ret = 0
while True:
number, residue = divmod(number, divisor)
if residue:
break
ret += 1
return ret
def overload(operators, *args):
for operator in operators:
try:
ret = operator(*args)
except:
pass
else:
return ret
def integer_partitions(n, I=1):
result = [[n,]]
for i in range(I, n//2 + 1):
for p in integer_partitions(n-i, i):
result.append([i,] + p)
return result
def neighbors(links, array):
array = iterable(array, make_digits = True)
chain = dyadic_chain if links[-1].arity == 2 else monadic_chain
return [chain(links, list(pair)) for pair in zip(array, array[1:])]
def partitions(array):
array = iterable(array, make_digits = True)
ret = []
for index in range(1, len(array)):
for subarray in partitions(array[index:]):
subarray.insert(0, array[:index])
ret.append(subarray)
ret.append([array])
return ret
def parse_code(code):
lines = regex_flink.findall(code)
links = [[] for line in lines]
for index, line in enumerate(lines):
chains = links[index]
for word in regex_chain.findall(line):
chain = []
arity, isForward = chain_separators.get(word[0], default_chain_separation)
for token in regex_token.findall(word):
if token in atoms:
chain.append(atoms[token])
elif token in quicks:
popped = []
while not quicks[token].condition(popped) and (chain or chains):
popped.insert(0, chain.pop() if chain else chains.pop())
chain += quicks[token].quicklink(popped, links, index)
elif token in hypers:
x = chain.pop() if chain else chains.pop()
chain.append(hypers[token](x, links))
else:
chain.append(create_literal(regex_liter.sub(parse_literal, token)))
chains.append(create_chain(chain, arity, isForward))
return links
def parse_literal(literal_match):
literal = literal_match.group(0)
if literal[0] in '”⁾':
return repr(literal[1:].replace('¶', '\n'))
elif literal[0] == '“':
if literal[-1] in '«»‘’”':
mode = literal[-1]
literal = literal[:-1]
else:
mode = ''
parsed = literal.split('“')[1:]
if mode == '»':
parsed = [sss(string).replace('¶', '\n') for string in parsed]
elif mode == '‘':
parsed = [[code_page.find(char) for char in string] for string in parsed]
elif mode == '’':
parsed = [from_base([code_page.find(char) + 1 for char in string], 250) for string in parsed]
else:
parsed = [string.replace('¶', '\n') for string in parsed]
if mode not in '‘’':
parsed = [[string] if len(string) == 1 else string for string in parsed]
if len(parsed) == 1:
parsed = parsed[0]
elif literal[0] == '⁽':
parsed = from_base([code_page.find(char) + 1 for char in literal[1:]], 250)
parsed += parsed > 31500 and -62850 or 750
else:
parsed = eval('+ 1j *'.join([
repr(eval('* 10 **'.join(['-1' if part == '-' else (part + '5' if part[-1:] == '.' else part) or repr(2 * index + 1)
for index, part in enumerate(component.split('ȷ'))])) if component else index)
for index, component in enumerate(literal.split('ı'))
]))
return repr(parsed) + ' '
def partition_at(booleans, array, keep_border = True):
booleans = iterable(booleans)
array = iterable(array)
chunks = []
chunk = []
index = 0
while index < len(array):
if index < len(booleans) and booleans[index]:
chunks.append(chunk)
chunk = [array[index]] if keep_border else []
else:
chunk.append(array[index])
index += 1
return chunks + [chunk]
def pemutation_at_index(index, array = None):
result = []
if array is None:
divisor = 1
count = 0
while divisor < index:
count += 1
divisor *= count
values = list(range(1, count + 1))
else:
values = iterable(array, make_copy = True, make_range = True)
try:
divisor = math.factorial(len(values))
except:
divisor = functools.reduce(operator.mul, range(1, len(values) + 1), 1)
index -= 1
index %= divisor
while values:
divisor //= len(values)
quotient, index = divmod(index, divisor)
result.append(values.pop(quotient))
return result
def permutation_index(array):
result = 1
array = iterable(array)
length = len(array)
for index in range(length):
k = sum(1 for value in array[index + 1:] if value < array[index])
try:
factor = math.factorial(length - index - 1)
except:
factor = functools.reduce(operator.mul, range(1, length - index), 1)
result += k * factor
return result
def Pi(number):
if type(number) == int:
if number < 0:
return inf
try:
return math.factorial(number)
except:
return functools.reduce(operator.mul, range(1, number + 1), 1)
return math.gamma(number + 1)
def powerset(array):
array = iterable(array, make_range = True)
ret = []
for t in range(len(array) + 1):
ret += jellify(itertools.combinations(array, t))
return ret
def prefix(links, outmost_links, index):
ret = [attrdict(arity = max(1, links[0].arity))]
if len(links) == 1:
ret[0].call = lambda x, y = None: [variadic_link(links[0], (t, y)) for t in split_prefix(x)]
else:
ret[0].call = lambda x, y = None: [variadic_link(links[0], (t, y)) for t in split_rolling(x, niladic_link(links[1]))]
return ret
def primerange(start, end):
if start > end:
return list(sympy.primerange(end, start + 1))[::-1]
else:
return list(sympy.primerange(start, end + 1))
def python_eval(string, dirty = True):
try:
return jellify(eval(string), dirty)
except SyntaxError:
exec(string)
return []
def quickchain(arity, min_length):
return attrdict(
condition =
(lambda links: len(links) >= min_length and links[0].arity == 0)
if arity == 0 else
lambda links:
len(links) - sum(map(leading_nilad, split_suffix(links)[:-1])) >= min_length,
quicklink = lambda links, outmost_links, index: [attrdict(
arity = arity,
call = lambda x = None, y = None: variadic_chain(links, (x, y))
)]
)
def random_int(pool):
if not pool:
return 0
if type(pool) == list:
return random.choice(pool)
return random.randint(1, pool)
def reduce(links, outmost_links, index, arity = 1):
ret = [attrdict(arity = arity)]
if len(links) == 1:
ret[0].call = lambda x, *y: reduce_simple(x, links[0], *y)
else:
ret[0].call = lambda x, *y: [reduce_simple(t, links[0], *y) for t in split_fixed(iterable(x), links[1].call())]
return ret
def reduce_simple(array, link, *init):
array = iterable(array)
return functools.reduce(lambda x, y: dyadic_link(link, (x, y)), array, *init)
def reduce_cumulative(links, outmost_links, index):
ret = [attrdict(arity = 1)]
if len(links) == 1:
ret[0].call = lambda t: list(itertools.accumulate(iterable(t), lambda x, y: dyadic_link(links[0], (x, y))))
else:
ret[0].call = lambda z: [reduce_simple(t, links[0]) for t in split_rolling(iterable(z), links[1].call())]
return ret
def rld(runs):
return list(itertools.chain(*[[u] * v for u, v in runs]))
def rle(array):
return [[group[0], len(group)] for group in group_equal(array)]
def rotate_left(array, units):
array = iterable(array)
length = len(array)
return array[units % length :] + array[: units % length] if length else []
def shift_left(number, bits):
if type(number) == int and type(bits) == int:
return number << bits
return number * 2 ** bits
def shift_right(number, bits):
if type(number) == int and type(bits) == int:
return number >> bits
return div(number, 2 ** bits, floor = True)
def shuffle(array):
array = iterable(array, make_copy = True, make_range = True)
random.shuffle(array)
return array
def sparse(link, args, indices):
larg = args[0]
indices = [index - 1 if index > 0 else index - 1 + len(larg) for index in iterable(variadic_link(indices, args))]
ret = iterable(variadic_link(link, args))
return [ret[t % len(ret)] if t in indices else u for t, u in enumerate(larg)]
def split_around(array, needle):
chunk = []
window = len(needle)
index = 0
while index < len(array):
if array[index : index + window] == needle:
yield chunk
chunk = []
index += window
else:
chunk.append(array[index])
index += 1
yield chunk
def split_at(array, needle):
chunk = []
for element in array:
if element == needle:
yield chunk
chunk = []
else:
chunk.append(element)
yield chunk
def split_evenly(array, chunks):
array = iterable(array)
min_width, overflow = divmod(len(array), chunks)
ret = []
high = 0
for index in range(chunks):
low = high
high = low + min_width + (index < overflow)
ret.append(array[low : high])
return ret
def split_fixed(array, width):
if width < 0:
return split_fixed_out(array, -width)
array = iterable(array)
return [array[index : index + width] for index in range(0, len(array), width)]
def split_fixed_out(array, width):
array = iterable(array)
return [array[:index] + array[index + width:] for index in range(0, len(array), width)]
def split_key(control, data):
groups = {}
order = []
count = 0
for key, item in zip(control, data):
key = repr(key) if type(key) == list else key
if key not in groups:
order.append(key)
groups[key] = []
groups[key].append(item)
count += 1
result = [groups[key] for key in order]
if count < len(data):
result.append(data[count:])
return result
def split_once(array, needle):
array = iterable(array, make_digits = True)
index = index_of(array, needle) or len(array)
return [array[0 : index - 1], array[index :]]
def split_prefix(array):
array = iterable(array)
return [array[:index + 1] for index in range(len(array))]
def split_rolling(array, width):
if width < 0:
return split_rolling_out(array, -width)
array = iterable(array)
return [array[index : index + width] for index in range(len(array) - width + 1)]
def split_rolling_out(array, width):
array = iterable(array)
return [array[:index] + array[index + width:] for index in range(len(array) - width + 1)]
def split_suffix(array):
array = iterable(array)
return [array[index:] for index in range(len(array))]
def sss(compressed):
from . import dictionary
decompressed = ''
integer = from_base([code_page.find(char) + 1 for char in compressed], 250)
while integer:
integer, mode = divmod(integer, 3)
if mode == 0:
integer, code = divmod(integer, 96)
decompressed += code_page[code + 32]
else:
flag_swap = False
flag_space = decompressed != ''
if mode == 2:
integer, flag = divmod(integer, 3)
flag_swap = flag != 1
flag_space ^= flag != 0
integer, short = divmod(integer, 2)
the_dictionary = (dictionary.long, dictionary.short)[short]
integer, index = divmod(integer, len(the_dictionary))
word = the_dictionary[index]
if flag_swap:
word = word[0].swapcase() + word[1:]
if flag_space:
word = ' ' + word
decompressed += word
return decompressed
def stringify(iterable, recurse = True):
if type(iterable) != list:
return iterable
if len(iterable) == 1:
return stringify(iterable[0])
if str in map(type, iterable) and not list in map(type, iterable) or not iterable:
return ''.join(map(str, iterable))
iterable = [stringify(item) for item in iterable]
return stringify(iterable, False) if recurse else iterable
def suffix(links, outmost_links, index):