Created
December 23, 2016 09:30
-
-
Save raghavrv/2f0ff2439bce4c1745f562d77ec9dd41 to your computer and use it in GitHub Desktop.
Interview question for pratheeban
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
| # Write a function that takes a list of string and returns the sum of the list items that represents an integer. | |
| def sum_up_int_terms(string): | |
| sum = 0 | |
| for item in string: | |
| try: | |
| sum += int(item) | |
| except: | |
| pass | |
| return sum | |
| print(sum_up_int_terms('a47b8')) | |
| # Write above in a recursive setup | |
| def rec_sum_up_int_terms(string): | |
| if len(string) == 0: | |
| return 0 | |
| try: | |
| return int(string[0]) + rec_sum_up_int_terms(string[1:]) | |
| except: | |
| try: | |
| return rec_sum_up_int_terms(string[1:]) | |
| except: | |
| return 0 | |
| # Should evaluate to 7 * 7 = 49 (tests all cases) | |
| print(rec_sum_up_int_terms('a') + rec_sum_up_int_terms('7') + rec_sum_up_int_terms('77') + | |
| rec_sum_up_int_terms('a7') + rec_sum_up_int_terms('7a') + rec_sum_up_int_terms('a77a')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment