簡體   English   中英

使用遞歸的兩個字符串的長度2的唯一組合

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM