简体   繁体   中英

return a list of strings in a recursive function python

I'm trying to return a list of strings from the function Groups(s,k) where basically, the list of strings of 'k' elements from string 's' k>=0 and k<= len(s) and these elements in the these strings occur in the same order as 's' as shown below

Groups("abcde", 2) → ["ab","ac","ad","ae","bc","bd","be","cd","ce,"de"]

Groups("abcde",5) → ["abcde"]
Groups("abcde",1) → ["a","b","c","d","e"]

I'm really sorry for my wording of the question as it's hard to understand but here is what I have so far:

    def Groups(s,k):
        if k == 0 or k > len(s):
            return [""]

        return [ i*k for i in s if k ==1]
        if k > 1 and k <= 5:
            return[ x for y in s y for x in s]

I would greatly appreciate any help:)

I think combinations is the word you are looking for:

list(''.join(letters) for letters in combinations("abcde", 2))
# returns ['ab', 'ac', 'ad', 'ae', 'bc', 'bd', 'be', 'cd', 'ce', 'de']

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