【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.

转载于:https://www.cnblogs.com/alex-bn-lee/p/10718182.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值