[英]Unique combinations of length 2 of two strings using recursion
我写了一个小函数,可以打印出组合:
def get_data(str1, str2):
if len(str1) == 0 or len(str2) == 0:
return
print str1[0], str2[0]
get_data(str1[1:], str2)
get_data(str1, str2[1:])
get_data("stu", "wxyz")
我得到的输出为:
s w
t w
u w
u x
u y
u z
t x
u x
u y
u z
t y
u y
u z
t z
u z
s x
t x
u x
u y
u z
t y
u y
u z
t z
u z
s y
t y
u y
u z
t z
u z
s z
t z
u z
输出有很多重复的对。 我如何只获得唯一值?
简单的for循环有什么问题吗?
def get_data(str1, str2):
for char in str1:
for char2 in str2:
print char, char2
get_data("stu", "wxyz")
输出:
s w
s x
s y
s z
t w
t x
t y
t z
u w
u x
u y
u z
您的代码很复杂,使用的递归比循环慢,而且占用的内存也比循环多,而且正如您指出的那样,它不能正常工作。
这是使用循环的更简单版本。 唯一性是显而易见的,至少在两个字符串中都没有重复字符的情况下。 这也适用于其他数据类型,例如两个列表。
def getdata(str1, str2):
for s1 in str1:
for s2 in str2:
print(s1, s2)
getdata("stu", "wxyz")
这将打印您想要的内容:
s w
s x
s y
s z
t w
t x
t y
t z
u w
u x
u y
u z
请注意,我的代码适用于Python 3:要在Python 2中使用它,只需删除print
语句中的括号,或从将来导入print 。
如果您坚持递归:
def get_data(s1,s2):
get_data_helper( s1, s2, s2 )
def get_data_helper(s1,s2,s2full):
'''Print all combinations of s1[0] w/ s2, followed by all combinations from s1[1:] with s2full
s2 is a suffix of s2full'''
if s1=="":
return
if s2=="":
get_data_helper( s1[1:],s2full,s2full)
else:
print s1[0], s2[0]
get_data_helper( s1, s2[1:], s2full )
Python在软件包itertools中提供了用于各种迭代的漂亮工具。 您这里需要的是product ,一组可迭代项的笛卡尔积。
我添加了join -with-space操作以原始格式获取输出。 您也可以只使用有序的字符对。
import itertools
def get_data(str1, str2):
for combo in itertools.product(str1, str2):
print ' '.join(combo)
get_data("stu", "wxyz")
输出:
s w
s x
s y
s z
t w
t x
t y
t z
u w
u x
u y
u z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.