Python task Substrings without loops

Viewed 70

You have to count how many substrings of a given string starts and ends with the same letter. You cannot use in your code the following: for,while,sum,map,reduce,filter,import,eval,exec,complile,single

My code but doesn't work properly:

def substringsV2(i,string,sub_list):
    if i == len(string)-1:
        return len(sub_list),sub_list
        # return len(sub_list)
    if string[:i + 2][0] == string[:i + 2][-1] and  string[:i + 2]not in sub_list:
        substring = string[:i + 2]
        sub_list.append(substring)
    if string[i:][0] == string[i:][-1]  and  string[i:] not in sub_list:
        substring = string[i:]
        sub_list.append(substring)
    return substringsV2(i + 1,string,sub_list)
 
def substrings(i,string,subs_list):
    if i == len(string):
        print(subs_list)
        return substringsV2(0,string,subs_list)
    if len(string[i]) == 1:
        subs_list.append(string[i])
    return substrings(i+1,string,subs_list)

s = 'aba'
if len(s) == 0:
    print()
else:
    print(substrings(0,s,[]))

For example input 'aba' Substrings: a, b, a, ab, ba, aba ,

Output 4 , because there are 4 substrings that starts and ends the same letter

0 Answers
Related