【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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | 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:
1 | The first string can be obtained by merging the other two. |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
2015-04-16 【164】ALL_VIDEOS
2012-04-16 【032】Mark Zuckerberg