File size: 11,215 Bytes
b2f0875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import ast
from dataclasses import dataclass
from functools import reduce
import re
from typing import Callable


@dataclass(frozen=True)
class Skill:
    family: str
    names: tuple[str, ...]
    arguments: tuple[str, ...]
    description: str
    expression: str
    cases: tuple[tuple, ...]
    oracle: Callable


NUMBERS = ((-4,), (-1,), (0,), (1,), (2,), (3,), (7,))
PAIRS = ((-3, 2), (0, 0), (2, -4), (1, 5), (7, 3), (-2, -5))
TEXT = (('',), ('hello',), (' A b ',), ('A_B',), ('a  b c',), ('123',), ('MiXeD',))
LISTS = (([],), ([0],), ([3, -1, 3, 0],), ([-4, -2],), ([1, 2, 3],), ([0, 0],))
MAPS = (({},), ({'a': 1},), ({'x': 0, 'y': -2},), ({'b': 3, 'a': 4},))


def skills() -> tuple[Skill, ...]:
    return (
        Skill('numbers', ('square', 'square_number', 'squared', 'number_squared'), ('number',), 'Return the square of the number.', 'a ** 2', NUMBERS, lambda a: a*a),
        Skill('numbers', ('cube', 'cube_number', 'cubed', 'number_cubed'), ('number',), 'Return the cube of the number.', 'a ** 3', NUMBERS, lambda a: a*a*a),
        Skill('numbers', ('negate', 'negate_number', 'opposite', 'additive_inverse'), ('number',), 'Return the negation of the number.', '-a', NUMBERS, lambda a: 0-a),
        Skill('numbers', ('absolute', 'absolute_value', 'magnitude', 'number_magnitude'), ('number',), 'Return the absolute value of the number.', 'abs(a)', NUMBERS, lambda a: a if a >= 0 else -a),
        Skill('numbers', ('double', 'double_number', 'twice', 'twice_number'), ('number',), 'Return twice the number.', 'a * 2', NUMBERS, lambda a: a+a),
        Skill('numbers', ('increment', 'add_one', 'successor', 'next_integer'), ('number',), 'Return the number plus one.', 'a + 1', NUMBERS, lambda a: a+1),
        Skill('numbers', ('larger', 'larger_number', 'maximum_pair', 'pair_maximum'), ('number', 'number'), 'Return the larger of the two numbers.', 'max(a, b)', PAIRS, lambda a,b: a if a > b else b),
        Skill('predicates', ('is_even', 'even_number', 'check_even', 'has_even_parity'), ('number',), 'Return whether the number is even.', 'a % 2 == 0', NUMBERS, lambda a: a in range(-100,101,2)),
        Skill('predicates', ('is_odd', 'odd_number', 'check_odd', 'has_odd_parity'), ('number',), 'Return whether the number is odd.', 'a % 2 != 0', NUMBERS, lambda a: a not in range(-100,101,2)),
        Skill('predicates', ('is_positive', 'positive_number', 'check_positive', 'above_zero'), ('number',), 'Return whether the number is greater than zero.', 'a > 0', NUMBERS, lambda a: a >= 1),
        Skill('predicates', ('is_empty', 'empty_list', 'check_empty', 'has_no_items'), ('list',), 'Return whether the list is empty.', 'len(a) == 0', LISTS, lambda a: not bool(a)),
        Skill('predicates', ('contains', 'contains_item', 'has_item', 'item_present'), ('list', 'number'), 'Return whether the value occurs in the list.', 'b in a', (([],0),([1,2],2),([1,2],3),([0],0),([-1,2],-1)), lambda a,b: a.count(b)>0),
        Skill('predicates', ('starts_with', 'has_prefix', 'begins_with', 'prefix_matches'), ('text', 'text'), 'Return whether the text starts with the given prefix.', 'a.startswith(b)', (('hello','he'),('hello','x'),('',''),('A','a'),('abc','abcd')), lambda a,b: a[:len(b)]==b),
        Skill('predicates', ('is_lowercase', 'all_lowercase', 'check_lowercase', 'has_lowercase_text'), ('text',), 'Return whether the text is lowercase, using str.islower.', 'a.islower()', TEXT, lambda a: a.lower()==a and a.upper()!=a),
        Skill('strings', ('lowercase', 'to_lower', 'lower_text', 'make_lowercase'), ('text',), 'Return the text converted to lowercase.', 'a.lower()', TEXT, lambda a: ''.join(chr(ord(c)+32) if 'A'<=c<='Z' else c for c in a)),
        Skill('strings', ('uppercase', 'to_upper', 'upper_text', 'make_uppercase'), ('text',), 'Return the text converted to uppercase.', 'a.upper()', TEXT, lambda a: ''.join(chr(ord(c)-32) if 'a'<=c<='z' else c for c in a)),
        Skill('strings', ('strip_text', 'trim', 'trim_text', 'strip_edges'), ('text',), 'Return the text without leading or trailing whitespace.', 'a.strip()', TEXT, lambda a: a.lstrip().rstrip()),
        Skill('strings', ('reverse_text', 'reversed_text', 'reverse_string', 'backwards_text'), ('text',), 'Return the text in reverse order.', 'a[::-1]', TEXT, lambda a: ''.join(reversed(a))),
        Skill('strings', ('split_words', 'words', 'text_to_words', 'whitespace_words'), ('text',), 'Split the text into words on whitespace.', 'a.split()', TEXT, lambda a: re.findall(r'\S+',a)),
        Skill('strings', ('underscore_spaces', 'spaces_to_underscores', 'replace_spaces', 'underscored_text'), ('text',), 'Replace each space in the text with an underscore.', "a.replace(' ', '_')", TEXT, lambda a: ''.join('_' if c==' ' else c for c in a)),
        Skill('strings', ('join_words', 'words_to_text', 'space_join', 'join_with_spaces'), ('words',), 'Join the strings with a single space between them.', "' '.join(a)", (([],),(['hi'],),(['a','b','c'],),(['','x',''],)), lambda a: ''.join(word+(' ' if i<len(a)-1 else '') for i,word in enumerate(a))),
        Skill('sequences', ('list_length', 'count_items', 'item_count', 'number_of_items'), ('list',), 'Return the number of items in the list.', 'len(a)', LISTS, lambda a: sum(1 for v in a)),
        Skill('sequences', ('list_sum', 'sum_items', 'sum_values', 'total'), ('list',), 'Return the sum of the numbers in the list.', 'sum(a)', LISTS, lambda a: reduce(lambda x,y:x+y,a,0)),
        Skill('sequences', ('sort_items', 'sorted_items', 'ascending', 'sort_values'), ('list',), 'Return a new list sorted in ascending order.', 'sorted(a)', LISTS, lambda a: sorted(a)),
        Skill('sequences', ('reverse_list', 'reversed_list', 'reverse_items', 'backwards_items'), ('list',), 'Return a new list with the items in reverse order.', 'a[::-1]', LISTS, lambda a: list(reversed(a))),
        Skill('sequences', ('first_or_none', 'first_item', 'safe_first', 'head_or_none'), ('list',), 'Return the first item, or None if the list is empty.', 'a[0] if a else None', LISTS, lambda a: next(iter(a),None)),
        Skill('sequences', ('last_or_none', 'last_item', 'safe_last', 'tail_or_none'), ('list',), 'Return the last item, or None if the list is empty.', 'a[-1] if a else None', LISTS, lambda a: next(reversed(a),None)),
        Skill('sequences', ('count_value', 'count_occurrences', 'occurrence_count', 'item_occurrences'), ('list', 'number'), 'Count how many times the value occurs in the list.', 'a.count(b)', (([],0),([1,1,2],1),([0,0],0),([2],3)), lambda a,b: sum(v==b for v in a)),
        Skill('mappings', ('mapping_size', 'count_keys', 'key_count', 'dictionary_size'), ('mapping',), 'Return the number of keys in the dictionary.', 'len(a)', MAPS, lambda a: sum(1 for k in a)),
        Skill('mappings', ('keys_list', 'list_keys', 'dictionary_keys', 'mapping_keys'), ('mapping',), 'Return the dictionary keys as a list in insertion order.', 'list(a.keys())', MAPS, lambda a: [k for k in a]),
        Skill('mappings', ('values_list', 'list_values', 'dictionary_values', 'mapping_values'), ('mapping',), 'Return the dictionary values as a list in insertion order.', 'list(a.values())', MAPS, lambda a: [a[k] for k in a]),
        Skill('mappings', ('has_key', 'contains_key', 'key_present', 'key_exists'), ('mapping', 'key'), 'Return whether the key is in the dictionary.', 'b in a', (({},'x'),({'a':1},'a'),({'a':1},'b'),({'x':None},'x')), lambda a,b: b in list(a.keys())),
        Skill('mappings', ('get_or_none', 'lookup', 'lookup_value', 'optional_value'), ('mapping', 'key'), 'Return the value for the key, or None if the key is absent.', 'a.get(b)', (({},'x'),({'a':1},'a'),({'a':1},'b'),({'x':None},'x')), lambda a,b: a[b] if b in a else None),
        Skill('mappings', ('sorted_keys', 'ordered_keys', 'keys_sorted', 'alphabetical_keys'), ('mapping',), 'Return the dictionary keys as a sorted list.', 'sorted(a)', MAPS, lambda a: sorted(a.keys())),
        Skill('mappings', ('sum_values', 'values_total', 'dictionary_total', 'mapping_total'), ('mapping',), 'Return the sum of the dictionary values.', 'sum(a.values())', MAPS, lambda a: sum(a[k] for k in a)),
        Skill('elementwise', ('square_items', 'squared_items', 'square_each', 'squares'), ('list',), 'Return a list containing the square of each number.', '[x ** 2 for x in a]', LISTS, lambda a: list(map(lambda x:x*x,a))),
        Skill('elementwise', ('negate_items', 'negated_items', 'negate_each', 'opposites'), ('list',), 'Return a list containing the negation of each number.', '[-x for x in a]', LISTS, lambda a: list(map(lambda x:0-x,a))),
        Skill('elementwise', ('positive_items', 'keep_positive', 'positive_values', 'filter_positive'), ('list',), 'Return only the numbers greater than zero, preserving order.', '[x for x in a if x > 0]', LISTS, lambda a: list(filter(lambda x:x>0,a))),
        Skill('elementwise', ('even_items', 'keep_even', 'even_values', 'filter_even'), ('list',), 'Return only the even numbers, preserving order.', '[x for x in a if x % 2 == 0]', LISTS, lambda a: list(filter(lambda x:x in range(-100,101,2),a))),
        Skill('elementwise', ('word_lengths', 'lengths', 'length_of_each', 'string_lengths'), ('words',), 'Return the length of each string as a list.', '[len(x) for x in a]', (([],),(['a','bb',''],),(['hello','world'],)), lambda a: list(map(len,a))),
        Skill('elementwise', ('lowercase_words', 'lower_each', 'lower_words', 'lowercase_each'), ('words',), 'Return each string converted to lowercase, as a list.', '[x.lower() for x in a]', (([],),(['A','b','MiXeD'],),(['','HI'],)), lambda a: list(map(str.lower,a))),
        Skill('elementwise', ('nonempty_words', 'keep_nonempty', 'nonempty_strings', 'filter_empty_strings'), ('words',), 'Return only the nonempty strings, preserving order.', '[x for x in a if x]', (([],),(['a','','b'],),(['',''],),([' '],)), lambda a: list(filter(bool,a))),
    )


ARGUMENTS = dict(number=('x','n','number','value'), text=('text','s','string','value'),
    list=('items','values','numbers','xs'), words=('words','strings','items','values'),
    mapping=('mapping','data','dictionary','d'), key=('key','name','k','lookup_key'))


class Rename(ast.NodeTransformer):
    def __init__(self, names: dict[str, str]):
        self.names = names

    def visit_Name(self, node):
        return ast.copy_location(ast.Name(id=self.names.get(node.id,node.id),ctx=node.ctx),node)


def program(skill: Skill, name_index: int, interface: int, canonical: bool=False) -> tuple[str, str, str]:
    stable=dict(number='x',text='text',list='items',words='items',mapping='mapping',key='key')
    args = [stable[kind] if canonical else ARGUMENTS[kind][interface] for kind in skill.arguments]
    if len(args) == 2 and args[0] == args[1]:
        args[1] = 'y' if canonical else ('y','m','other','other_value')[interface]
    # Comprehension variables must not shadow a function argument (e.g. scalar x).
    mapping = dict(zip(('a','b'),args))
    expression = ast.unparse(Rename(mapping).visit(ast.parse(skill.expression,mode='eval')))
    name = skill.names[name_index]
    header = f'def {name}({", ".join(args)}):\n    """{skill.description}"""\n'
    return name, header, header+'    return '+expression