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},)) LIST_PAIRS = (([],[]),([1,2],[3,4]),([1,2],[7]),([-1,0],[2,0]),([],[1]),([1,2],[1,3])) 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 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))), Skill('predicates', ('all_positive', 'every_positive', 'all_above_zero', 'only_positive_numbers'), ('list',), 'Return whether every number is greater than zero.', 'all(x > 0 for x in a)', LISTS, lambda a: len([x for x in a if x<=0])==0), Skill('predicates', ('any_negative', 'has_negative', 'contains_negative', 'some_below_zero'), ('list',), 'Return whether any number is less than zero.', 'any(x < 0 for x in a)', LISTS, lambda a: len([x for x in a if x<0])>0), Skill('strings', ('digit_characters', 'digits', 'keep_digits', 'digit_list'), ('text',), 'Return a list of the digit characters, preserving order.', '[char for char in a if char.isdigit()]', TEXT+(('a1b2',),('0 19',)), lambda a: list(filter(str.isdigit,a))), Skill('strings', ('uppercase_characters', 'capital_letters', 'keep_uppercase', 'uppercase_list'), ('text',), 'Return a list of the uppercase characters, preserving order.', '[char for char in a if char.isupper()]', TEXT, lambda a: list(filter(str.isupper,a))), Skill('strings', ('letter_characters', 'letters', 'keep_letters', 'letter_list'), ('text',), 'Return a list of the alphabetic characters, preserving order.', '[char for char in a if char.isalpha()]', TEXT, lambda a: list(filter(str.isalpha,a))), Skill('sequences', ('pair_sums', 'add_pairs', 'add_lists', 'pairwise_sums'), ('list','list'), 'Add corresponding numbers from the two lists. Stop at the shorter list.', '[x + y for x, y in zip(a, b)]', LIST_PAIRS, lambda a,b: [a[i]+b[i] for i in range(min(len(a),len(b)))]), Skill('sequences', ('pair_products', 'multiply_pairs', 'multiply_lists', 'pairwise_products'), ('list','list'), 'Multiply corresponding numbers from the two lists. Stop at the shorter list.', '[x * y for x, y in zip(a, b)]', LIST_PAIRS, lambda a,b: [a[i]*b[i] for i in range(min(len(a),len(b)))]), Skill('sequences', ('matching_pairs', 'equal_pairs', 'matching_values', 'aligned_matches'), ('list','list'), 'Return the equal values at corresponding positions in the two lists.', '[x for x, y in zip(a, b) if x == y]', LIST_PAIRS, lambda a,b: [a[i] for i in range(min(len(a),len(b))) if a[i]==b[i]]), Skill('mappings', ('invert_mapping', 'swap_keys_values', 'invert_dictionary', 'values_to_keys'), ('mapping',), 'Map each value to its key. Later keys win for repeated values.', '{value: key for key, value in a.items()}', MAPS+(({'a':1,'b':1},),), lambda a: dict(zip(a.values(),a.keys()))), Skill('mappings', ('positive_entries', 'keep_positive_values', 'positive_mapping', 'filter_positive_values'), ('mapping',), 'Return a dictionary containing only entries with positive values.', '{key: value for key, value in a.items() if value > 0}', MAPS, lambda a: {k:a[k] for k in a if a[k]>0}), Skill('mappings', ('increment_values', 'add_one_to_values', 'increment_mapping', 'successor_values'), ('mapping',), 'Return a dictionary with one added to each value.', '{key: value + 1 for key, value in a.items()}', MAPS, lambda a: dict(zip(a.keys(),map(lambda x:x+1,a.values())))), Skill('mappings', ('keys_for_value', 'matching_keys', 'find_keys', 'keys_with_value'), ('mapping','number'), 'Return the keys whose values equal the number, in insertion order.', '[key for key, value in a.items() if value == b]', (({},0),({'a':1,'b':2},1),({'a':0,'b':0},0),({'a':2},3)), lambda a,b: list(filter(lambda key:a[key]==b,a))), Skill('elementwise', ('absolute_items', 'absolute_values', 'magnitudes', 'absolute_each'), ('list',), 'Return a list containing the absolute value of each number.', '[abs(x) for x in a]', LISTS, lambda a: list(map(abs,a))), Skill('elementwise', ('indexed_items', 'enumerate_items', 'numbered_items', 'index_value_pairs'), ('list',), 'Return a list of index and value pairs, starting at index zero.', '[(index, value) for index, value in enumerate(a)]', LISTS, lambda a: list(zip(range(len(a)),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 skill.arguments[0]=='number' else 'prefix' if skill.arguments[0]=='text' else 'other_items') 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