Created
April 28, 2011 14:32
-
-
Save jongyeol/946455 to your computer and use it in GitHub Desktop.
Arithmetic Puzzle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# problem: http://club.filltong.net/codingdojo/29104 | |
# solved: https://gist.github.com/946455 | |
# coded by jong10 | |
import unittest | |
def inserted(s, i, c): | |
return s[:i] + c + s[i:] | |
def moved(s): | |
return sorted(set(inserted(s[:w] + s[w+1:], i, s[w]) for i in xrange(len(s)) for w in xrange(len(s)))) | |
def isfit(expr): | |
try: | |
return apply(lambda x, y: x == y, map(eval, expr.split('='))) | |
except SyntaxError: | |
return False | |
def solve(s): | |
return filter(isfit, moved(s)) | |
class TestArithmetic(unittest.TestCase): | |
def test_moved(self): | |
self.assertEqual(moved('01'), ['01', '10']) | |
self.assertEqual(moved('012'), ['012', '021', '102', '120', '201']) | |
def test_isfit(self): | |
self.assertEqual(isfit('1+1=2'), True) | |
self.assertEqual(isfit('1+2=2'), False) | |
self.assertEqual(isfit('1+23='), False) | |
def test_solve(self): | |
self.assertEqual(solve('6+22=64'), ['62+2=64']) | |
self.assertEqual(solve('4*23=72'), ['24*3=72']) | |
self.assertEqual(solve('73+3=40'), ['3+37=40', '37+3=40', '7+33=40']) | |
self.assertEqual(solve('19-90=1'), ['19-0=19', '19-9=10', '91-90=1']) | |
self.assertEqual(solve('3+3=418'), ['3+38=41', '38+3=41']) | |
self.assertEqual(solve('8/8=64'), ['48/8=6']) | |
self.assertEqual(solve('-12-38=26'), ['12-38=-26']) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment