summaryrefslogtreecommitdiff
path: root/python/problems/functions/greatest/common.py
blob: 91f773ee214691021dc725c8d8706cb75fd48be2 (plain)
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
# coding=utf-8

import re
from python.util import has_token_sequence, string_almost_equal, \
    string_contains_number, get_tokens, get_numbers, get_exception_desc
from server.hints import Hint, HintSequence

id = 195
group = 'functions'
number = 1
visible = True

solution = '''\
def naj(xs):
    naj = xs[0]
    for x in xs:
        if x > naj:
            naj = x
    return naj
'''

hint_type = {
    'no_def': Hint('no_def'),
    'no_return': Hint('no_return'),
    'for_loop': Hint('for_loop'),
    'if_clause': Hint('if_clause'),
}

def test(python, code):
    test_in = [('naj([6, 4, 2, 0])', None),
               ('naj([4, 6, 2, 0])', None),
               ('naj([4, 2, 6, 0])', None),
               ('naj([4, 2, 0, 6])', None),
               ('naj([6, -8, 2, 0])', None),
               ('naj([-8, 6, 2, 0])', None),
               ('naj([-8, -6, -2, 0])', None),
               ('naj([-8, -6, -2, -1])', None),
               ('naj([-8, -1, -6, -2])', None),
               ('naj([-1, -8, -6, -2])', None),
               ('naj([42])', None),
               ('naj([-42])', None)]

    test_out = [6, 6, 6, 6, 6, 6, 0, -1, -1, -1, 42, -42]

    answers = python(code=code, inputs=test_in, timeout=1.0)
    n_correct = sum(ans[0] == to for ans, to in zip(answers, test_out))
    return n_correct, len(test_in)

def hint(python, code):
    # run one test first to see if there are any exceptions
    answer = python(code=code, inputs=[('naj([1, 2, 3, 6, 4, 2, 0])', None)], timeout=1.0)
    exc = get_exception_desc(answer)
    if exc: return exc

    tokens = get_tokens(code)
    # if has no def, tell him to define the function
    if not has_token_sequence(tokens, ['def']):
        return [{'id' : 'no_def'}]

    # if has no return, tell him to return the value
    if not has_token_sequence(tokens, ['return']):
        return [{'id' : 'no_return'}]

    # if has no loop, tell him to use it
    if not has_token_sequence(tokens, ['while']) and \
       not has_token_sequence(tokens, ['for']):
        return [{'id' : 'for_loop'}]

    # if has no condition if, tell him to use it
    if not has_token_sequence(tokens, ['if']):
        return [{'id' : 'if_clause'}]

    return None