简体   繁体   中英

Need to reduce the number of recursive calls in this function

The problem is given a string S and an integer k<len(S) we need to find the highest string in dictionary order with any k characters removed but maintaining relative ordering of string.

This is what I have so far:

def allPossibleCombinations(k,s,strings):
    if k == 0:
       
        strings.append(s)
        return strings
    
    for i in range(len(s)):
        new_str = s[:i]+s[i+1:]
        strings = allPossibleCombinations(k-1, new_str, strings)
        
    return strings

def stringReduction(k, s):
    strings = []
    combs = allPossibleCombinations(k,s, strings)
    return sorted(combs)[-1]

This is working for a few test cases but it says that I have too many recursive calls for other testcases. I don't know the testcases.

This should get you started -

from itertools import combinations

def all_possible_combinations(k = 0, s = ""):
  yield from combinations(s, len(s) - k)

Now for a given k=2 , and s="abcde" , we show all combinations of s with k characters removed -

for c in all_possible_combinations(2, "abcde"):
  print("".join(c))

# abc
# abd
# abe
# acd
# ace
# ade
# bcd
# bce
# bde
# cde

it says that I have too many recursive calls for other testcases

I'm surprised that it failed on recursive calls before it failed on taking too long to come up with an answer. The recursion depth is the same as k , so k would have had to reach 1000 for default Python to choke on it. However, your code takes 4 minutes to solve what appears to be a simple example:

print(stringReduction(8, "dermosynovitis"))

The amount of time is a function of k and string length. The problem as I see it, recursively, is this code:

for i in range(len(s)):
    new_str = s[:i]+s[i+1:]
    strings = allPossibleCombinations(k-1, new_str, strings, depth + 1)

Once we've removed the first character say, and done all the combinations without it, there's nothing stopping the recursive call that drops out the second character from again removing the first character and trying all the combinations. We're (re)testing too many strings!

The basic problem is that you need to prune (ie avoid) strings as you test, rather than generate all possibilties and test them. If a candidate's first letter is less than that of the best string you've seen so far, no manipulation of the remaining characters in that candidate is going to improve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM