Created
October 19, 2015 05:53
-
-
Save gulan/3b2c9ae423af1ec94e81 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| #!/usr/bin/env python | |
| """ | |
| More TLA+ inspired coding. Using an explict step() that takes the | |
| current state to the next state makes loop invarients easier to think | |
| about. | |
| """ | |
| def str2int(s): | |
| def step(pair): | |
| (s,n) = pair | |
| digit = ord(s[0]) - ord('0') | |
| return (s[1:], 10*n + digit) | |
| p = (s,0) | |
| while p[0] != '': | |
| p = step(p) | |
| return p[1] | |
| if __name__ == '__main__': | |
| assert str2int('0') == 0 | |
| assert str2int('0000') == 0 | |
| assert str2int('1') == 1 | |
| assert str2int('9') == 9 | |
| assert str2int('09') == 9 # No implied octal conversion | |
| assert str2int('1000') == 1000 | |
| assert str2int('12345') == 12345 | |
| assert str2int('') == 0 # Odd case, but seems logical because sum([]) == 0 | |
| print 'str2int ok' | |
| def int2str(n): | |
| def step(p0): | |
| # Let | |
| # (n',s') = step((n,s)) | |
| # then | |
| # 10*n' + str2int(s') == n + str2int(s) | |
| # Remember, I defined str2int('') == 0 | |
| (n,s) = p0 | |
| r = n % 10 | |
| return (n/10, `r`+s) # inefficient, I know. | |
| assert n >= 0 | |
| p = step((n,'')) | |
| while p[0] != 0: | |
| p = step(p) | |
| return p[1] | |
| if __name__ == '__main__': | |
| assert int2str(0) == '0' | |
| assert int2str(1) == '1' | |
| assert int2str(10) == '10' | |
| assert int2str(1234567) == '1234567' | |
| for n in range(100): | |
| assert str2int(int2str(n)) == n | |
| print 'int2str ok' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment