简体   繁体   English

递归返回 python 中包含 2 个元素的列表

[英]Recursion return a list with 2 elements in python

i want the function to store a list or a tuple with two strings in it.我希望 function 存储一个列表或一个包含两个字符串的元组。 The diffrent strings is dependent on wether the character is lower or upper case, if not in the alphabet it should be removed.不同的字符串取决于字符是小写还是大写,如果不在字母表中,则应将其删除。 The functions should be strictly recursive and no extra parameters to the function.这些函数应该是严格递归的,并且 function 没有额外的参数。 how do i get this done?我该怎么做?

def recursive(message):
        if message > 0:

               if message[0].islower():

                    return message[0] + recursive(message[1:]), 


               if message[0].isupper():
                    return message[0] + recursive(message[1:]),

               else:
                    return recursive(message[1:])



first, second = recursive("HalleLUJAh")

first should then hold ("alleh")
second should then hold ("HLUJA")


def split_case(sentence)
    lower, upper  = "", ""
        for char in sentence:
            if char.islower():
                lower += char
            else:
                upper += char
    return lower, upper
def recursive_split(message):
    if message:
        first, second = recursive_split(message[1:])
        if message[0].isupper():
            return first, message[0] + second
        else:
            return message[0] + first, second

    else:
        return "", ""

print(recursive_split("HalleLUJAh")) # ('alleh', 'HLUJA')

You can just use something like,你可以使用类似的东西,

$ cat rec.py
def recursive(word):
    lower, upper = "", ""
    if word:
        if word[0].islower():
            lower += word[0]
            f, s = recursive(word[1:])
            lower += f
            upper += s
        else:
            upper += word[0]
            f, s = recursive(word[1:])
            lower += f
            upper += s
    return lower, upper

first, second = recursive("HalleLUJAh")
print(first, second)

Output: Output:

$ python rec.py
('alleh', 'HLUJA')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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