-
Notifications
You must be signed in to change notification settings - Fork 58
/
macros.py
executable file
·2082 lines (1749 loc) · 54.9 KB
/
macros.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 binascii
import cmath
import collections.abc
import copy
import datetime
import fractions
import functools
import hashlib
import itertools
import math
import numbers
import operator
import random
import re
import string
import sys
import time
import urllib.request
from ast import literal_eval
import zlib
from data import c_to_f
# Type checking
def is_num(a):
return isinstance(a, numbers.Number)
def is_seq(a):
return isinstance(a, collections.abc.Sequence)
def is_col(a):
return isinstance(a, collections.abc.Iterable)
def is_hash(a):
return isinstance(a, collections.abc.Hashable)
def is_lst(a):
return isinstance(a, list) or isinstance(a, tuple)
# Error handling
class BadTypeCombinationError(Exception):
def __init__(self, func, *args):
self.args = args
self.func = func
def __str__(self):
error_message = "\nError occured in function: %s" % self.func
for i in range(len(self.args)):
arg = self.args[i]
arg_type = str(type(arg)).split("'")[1]
error_message += "\nArg %d: %r, type %s." % (i + 1, arg, arg_type)
return error_message
# Itertools type normalization
def itertools_norm(func, a, *args, **kwargs):
if isinstance(a, str):
return ["".join(group) for group in func(a, *args, **kwargs)]
if isinstance(a, set):
return [set(group) for group in func(a, *args, **kwargs)]
else:
return [list(group) for group in func(a, *args, **kwargs)]
def unknown_types(func, name, *args):
if len(args) == 1:
a, = args
if is_seq(a) and not (isinstance(a, str) and len(a) == 1):
return list(map(func, a))
if len(args) == 2:
a, b = args
if is_seq(a) and not (isinstance(a, str) and len(a) == 1):
return list(map(lambda left:func(left, b), a))
elif is_seq(b) and not (isinstance(b, str) and len(b) == 1):
return list(map(lambda right:func(a, right), b))
raise BadTypeCombinationError(name, *args)
# The environment in which the generated Python code is run.
# All functions and all variables must be added to it.
environment = {}
# Infinite Iterator. Used in .f, .V
def infinite_iterator(start):
def successor(char):
if char.isalpha():
if char == 'z':
return 'a', True
if char == 'Z':
return 'A', True
return chr(ord(char) + 1), False
elif char.isdigit():
if char == '9':
return '0', True
return chr(ord(char) + 1), False
else:
return chr(ord(char) + 1), False
if is_num(start):
while True:
yield start
start += 1
# Replicates the behavior of ruby's .succ
if isinstance(start, str):
while True:
yield start
alphanum_locs = [loc for loc in range(len(start))
if start[loc].isalnum() and ord(start[loc]) < 128]
if alphanum_locs:
locs = alphanum_locs[::-1]
elif start:
locs = range(len(start))[::-1]
else:
locs = []
succ_char = 'a'
for inc_loc in locs:
inc_char = start[inc_loc]
succ_char, carry = successor(inc_char)
start = start[:inc_loc] + succ_char + start[inc_loc + 1:]
if not carry:
break
else:
start = succ_char + start
raise BadTypeCombinationError("infinite_iterator, probably .V", start)
environment['infinite_iterator'] = infinite_iterator
# memoizes function calls, key = repr of input.
class memoized(object):
def __init__(self, func):
self.func = func
self.cache = {}
def __call__(self, *args):
args_repr = repr(args)
if args_repr in self.cache:
return self.cache[args_repr]
else:
value = self.func(*args)
self.cache[args_repr] = value
return value
environment['memoized'] = memoized
# If argument is a number, turn it into a range.
def num_to_range(arg):
if isinstance(arg, int) and arg > 0:
return range(arg)
if is_num(arg):
return urange(arg)
return arg
environment['num_to_range'] = num_to_range
# Implicit print
def imp_print(a):
if a is not None:
print(a)
return a
environment['imp_print'] = imp_print
# F on unary function. Repeated application.
def repeat(func, start, repetitions):
if not isinstance(repetitions, int):
raise BadTypeCombinationError("F", repetitions, start)
value = start
for _ in range(repetitions):
value = func(value)
return value
environment['repeat'] = repeat
# F on binary function. Fold.
def fold(func, lst):
if func == environment[c_to_f['*'][0]]:
if not lst:
return 1
if not is_col(lst):
return factorial(lst)
if not lst:
if func == environment[c_to_f['+'][0]]:
return []
else:
return 0
return reduce2(func, lst)
environment['fold'] = fold
# Lookup from the environment, ignoring lambdas.
def env_lookup(var):
return environment[var]
environment['env_lookup'] = env_lookup
# Function library. See data for letter -> function correspondences.
# =. N/A
def assign(a, b):
if isinstance(a, str):
if len(a) == 1:
environment[a] = copy.deepcopy(b)
return environment[a]
else:
var_names = a.strip('[]').split(',')
if is_seq(b) and len(var_names) == len(b) == 2 and \
all(len(var_name) == 1 for var_name in var_names):
output = []
for var_name, item in zip(var_names, b):
environment[var_name] = copy.deepcopy(item)
output.append(environment[var_name])
return output
raise BadTypeCombinationError("=", a, b)
environment['assign'] = assign
# ~. N/A
def post_assign(a, b):
if isinstance(a, str):
if len(a) == 1:
old_a = environment[a]
environment[a] = copy.deepcopy(b)
return old_a
raise BadTypeCombinationError("~", a, b)
environment['post_assign'] = post_assign
# !. All.
def Pnot(a):
return not a
environment['Pnot'] = Pnot
# @.
def lookup(a, b):
if is_num(a) and is_num(b):
return a ** (1 / b)
if isinstance(a, dict):
if isinstance(b, list):
b = tuple(b)
return a[b]
if is_seq(a) and isinstance(b, int):
return a[b % len(a)]
if is_col(a) and is_col(b):
if isinstance(a, str):
intersection = [b_elem for b_elem in b
if isinstance(b_elem, str) and b_elem in a]
else:
intersection = [b_elem for b_elem in b if b_elem in a]
if isinstance(a, str):
return ''.join(intersection)
if isinstance(a, set):
return set(intersection)
else:
return list(intersection)
return unknown_types(lookup, "@", a, b)
environment['lookup'] = lookup
# %. int, str.
def mod(a, b):
if isinstance(a, int) and is_seq(b):
return b[::a]
if isinstance(a, complex) and is_num(b):
return (a.real % b) + (a.imag % b) * 1j
if is_num(a) and is_num(b):
return a % b
if isinstance(a, str):
if is_lst(b):
return a % tuple(b)
else:
return a % b
return unknown_types(mod, "%", a, b)
environment['mod'] = mod
# ^. int, str, list.
def Ppow(a, b):
if is_num(a) and is_num(b):
return pow(a, b)
if is_col(a) and isinstance(b, int):
return itertools_norm(itertools.product, a, repeat=b)
return unknown_types(Ppow, "^", a, b)
environment['Ppow'] = Ppow
# *. int, str, list.
def times(a, b):
if is_col(a) and is_col(b):
prod = list(itertools.product(a, b))
if isinstance(a, str) and isinstance(b, str):
return[''.join(pair) for pair in prod]
else:
return [list(pair) for pair in prod]
if is_num(a) and is_num(b):
return a * b
if isinstance(a, int) and is_seq(b):
return a * b
if is_seq(a) and isinstance(b, int):
if b < 0:
return -b * a[::-1]
else:
return a * b
return unknown_types(times, "*", a, b)
environment['times'] = times
# (. All types
def Ptuple(*a):
return a
environment['Ptuple'] = Ptuple
# -. int, set.
def minus(a, b):
if is_num(a) and is_num(b):
return a - b
if is_num(a) and is_col(b):
if isinstance(b, str):
return minus(str(a), b)
if is_lst(b):
return minus([a], b)
if isinstance(b, set):
return minus({a}, b)
if is_num(b) and is_col(a):
if isinstance(a, str):
return minus(a, str(b))
if is_lst(a):
return minus(a, [b])
if isinstance(a, set):
return minus(a, {b})
if is_col(a) and is_col(b):
if isinstance(b, str):
difference = [c for c in a if not isinstance(c, str) or c not in b]
else:
difference = [c for c in a if c not in b]
if isinstance(a, str):
return ''.join(difference)
if is_lst(a):
return list(difference)
if isinstance(a, set):
return set(difference)
return unknown_types(minus, "-", a, b)
environment['minus'] = minus
# '. str.
def read_file(a):
if isinstance(a, str):
if any(a.lower().endswith("." + i) for i in
["png", "jpg", "jpeg", "gif", "svg", "ppm", "pgm", "pbm"]):
from PIL import Image
img = Image.open(a)
data = list(img.getdata())
# If alpha all 255, take out alpha
if len(data[0]) > 3 and all(i[3] == 255 for i in data):
data = [i[:3] for i in data]
# Check grayscale
if all(i.count(i[0]) == len(i) for i in data):
data = [i[0] for i in data]
data = chop(data, img.size[0])
return data
if a.startswith("http"):
b = list(map(str, urllib.request.urlopen(a)))
else:
b = open(a)
b = [lin[:-1] if lin[-1] == '\n' else lin for lin in b]
return b
return unknown_types(read_file, "'", a)
environment['read_file'] = read_file
# _. All.
def neg(a):
if is_num(a):
return -a
if is_seq(a):
return a[::-1]
if isinstance(a, dict):
return {value: key for key, value in a.items()}
return unknown_types(neg, "_", a)
environment['neg'] = neg
# {. All.
def uniquify(a):
if is_seq(a):
try:
seen = set()
out = []
for elem in a:
if not elem in seen:
out.append(elem)
seen.add(elem)
except TypeError:
out = []
for elem in a:
if not elem in out:
out.append(elem)
if isinstance(a, str):
return ''.join(out)
return out
if is_col(a):
return sorted(a)
return unknown_types(uniquify, '{', a)
environment['uniquify'] = uniquify
# }. in
def Pin(a, b):
if isinstance(a, int) and isinstance(b, int):
if a < b:
return list(range(a, b + 1))
return list(range(b, a + 1))[::-1]
if is_col(b):
return a in b
return unknown_types(Pin, '}', a, b)
environment['Pin'] = Pin
# +. All.
def plus(a, b):
if isinstance(a, set):
if is_col(b):
return a.union(b)
else:
return a.union({b})
if is_lst(a) and not is_lst(b):
return list(a) + [b]
if is_lst(b) and not is_lst(a):
return [a] + list(b)
if is_lst(a) and is_lst(b):
return list(a) + list(b)
if is_num(a) and is_num(b) or\
isinstance(a, str) and isinstance(b, str):
return a + b
if is_num(a) and isinstance(b, str):
return str(a) + b
if isinstance(a, str) and is_num(b):
return a + str(b)
return unknown_types(plus, "+", a, b)
environment['plus'] = plus
# [. All.
def Plist(*a):
return list(a)
environment['Plist'] = Plist
# ]. All.
def singleton(a):
return [a]
environment['singleton'] = singleton
# :. list.
def at_slice(a, b, c=0):
if isinstance(a, str) and isinstance(b, str):
if isinstance(c, str):
return re.sub(b, c, a)
if c == 0:
return bool(re.search(b, a))
if c == 1:
return [m.group(0) for m in re.finditer(b, a)]
if c == 2:
def first_group(matchobj):
return matchobj.group(1)
return re.sub(b, first_group, a)
if c == 3:
return re.split(b, a)
if c == 4:
return [[m.group(0)] + list(m.groups()) for m in re.finditer(b, a)]
return unknown_types(at_slice, ":", a, b, c)
if is_seq(a) and isinstance(b, int) and isinstance(c, int):
return a[slice(b, c)]
if is_num(a) and is_num(b) and is_num(c):
if c > 0:
work = a
gen_range = []
if a <= b:
def cont_test(work):
return work < b
step = c
else:
def cont_test(work):
return work > b
step = -c
while cont_test(work):
gen_range.append(work)
work += step
return gen_range
elif c < 0:
return at_slice(b, a, -c)[::-1]
# There is no nice ABC for this check.
if hasattr(a, "__getitem__") and is_col(b):
if is_col(c):
rep_c = itertools.cycle(c)
else:
rep_c = itertools.repeat(c)
if isinstance(a, str) or isinstance(a, tuple):
indexable = list(a)
else:
indexable = a
for repl_index in b:
if isinstance(a, str):
indexable[repl_index] = str(next(rep_c))
else:
indexable[repl_index] = next(rep_c)
if isinstance(a, str):
return "".join(indexable)
return indexable
return unknown_types(at_slice, ":", a, b, c)
environment['at_slice'] = at_slice
# <. All.
def lt(a, b):
if isinstance(a, set) and is_col(b):
return a.issubset(b) and a != b
if is_seq(a) and isinstance(b, int):
return a[:b]
if isinstance(a, int) and is_seq(b):
if a >= len(b):
if isinstance(b, str):
return ''
else:
return []
return b[:len(b) - a]
if isinstance(a, complex) or isinstance(b, complex):
return abs(a) < abs(b)
if is_num(a) and is_num(b) or\
isinstance(a, list) and isinstance(b, list) or\
isinstance(a, tuple) and isinstance(b, tuple) or\
isinstance(a, str) and isinstance(b, str):
return a < b
return unknown_types(lt, "<", a, b)
environment['lt'] = lt
# >. All.
def gt(a, b):
if isinstance(a, set) and is_col(b):
return a.issuperset(b) and a != b
if is_seq(a) and isinstance(b, int):
return a[b:]
if isinstance(a, int) and is_seq(b):
if a >= len(b):
return b
return b[len(b) - a:]
if isinstance(a, complex) or isinstance(b, complex):
return abs(a) > abs(b)
if is_num(a) and is_num(b) or\
isinstance(a, list) and isinstance(b, list) or\
isinstance(a, tuple) and isinstance(b, tuple) or\
isinstance(a, str) and isinstance(b, str):
return a > b
return unknown_types(gt, ">", a, b)
environment['gt'] = gt
# /. All.
def div(a, b):
if is_num(a) and is_num(b):
return int(a // b)
if is_seq(a):
return a.count(b)
return unknown_types(div, "/", a, b)
environment['div'] = div
# a. List, Set.
def append(a, b):
if isinstance(a, list):
a.append(b)
return a
if isinstance(a, set):
if is_hash(b):
a.add(b)
return a
else:
a.add(tuple(b))
return a
if is_num(a) and is_num(b):
return abs(a - b)
return unknown_types(append, "a", a, b)
environment['append'] = append
environment['b'] = "\n"
# c. All
def chop(a, b=None):
if is_num(a) and is_num(b):
return a / b
if isinstance(a, str) and isinstance(b, str):
return a.split(b)
if isinstance(a, str) and b is None:
return a.split()
# iterable, int -> chop a into pieces of length b
if is_seq(a) and isinstance(b, int):
return [a[i:i + b] for i in range(0, len(a), b)]
# int, iterable -> split b into a pieces (distributed equally)
if isinstance(a, int) and is_seq(b):
m = len(b) // a # min number of elements
r = len(b) % a # remainding elements
begin_ind, end_ind = 0, m + (r > 0)
l = []
for i in range(a):
l.append(b[begin_ind:end_ind])
begin_ind, end_ind = end_ind, end_ind + m + (i + 1 < r)
return l
# seq, col of ints -> chop seq at number locations.
if is_seq(a) and is_col(b):
if all(isinstance(elem, int) for elem in b) and not isinstance(b, str):
locs = sorted(b)
return [a[i:j] for i, j in zip([0] + locs, locs + [len(a)])]
if is_seq(a):
output = [[]]
for elem in a:
if elem == b:
output.append([])
else:
output[-1].append(elem)
return output
return unknown_types(chop, "c", a, b)
environment['chop'] = chop
# C. int, str.
def Pchr(a):
if isinstance(a, int):
try:
return chr(a)
except (ValueError, OverflowError):
return ''.join(chr(digit) for digit in from_base_ten(a, 256))
if isinstance(a, complex):
return a.real - a.imag * 1j
if is_num(a):
return Pchr(int(a))
if isinstance(a, str):
return to_base_ten([ord(char) for char in a], 256)
if is_col(a):
trans = list(zip(*a))
if all(isinstance(sublist, str) for sublist in a):
return [''.join(row) for row in trans]
else:
return [list(row) for row in trans]
return unknown_types(Pchr, "C", a)
environment['Pchr'] = Pchr
environment['d'] = ' '
# e. All.
def end(a):
if isinstance(a, complex):
return a.imag
if is_num(a):
return a % 10
if is_seq(a):
return a[-1]
return unknown_types(end, "e", a)
environment['end'] = end
# E.
def eval_input():
return literal_eval(input())
environment['eval_input'] = eval_input
# f. single purpose.
def Pfilter(a, b=1):
if is_num(b):
return next(counter for counter in itertools.count(b) if a(counter))
if is_col(b):
return list(filter(a, b))
return unknown_types(Pfilter, "f", a, b)
environment['Pfilter'] = Pfilter
environment['G'] = string.ascii_lowercase
# g. All.
def gte(a, b):
if isinstance(a, set) and is_col(b):
return a.issuperset(b)
if is_seq(a) and isinstance(b, int):
return a[b - 1:]
if is_num(a) and is_num(b) or\
isinstance(a, list) and isinstance(b, list) or\
isinstance(a, tuple) and isinstance(b, tuple) or\
isinstance(a, str) and isinstance(b, str):
return a >= b
return unknown_types(gte, "g", a, b)
environment['gte'] = gte
environment['H'] = {}
# h. int, str, list.
def head(a):
if is_num(a):
return a + 1
if is_seq(a):
return a[0]
return unknown_types(head, "h", a)
environment['head'] = head
# i. int, str
def base_10(a, b):
if isinstance(a, str) and isinstance(b, int):
if not a:
return 0
return int(a, b)
if is_seq(a) and is_num(b):
return to_base_ten(a, b)
if isinstance(a, int) and isinstance(b, int):
return fractions.gcd(a, b)
return unknown_types(base_10, "i", a, b)
environment['base_10'] = base_10
def to_base_ten(arb, base):
# Special cases
if abs(base) == 1:
return len(arb)
if len(arb) < 2:
return arb[0] if arb else 0
digits = []
it = iter(arb)
if len(arb) % 2 != 0:
digits.append(next(it))
for digit in it:
digits.append(digit * base + next(it))
return to_base_ten(digits, base * base)
# j. str.
def join(a, b=None):
if b is None:
a, b = '\n', a
if isinstance(a, int) and isinstance(b, int):
return from_base_ten(a, b)
if isinstance(a, str) and is_col(b):
return a.join(list(map(str, b)))
if is_col(b):
return str(a).join(list(map(str, b)))
return unknown_types(join, "j", a, b)
environment['join'] = join
def from_base_ten(arb, base):
# Special cases
if arb == 0:
return [0]
if abs(base) == 1:
return [0] * arb
# Main routine
base_list = []
it = reversed(from_base_ten(arb, base * base) if abs(arb) >= abs(base) else [arb])
digit = next(it)
clock = 0
work = 0
while clock >= 0 or work != 0:
if clock == 0:
work += digit
try:
digit = next(it)
clock = 2
except StopIteration:
digit = 0
clock -= 1
work, remainder = divmod(work, base)
if remainder < 0:
work += 1
remainder -= base
if work == -1 and base > 0:
work = 0
remainder -= base
base_list.append(remainder)
return base_list[::-1]
environment['k'] = ''
# l. any
def Plen(a):
if is_num(a):
if isinstance(a, complex) or a < 0:
return cmath.log(a, 2)
return math.log(a, 2)
if is_col(a):
return len(a)
return unknown_types(Plen, "l", a)
environment['Plen'] = Plen
# m. Single purpose.
def Pmap(a, b):
if is_num(b):
return list(map(a, urange(b)))
if is_col(b):
return list(map(a, b))
return unknown_types(Pmap, "m", a, b)
environment['Pmap'] = Pmap
environment['N'] = '"'
# n. All.
def ne(a, b):
return not equal(a, b)
environment['ne'] = ne
# O. int, str, list
def rchoice(a):
if isinstance(a, int):
if a == 0:
return random.random()
if a < 0:
random.seed(-a)
return
if a > 0:
return random.randrange(a)
if is_num(a):
# random.uniform works for both complex and float
return random.uniform(0, a)
if is_seq(a):
return random.choice(a)
if is_col(a):
return random.choice(list(a))
return unknown_types(rchoice, "O", a)
environment['rchoice'] = rchoice
# o. Single purpose.
def order(a, b):
if is_num(b):
b = urange(b)
if is_col(b):
if isinstance(b, str):
return ''.join(sorted(b, key=a))
else:
return sorted(b, key=a)
return unknown_types(order, "o", a, b)
environment['order'] = order
# P. int, str, list.
def primes_pop(a):
if isinstance(a, int):
if a < 0:
# Primality testing
return len(primes_pop(-a)) == 1
if a < 2:
return []
def simple_factor(a):
working = a
output = []
num = 2
while num * num <= working:
while working % num == 0:
output.append(num)
working //= num
num += 1
if working != 1:
output.append(working)
return output
if a < 10 ** 4:
return simple_factor(a)
else:
try:
from sympy import factorint
factor_dict = factorint(a)
factors_with_mult = [[fact for _ in range(
factor_dict[fact])] for fact in factor_dict]
return sorted(sum(factors_with_mult, []))
except:
return simple_factor(a)
if is_num(a):
return cmath.phase(a)
if is_seq(a):
return a[:-1]
return unknown_types(primes_pop, "P", a)
environment['primes_pop'] = primes_pop
# p. All.
def Pprint(a):
print(a, end='')
return a
environment['Pprint'] = Pprint
# q. All.
def equal(a, b):
return a == b
environment['equal'] = equal
# r. int, int or str,int.
def Prange(a, b):
def run_length_encode(a):
return [[len(list(group)), key] for key, group in itertools.groupby(a)]
if isinstance(b, int):
if isinstance(a, str):
if b == 0:
return a.lower()
if b == 1:
return a.upper()
if b == 2:
return a.swapcase()
if b == 3:
return a.title()
if b == 4:
return a.capitalize()
if b == 5:
return string.capwords(a)
if b == 6:
return a.strip()
if b == 7:
return [Pliteral_eval(part) for part in a.split()]
if b == 8:
return run_length_encode(a)
if b == 9:
# Run length decoding, format "<num><char><num><char>",
# e.g. "12W3N6S1E"
return re.sub(r'(\d+)(\D)',
lambda match: int(match.group(1))
* match.group(2), a)
if is_seq(a):
if b == 8:
return run_length_encode(a)
if b == 9:
if all(isinstance(key, str) for group_size, key in a):
return ''.join(key * group_size for group_size, key in a)
else:
return sum(([copy.deepcopy(key)] * group_size
for group_size, key in a), [])
return unknown_types(Prange, "r", a, b)
if isinstance(a, int):
if a < b:
return list(range(a, b))
else:
return list(range(a, b, -1))
return unknown_types(Prange, "r", a, b)
if isinstance(a, str) and isinstance(b, str):
a_val = Pchr(a)
b_val = Pchr(b)
ab_range = Prange(a_val, b_val)
return [''.join(chr(char_val) for char_val in join(str_val, 256))
for str_val in ab_range]
if isinstance(a, int) and is_seq(b):
return Prange(b, a)
return unknown_types(Prange, "r", a, b)
environment['Prange'] = Prange
# s. int, str, list.
def Psum(a):
if is_col(a) and not isinstance(a, str):
if len(a) == 0:
return 0
if all(isinstance(elem, str) for elem in a):
return ''.join(a)
if len(a) > 100:
cutoff = len(a) // 2
first = a[:cutoff]
second = a[cutoff:]
return plus(Psum(first), Psum(second))
return reduce(lambda b, c: plus(b, c), a[1:], a[0])
if isinstance(a, complex):
return a.real