• 【396】python 递归练习题(COMP9021)


    Merging two strings into a third one

    Say that two strings s1 and s2 can be merged into a third string s3 if s3 is obtained from s1 by inserting arbitrarily in s1 the characters in s2, respecting their order. For instance, the two strings ab and cd can be merged into abcd, or cabd, or cdab, or acbd, or acdb, ..., but not into adbc nor into cbda. Write a program merging_strings.py that prompts the user for 3 strings and displays the output as follows:

    • If no string can be obtained from the other two by merging, then the program outputs that there is no solution.

    • Otherwise, the program outputs which of the strings can be obtained from the other two by merging.

    def one_char(a, b_list):
        for i in range(len(b_list)+1):
            tmp = b_list.copy()
            tmp.insert(i, a)
            yield tmp
            
    def whole_char(a_list, b_list):
        if len(a_list) == 1:
            yield from one_char(a_list[0], b_list)
        else:
            for li in whole_char(a_list[1:], b_list):
                yield from one_char(a_list[0], li)
    
    def is_merging(str_1, str_2, str_3):
        for tmp in [''.join(li) for li in whole_char(list(str_1), list(str_2))]:
            if tmp == str_3:
                return True
        return False
    
    str1 = input("Please input the first string: ")
    str2 = input("Please input the second string: ")
    str3 = input("Please input the third string: ")
    
    if is_merging(str1, str2, str3):
        print("The third string can be obtained by merging the other two.")
    elif is_merging(str1, str3, str2):
        print("The second string can be obtained by merging the other two.")
    elif is_merging(str2, str3, str1):
        print("The first string can be obtained by merging the other two.")
    else:
        print("No solution")            
    

      

    测试数据:

    str1: abcd

    str2: cd

    str3: ab

    output: 

    The first string can be obtained by merging the other two.
  • 相关阅读:
    [译]理解 iOS 异常类型 <🌟>
    LeetCode 24. 两两交换链表中的节点
    解决The operation couldn’t be completed. Unable to log in with account
    <Typora> 常用操作快捷键
    LeetCode 23. 合并K个升序链表
    CSS盒子模型
    CCS属性
    CSS
    form表单
    html
  • 原文地址:https://www.cnblogs.com/alex-bn-lee/p/10718182.html
Copyright © 2020-2023  润新知