Daily Programmer project


This is an older one, but it was interesting to play around with.

https://www.reddit.com/r/dailyprogrammer/comments/2z68di/20150316_challenge_206_easy_recurrence_relations/

Avoided a massive if/else construct, while still allowing all binary operators, by building a string and using eval.  The recurrence function could probably be exploited due to that eval, I really should follow up on that comment I put there about protecting it.  It simplifies the code, but eval lets you execute arbitrary strings.

If the code is used as intended, by calling the last function, the int() cast, along with only keeping the first character as a string, breaks any attempt at an exploit that I’ve tried.  But I can’t guarantee use as intended in Python, certainly not easily.

#Daily Programmer 206e Recurrence Relations

def recurrence(n, op_list):
    """Applies the recurrence relation in op_list to n
    op_list is a list of tuples, op[n][0] is an operator,
    op[n][1] is an integer"""

    result = n
    for op in op_list:
        operator, operand = op[0], op[1]
        #Should probably do something to protect this eval
        result = eval('{}{}{}'.format(result, operator, operand))
    return result

def get_nth_term(recurrence_relation, relation, first_term, n):
    if n == 0:
        return first_term
    else:
        return get_nth_term(recurrence_relation,
                            relation,
                            recurrence_relation(first_term, relation),
                            n-1)

def recur_n_times(relation, first_term, n):
    op_list = [(x[0],int(x[1:])) for x in relation.split()]

    return get_nth_term(recurrence, op_list, first_term, n)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: