Skip to content

Instantly share code, notes, and snippets.

@raghavrv
Created December 23, 2016 09:30
Show Gist options
  • Select an option

  • Save raghavrv/2f0ff2439bce4c1745f562d77ec9dd41 to your computer and use it in GitHub Desktop.

Select an option

Save raghavrv/2f0ff2439bce4c1745f562d77ec9dd41 to your computer and use it in GitHub Desktop.
Interview question for pratheeban
# 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