简体   繁体   中英

Recursion inside for loop (Python)

I don't have experience to code recursion programs. I am trying to find a recursive solution that gives all different combinations for given two strings using for loop. I would like to find a solution using for loop inside recursion. For a given string ABC,DEF. the output must be AD,AE,AF,BD,BE,BF,CD,CE,CF. Assume combination length = 2. I wrote below code, it is not working. Can any one help? what would be thought process for a recursion inside a for loop?

def mkcb(s1, s2, i, ns):

    if i <= 2:
        print(ns)
    
    for k in range(len(s1)):
        mkcb(s1[1:], s2, i+1, s1[k] + s2[k])
        
mkcb('ABC', 'DEF', 0, '')

There really is no need to recursion here, this is far easier using a simple nested for-loop (pseudo-code):

for each char1 in "ABC":
  for each char2 in "DEF":
    print_on_screen(concatenation(char1, char2))
  next char2
next char1

Recursion doesn't really make sense for your simple case with two strings. A pair of nested loops would be much easier.

It would make more sense to use recursion if you were trying to solve a more general problem of making combinations of an arbitrary number of strings. Then the general structure of recursion combined with iteration would make sense.

I'd do it like this, with a loop over the first string, and the recursion working on the remaining strings. A prefix keyword-only argument (defaulting to an empty string) would get passed along to tell the code what characters had already been added, and the whole prefix would be printed when there were no strings left to pick characters from:

def combinations(*strings, prefix=""):
    if not strings:                          # base case, no strings left to pick from
        print(prefix)
        return

    for char in strings[0]:                            # iterate over the first string
        combinations(strings[1:], prefix=prefix+char)  # recurse on the other strings

This would work for your current case combinations("ABC", "DEF") , but would also work for more strings:

>>> combinations("AB", "CD", "EF", "GH")
ACEG
ACEH
ACFG
ACFH
ADEG
ADEH
ADFG
ADFH
BCEG
BCEH
BCFG
BCFH
BDEG
BDEH
BDFG
BDFH

If you didn't want to print the strings directly in the function, but rather return them to the caller, I'd write a recursive generator instead, which wouldn't need the prefix stuff:

def combinations_gen(*strings):
    if not strings:
        yield ""
        return

    for char in strings[0]:
        for rest in combinations_gen(*strings[1:]):
            yield char + rest

You'd use this by iterating over its return value:

for val in combinations_gen("ABC", "DEF"):
    print(val)

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