r/programming • • May 08 '15

Five programming problems every Software Engineer should be able to solve in less than 1 hour

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k Upvotes

2.1k comments sorted by

View all comments

Show parent comments

1

u/glemnar May 08 '15

8 line recursive solution. would be 7 lines if return could come before "print" in python

def recurse(valstring, num):
    if num == 9:
        if eval(valstring + str(num)) == 100:
            print(valstring + str(num))
        return
    for op in ['+', '-', '']:
        recurse(valstring + str(num) + op, num + 1)
recurse('', 1)

1

u/stratoscope May 09 '15

Very nice!

Keeping with the theme of simple Python solutions, here's one I wrote before I discovered this thread, coincidentally also eight lines:

ops = ( '', ' + ', ' - ' )
for k in range( 0, pow(3,8) ):
    v = '1'
    for i in range( 2, 10 ):
        v += ops[ k % 3 ] + str( i )
        k = k // 3
    if eval( v ) == 100:
        print( v )