-
Notifications
You must be signed in to change notification settings - Fork 31
/
helpers.py
1566 lines (1291 loc) · 45.7 KB
/
helpers.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
"""This is where the cool functions go that help out stuff.
They aren't directly attached to an element. Consequently, you need to
use type annotations here.
"""
import ast
import collections
import inspect
import itertools
import math # lgtm [py/unused-import]
import re
import string
import textwrap
import types
import unicodedata
from typing import Any, Iterable, List, Optional, Union
import sympy
from sympy.parsing.sympy_parser import (
convert_xor,
implicit_multiplication_application,
standard_transformations,
)
import vyxal.dictionary
import vyxal.encoding
from vyxal import lexer, parse
from vyxal.context import DEFAULT_CTX, Context
from vyxal.LazyList import *
NUMBER_TYPE = "number"
SCALAR_TYPE = "scalar"
VyList = Union[list, LazyList]
VyIterable = Union[str, VyList]
def case_of(value: str) -> int:
"""Returns 1 for all uppercase, 0 for all lowercase, and -1 for
mixed case."""
if all(map(lambda x: x.isupper(), value)):
return 1
elif all(map(lambda x: x.islower(), value)):
return 0
return -1
def chop(it: VyIterable, n: int) -> LazyList:
"""Chop `it` into `n` chunks."""
@lazylist_from(it)
def gen():
nonlocal it
chunk_len = len(it) // n
left_over = len(it) % n
for i in range(n):
length = chunk_len + (1 if left_over > i else 0)
yield it[:length]
it = it[length:]
return gen()
def chunk_while(it: VyList, fun: types.FunctionType, ctx: Context) -> VyList:
"""Chunk a list while a function returns True."""
it = iterable(it, ctx=ctx)
indexable = LazyList(it)
@lazylist_from(it)
def gen():
ind = 0
while indexable.has_ind(ind + fun.arity):
chunk = [indexable[ind]]
while indexable.has_ind(ind + fun.arity) and safe_apply(
fun, *indexable[ind : ind + fun.arity], ctx=ctx
):
chunk.append(indexable[ind + 1])
ind += 1
yield chunk
ind += 1
yield indexable[ind:]
return list(gen())
@lazylist
def collect_until_false(
predicate: types.FunctionType,
function: types.FunctionType,
initial: Any,
ctx: Context,
) -> List[Any]:
"""Given a function, apply it on a given value while a predicate function
returns True. Return the list of values that were collected."""
val = initial
while safe_apply(predicate, val, ctx=ctx):
yield val
val = safe_apply(function, val, ctx=ctx)
def combinations(lst: VyList, size: int) -> VyList:
"""Combinations without replacement"""
if size == 0:
return [[]]
elif isinstance(lst, list):
return vyxalify(itertools.combinations(lst, size))
# Infinite LazyLists won't work with itertools.combinations
@lazylist_from(lst)
def gen():
prev_combs = [[]]
for elem in lst:
new_combs = []
for comb in prev_combs:
if len(comb) == size - 1:
yield comb + [elem]
else:
new_combs.append(comb + [elem])
prev_combs += new_combs
return gen()
def concat(vec1: VyList, vec2: VyList, ctx: Context = DEFAULT_CTX) -> VyList:
"""Concatenate two lists/lazylists"""
if LazyList not in (type(vec1), type(vec2)):
return vec1 + vec2
def gen():
for item in vec1:
yield item
for item in vec2:
yield item
return LazyList(
gen(),
isinf=(
(type(vec1) is LazyList and vec1.infinite)
or (type(vec2) is LazyList and vec2.infinite)
),
)
def count_from(
func: types.FunctionType, start: NUMBER_TYPE, ctx: Context
) -> NUMBER_TYPE:
temp = start
while not safe_apply(func, temp, ctx=ctx):
temp += 1
return temp
def deep_copy(value: Any) -> Any:
"""Because lists and lazylists use memory references. Frick them."""
if type(value) not in (list, LazyList):
return value # because primitives are all like "ooh look at me
# I don't have any fancy memory references because I'm an epic
# chad unlike those virgin memory reference needing lists".
return LazyList(itertools.tee(value)[-1], isinf=is_inf(value))
def dict_to_list(dictionary: dict) -> List[Any]:
"""Returns a dictionary as [[key, value]]"""
return [[str(key), dictionary[key]] for key in dictionary]
def digits(num: NUMBER_TYPE) -> List[int]:
"""Get the digits of a (possibly Rational) number.
This differs from to_base_digits because it works with floats.
This does NOT include signs and decimal points"""
return [int(let) if let not in "-./" else let for let in str(num)]
def drop_while(vec, fun, ctx):
vec = iterable(vec, ctx=ctx)
@lazylist_from(vec)
def gen():
t = True
for item in vec:
if not safe_apply(fun, item, ctx=ctx):
t = False
if not t:
yield item
return gen()
def enumerate_md(
haystack: VyList, _index_stack: tuple = (), include_all=False
) -> VyList:
"""Enumerate multi-dimensional indices and items of a list.
Parameters:
include_str:
Whether nested lists should be included as items too
"""
@lazylist_from(haystack)
def gen():
for i, item in enumerate(haystack):
if type(item) in (list, LazyList):
if not item:
yield [LazyList(_index_stack) + [i], item]
if include_all:
yield [LazyList(_index_stack) + [i], item]
yield from enumerate_md(item, _index_stack + (i,), include_all)
elif type(item) is str and len(item) > 1:
if include_all:
yield [LazyList(_index_stack) + [i], item]
yield from enumerate_md(
LazyList(item), _index_stack + (i,), include_all
)
else:
yield (LazyList(_index_stack) + [i], item)
return gen()
def first_where(
function: types.FunctionType, vector: VyList, ctx: Context
) -> Any:
"""Returns the first element in vector where function returns True"""
for item in vector:
if safe_apply(function, item, ctx=ctx):
return item
return None
@lazylist
def fixed_point(
function: types.FunctionType, initial: Any, ctx: Context
) -> List[Any]:
"""Repeat function until the result is no longer unique.
Uses initial as the initial value"""
previous = None
current = initial
while simplify(previous) != simplify(current):
yield current
previous = deep_copy(current)
current = safe_apply(function, current, ctx=ctx)
def foldl(
function: types.FunctionType,
vector: List[Any],
initial=None,
*,
ctx: Context,
) -> Any:
"""Reduce vector by function"""
working = initial
for item in vector:
if working is None:
working = item
else:
working = safe_apply(function, working, item, ctx=ctx)
return working if working is not None else 0
def format_string(pattern: str, data: VyIterable) -> str:
"""Returns the pattern formatted with the given data. If the data is
a string, then the string is reused if there is more than one % to
be formatted. Otherwise (the data is a list), % are cyclically
substituted"""
ret = ""
index = 0
f_index = 0
while index < len(pattern):
if pattern[index] == "\\":
ret += "\\" + pattern[index + 1]
index += 1
elif pattern[index] == "%":
ret += str(data[f_index % len(data)])
f_index += 1
else:
ret += pattern[index]
index += 1
return ret
def from_base_alphabet(value: str, alphabet: str) -> int:
"""Returns value in base 10 using base len(alphabet)
[bijective base]"""
ret = 0
for digit in value:
ret = len(alphabet) * ret + alphabet.find(digit)
return ret
def from_base_digits(digit_list: List[NUMBER_TYPE], base: int) -> int:
"""Returns digits in base 10 using arbitrary base 'base'"""
# I may have stolen this from Jelly
ret = 0
for digit in digit_list:
ret = base * ret + digit
return ret
def get_input(ctx: Context, explicit=False, evaluated=True) -> Any:
"""Returns the next input depending on where ctx tells to get the
input from."""
if ctx.use_top_input:
if ctx.array_inputs and not explicit:
return vyxalify(ctx.inputs[0][0])
if ctx.inputs[0][0]:
if evaluated:
ret = ctx.inputs[0][0][ctx.inputs[0][1] % len(ctx.inputs[0][0])]
ctx.inputs[0][1] += 1
return vyxalify(ret)
else:
ret = ctx.original_args[
ctx.inputs[0][1] % len(ctx.inputs[0][0])
]
ctx.inputs[0][1] += 1
return ret
else:
try:
temp = input("> " * ctx.repl_mode)
if evaluated:
temp = vy_eval(temp, ctx)
if ctx.empty_input_is_zero and temp == "":
return 0
except Exception: # skipcq: PYL-W0703
temp = 0
return temp
else:
if len(ctx.inputs) == 1:
ctx.use_top_input = True
temp = get_input(ctx)
ctx.use_top_input = False
return vyxalify(temp)
elif ctx.inputs[-1][0]:
ret = ctx.inputs[-1][0][ctx.inputs[-1][1] % len(ctx.inputs[-1][0])]
ctx.inputs[-1][1] += 1
return vyxalify(ret)
else:
return 0
def edges_to_dir_graph(edges: list, ctx: Context) -> dict:
"""Convert a list of edges to a directed graph (as a dictionary)"""
edges = [iterable(edge, ctx) for edge in iterable(edges, ctx)]
graph = {}
for edge in edges:
if len(edge) != 2:
raise ValueError(
"Graph edge expected to be list of 2 elements,"
f"got {edge} instead."
)
if edge[0] in graph:
graph[edge[0]].append(edge[1])
else:
graph[edge[0]] = [edge[1]]
if edge[1] not in graph:
graph[edge[1]] = []
vertices = graph.keys()
if all(
isinstance(vert, int) or (isinstance(vert, float) and int(vert) == vert)
for vert in vertices
):
# If we have just integers, assume the graph vertices are a range
# and fill in the middle disconnected vertices
# TODO make this behavior configurable with flags
min_vert = min_by(vertices, ctx=ctx)
max_vert = max_by(vertices, ctx=ctx)
vertices = LazyList(range(int(min_vert), int(max_vert) + 1))
for vert in vertices:
if vert not in graph:
graph[vert] = []
return graph
def edges_to_undir_graph(edges: list, ctx: Context) -> dict:
"""Convert a list of edges representing an undirected graph to a dictionary"""
edges = [iterable(edge, ctx) for edge in iterable(edges, ctx)]
graph = {}
for edge in edges:
if len(edge) != 2:
raise ValueError(
"Graph edge expected to be list of 2 elements,"
f"got {edge} instead."
)
if edge[0] not in graph:
graph[edge[0]] = []
graph[edge[0]].append(edge[1])
if edge[1] not in graph:
graph[edge[1]] = [edge[0]]
elif edge[0] != edge[1]:
graph[edge[1]].append(edge[0])
vertices = graph.keys()
if all(
isinstance(vert, int)
or ((isinstance(vert, float) or is_sympy(vert)) and int(vert) == vert)
for vert in vertices
):
# If we have just integers, assume the graph vertices are a range
# and fill in the middle disconnected vertices
# TODO make this behavior configurable with flags
min_vert = min_by(vertices, ctx=ctx)
max_vert = max_by(vertices, ctx=ctx)
vertices = LazyList(range(int(min_vert), int(max_vert) + 1))
for vert in vertices:
if vert not in graph:
graph[vert] = []
return graph
def graph_distance(
graph: dict, vert1, vert2, prev: list = []
) -> list[list[int]]:
"""Find the distance from vert1 to vert2 in a directed graph
Parameters:
graph: `dict[Vertex, list[Vertex]]`\\
A dictionary where keys are vertices and values are lists of
neighboring vertices
prev: `list[Vertex]`\\
A list of previously visited vertices, to avoid going in cycles"""
if vert1 == vert2:
return 0
# I know this is the American spelling, but it's shorter than neighbour
neighbors = [neighbor for neighbor in graph[vert1] if neighbor not in prev]
if not neighbors:
return float("inf")
elif vert2 in neighbors:
return 1
else:
new_prev = prev + [vert1]
return 1 + min(
graph_distance(graph, neighbor, vert2, new_prev)
for neighbor in neighbors
)
def group_by_function(
lst: VyList, function: types.FunctionType, ctx: Context
) -> LazyList:
"""Group a list of elements by a function"""
ret = {}
for el in lst:
key = safe_apply(function, el, ctx=ctx)
if key in ret:
ret[key].append(el)
else:
ret[key] = [el]
return list(ret.values())
def group_by_function_ordered(
lst: VyList, function: types.FunctionType, ctx: Context
) -> LazyList:
"""Group a list of elements by a function, but order is preserved"""
ret = []
is_lst = isinstance(lst, LazyList) or isinstance(lst, list)
for el in lst:
k = safe_apply(function, el, ctx=ctx)
if ret == []:
ret.append([k, [el] if is_lst else el])
elif ret[-1][0] == k:
if is_lst:
ret[-1][1].append(el)
else:
ret[-1][1] += el
else:
ret.append([k, [el] if is_lst else el])
return [x[1] for x in ret]
def has_ind(lst: VyList, ind: int) -> bool:
"""Whether or not the list is long enough for that index"""
if isinstance(lst, LazyList):
return lst.has_ind(ind)
else:
return 0 <= ind < len(lst)
def indent_str(string: str, indent: int, end="\n") -> str:
"""Indent a multiline string with 4 spaces, with a newline or `end` afterwards."""
return textwrap.indent(string, " " * indent) + end
def indent_code(*code, indent: int = 1) -> str:
"""Indent multiple lines (`*code`) by the given amount, then join on newlines."""
return "\n".join(indent_str(line, indent, end="") for line in code) + "\n"
def invert_brackets(lhs: str) -> str:
"""
Helper function to swap brackets and parentheses in a string
"""
res = ""
pairs = ["()", "[]", "{}", "<>", "/\\"]
open_close = {x[0]: x[1] for x in pairs}
close_open = {x[1]: x[0] for x in pairs}
for char in lhs:
if char in open_close:
res += open_close[char]
elif char in close_open:
res += close_open[char]
else:
res += char
return res
def is_inf(lst: VyList) -> bool:
"""Whether or not a list/LazyList is infinite"""
return isinstance(lst, LazyList) and lst.infinite
def is_sympy(value):
"""Whether or not this is a Sympy type"""
return isinstance(value, sympy.Basic)
def iterable(
item: Any, number_type: Any = None, ctx: Context = DEFAULT_CTX
) -> Union[LazyList, Union[list, str]]:
"""Turn a value into an iterable"""
item_type = type(item)
if item_type is int or is_sympy(item):
if ctx.number_as_range or number_type is range:
return LazyList(range(ctx.range_start, int(item) + ctx.range_end))
else:
return digits(item)
else:
return item
def join_with(lhs, rhs):
"""A generator to concatenate two iterables together"""
for item in lhs:
yield vyxalify(item)
for item in rhs:
yield vyxalify(item)
def levenshtein_distance(s1: str, s2: str) -> int:
"""Returns the levenshtein distance between two strings"""
# https://stackoverflow.com/a/32558749
if len(s1) > len(s2):
s1, s2 = s2, s1
distances: Iterable[int] = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2 + 1]
for i1, c1 in enumerate(s1):
if c1 == c2:
distances_.append(distances[i1])
else:
distances_.append(
1 + min((distances[i1], distances[i1 + 1], distances_[-1]))
)
distances = distances_
return distances[-1]
def local_minima(lhs: str) -> List[Union[int, float]]:
"""Find the local minima of a mathematical function using Sympy"""
x = sympy.symbols("x")
d_dx = sympy.diff(make_expression(lhs), x)
second_dx = sympy.diff(d_dx, x)
zeros = sympy.solve(d_dx, x)
return LazyList(z for z in zeros if second_dx.subs(x, z) > 0)
def local_maxima(lhs: str) -> List[Union[int, float]]:
"""Find the local minima of a mathematical function using Sympy"""
x = sympy.symbols("x")
d_dx = sympy.diff(make_expression(lhs), x)
second_dx = sympy.diff(d_dx, x)
zeros = sympy.solve(d_dx, x)
return LazyList(z for z in zeros if second_dx.subs(x, z) < 0)
def longest_suffix(a: VyIterable, b: VyIterable) -> VyIterable:
"""Find the longest suffix of a pair of strings or lists.
If bothare strings, the result is a string."""
i = 1
while i <= len(a) and i <= len(b):
if a[-i] == b[-i]:
i += 1
else:
break
i -= 1
if i == 0:
return "" if isinstance(a, str) and isinstance(b, str) else []
else:
return b[-i:] if isinstance(a, str) else a[-i:]
def keep(haystack: Any, needle: Any) -> Any:
"""Used for keeping only needle in haystack"""
if isinstance(haystack, str):
return "".join(char for char in haystack if char in needle)
else:
return LazyList(item for item in haystack if item in needle)
def make_equation(eqn: str) -> sympy:
"""Returns a sympy equation from a string"""
eqn = eqn.split("=")
return sympy.Eq(make_expression(eqn[0]), make_expression(eqn[1]))
def make_expression(expr: str) -> sympy:
"""Turns a string into a nice sympy expression"""
# Normalize the string according to how python normalizes it first
expr = unicodedata.normalize("NFKC", expr)
# Remove all problematic characters from expr
# "\\\"'{}_`" is the set of characters that are problematic
expr = "".join(char for char in expr if char not in "\\\"'{}[]_`")
# Keep only "."s that have numbers on either side
expr = re.sub(r"(\D)\.(\D)", "", expr)
# Remove runs of characters longer than 1
parts = re.split(r"([A-Za-z]+)", expr)
expr = "".join(
part[0] if part and part[0] in string.ascii_letters else part
for part in parts
)
# Substitute some letters for their Sympy equivalents
expr = expr.replace("T", "tan")
expr = expr.replace("S", "sin")
expr = expr.replace("C", "cos")
expr = expr.replace("N", "log")
expr = expr.replace("E", "exp")
expr = expr.replace("I", "integrate")
expr = expr.replace("D", "diff")
transformations = standard_transformations + (
implicit_multiplication_application,
convert_xor,
)
return sympy.parse_expr(expr, transformations=transformations)
def max_by(vec: VyList, key=lambda x: x, cmp=None, ctx=DEFAULT_CTX):
"""
The maximum of a list according to a key function and/or a comparator.
Parameters:
key: Any -> Any
A function to first transform each element of the list before comparing.
cmp: (Any, Any) -> bool
A binary function to check if its first argument is less than the second.
"""
if key is None:
def key(x, ctx=None):
return x
if cmp is None:
def cmp(a, b, ctx=None):
return a > b
if not len(vec):
return 0
return foldl(
lambda a, b, ctx=ctx: a
if safe_apply(
cmp,
safe_apply(key, a, ctx=ctx),
safe_apply(key, b, ctx=ctx),
ctx=ctx,
)
else b,
vec,
ctx=ctx,
)
def min_by(vec: VyList, key=None, cmp=None, ctx=DEFAULT_CTX):
"""
The minimum of a list according to a key function and/or a comparator.
Parameters:
key: Any -> Any
A function to first transform each element of the list before comparing.
cmp: (Any, Any) -> bool
A binary function to check if its first argument is less than the second.
"""
if key is None:
def key(x, ctx=None):
return x
if cmp is None:
def cmp(a, b, ctx=None):
return a < b
if not len(vec):
return 0
return foldl(
lambda a, b, ctx=ctx: a
if cmp(key(a, ctx=ctx), key(b, ctx=ctx), ctx=ctx)
else b,
vec,
ctx=ctx,
)
def mold(content: VyList, shape: VyList) -> VyList:
"""
Mold a list into a shape.
Parameters:
content: VyList
The list to mold.
shape: VyList
The shape to mold the list into.
Returns:
VyList
The content, molded into the shape.
"""
# Because something needs to be mutated.
content, shape = LazyList(content), LazyList(shape)
@lazylist_from(content)
def _mold(content, shape, index=0):
output = []
index = index
for item in shape:
if vy_type(item, simple=True) is list:
output.append(_mold(content, item, index))
yield output[-1]
index += len(output[-1]) - 1
else:
output.append(content[index])
yield output[-1]
index += 1
return _mold(content, shape)
def mold_without_repeat(
content: VyList,
shape: VyList,
) -> VyList:
"""
Mold a list into a shape but don't reuse content.
Parameters:
content: VyList
The list to mold.
shape: VyList
The shape to mold the list into.
Returns:
VyList
The content, molded into the shape.
"""
@lazylist_from(content)
def _mold(content, shape, index=0):
index = index
output = []
for item in shape:
if type(item) is list or type(item) is LazyList:
output.append(_mold(content, item, index))
yield output[-1]
index += len(output[-1]) - 1
else:
try:
output.append(content[index])
yield output[-1]
except IndexError:
break # We've reached the end of content, stop looping
index += 1
return _mold(content, shape)
def pad_to_square(array: VyList) -> VyList:
"""
Returns an array padded to the square of the largest dimension.
"""
mat = list(map(list, array))
max_dim = max(len(mat), max(map(len, mat)))
for row in mat:
for _ in range(max_dim - len(row)):
row.append(0)
if max_dim > len(mat):
mat += [[0] * max_dim for _ in range(max_dim - len(mat))]
return mat
def partition_at(booleans: VyList, array: VyList) -> VyList:
"""
Partitions an array at the indices where booleans is True.
"""
is_infinite = (
type(array) is LazyList
and array.infinite
or type(booleans) is LazyList
and booleans.infinite
)
def gen(array, booleans):
chunk = []
index = 0
booleans, array = LazyList(booleans), LazyList(array)
while array.has_ind(index):
if booleans.has_ind(index) and booleans[index]:
yield chunk
chunk = []
chunk.append(array[index])
index += 1
if chunk:
yield chunk
return LazyList(gen(array, booleans), is_infinite)
def partition_at_indices(indices: VyList, array: VyList) -> VyList:
"""
Partitions an array at the indices given.
"""
is_infinite = (
type(array) is LazyList
and array.infinite
or type(indices) is LazyList
and indices.infinite
)
def gen(array, indices):
chunk = []
index = 0
indices, array = LazyList(indices), LazyList(array)
while array.has_ind(index):
if index + 1 in indices:
yield chunk
chunk = []
chunk.append(array[index])
index += 1
if chunk:
yield chunk
return LazyList(gen(array, indices), is_infinite)
def pi_digits(n: int):
"""Generate x digits of Pi. Spigot's formula."""
@lazylist
def gen():
x = n + 1
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while x > 0:
p, q, k = k * k, 2 * k + 1, k + 1
a, b, a1, b1 = a1, b1, p * a + q * a1, p * b + q * b1
d, d1 = a / b, a1 / b1
while d == d1 and x > 0:
yield int(d)
x -= 1
a, a1 = 10 * (a % b), 10 * (a1 % b1)
d, d1 = a / b, a1 / b1
return gen()
def pop(iterable_object: VyList, count: int, ctx: Context) -> List[Any]:
"""Pops (count) items from iterable. If there isn't enough items
within iterable, input is used as filler."""
popped_items = []
for _ in range(count):
if iterable_object:
popped_items.append(iterable_object.pop())
else:
temp = get_input(ctx)
popped_items.append(temp)
if ctx.retain_popped:
for item in popped_items[::-1]:
iterable_object.append(item)
if ctx.reverse_flag:
popped_items = popped_items[::-1]
if count == 1:
return popped_items[0]
return popped_items
def prefixes(lhs: Union[VyList, str], ctx: Context) -> VyList:
"""Returns a list of prefixes of a string or list
(not including [] or '')"""
if isinstance(lhs, str):
return [lhs[: i + 1] for i in range(len(lhs))]
else:
@lazylist_from(lhs)
def gen():
temp = []
for item in iterable(lhs, ctx=ctx):
temp.append(deep_copy(item))
yield temp
return gen()
def primitive_type(item: Any) -> Union[str, type]:
"""Turns int/Rational/str into 'Scalar' and everything else
into list"""
if type(item) in [int, sympy.Rational, str, types.FunctionType] or is_sympy(
item
):
return SCALAR_TYPE
assert type(item) in [list, LazyList]
return list
def reverse_number(
item: Union[int, sympy.Rational]
) -> Union[int, sympy.Rational]:
"""Reverses a number. Negative numbers are returned negative"""
if item == 0:
return 0
sign = -1 if item < 0 else 1
rev = str(abs(item)).strip("0")[::-1]
return vyxalify(sympy.Rational(eval(rev) * sign))
def ring_translate(string: str, map_source: Union[str, list]) -> str:
"""Ring translates a given string according to the provided mapping
- that is, map matching elements to the subsequent element in the
translation ring. The ring wraps around."""
ret = ""
for char in string:
if char in map_source:
ret += map_source[(map_source.index(char) + 1) % len(map_source)]
else:
ret += char
return ret
def run(ast: vyxal.structure):
code = vyxal.transpile.transpile_ast(ast)
stack = []
ctx = Context()
exec(code, locals() | globals())
return pop(stack, 1, ctx)
def safe_apply(
function: types.FunctionType, *args, ctx, arity_override=None
) -> Any:
"""
Applies function to args that adapts to the input style of the passed function.
If the function is a _lambda (it's been defined within λ...;), it passes a
list of arguments and length of argument list.
Otherwise, if the function is a user-defined function (starts with FN_), it
simply passes the argument list.
Otherwise, unpack args and call as usual
*args does NOT contain ctx
"""
if function.__name__.startswith("_lambda"):
ret = function(
list(args)[::-1], function, arity_override or len(args), ctx=ctx
)
if len(ret):
return ret[-1]
else:
return []
elif function.__name__.startswith("VAR_"):
return function(list(args)[::-1], function, ctx=ctx)[-1]