2016-05-31 47 views
0

我目前有一個代碼,它遞歸地取兩個字符串中的字母,並用交替字母返回新字。我想優化此代碼,以便如果第一個或第二個單詞更長,它仍然會返回較長字符串中的其餘字母。返回不同長度的兩個字符串中的交替字母

def alt(s,t): 
    if len(s) != len(t): 
     return 
    elif s == '' and t == '': 
     return '' 
    else: 
     return s[0] + t[0] + alt(s[1:], t[1:]) 

所需的輸出:

>>> alt('hello','bye') 
'hbeylelo' 

回答

3

只是測試st是空的,返回其他價值,如果他們中的一個是:

def alt(s, t): 
    if not s: 
     return t 
    elif not t: 
     return s 
    else: 
     return s[0] + t[0] + alt(s[1:], t[1:]) 

即使兩個st爲空,返回空字符串,這是一個完全有效的結束狀態。

您可以縮短這:

def alt(s, t): 
    if not (s and t): 
     return s + t 
    return s[0] + t[0] + alt(s[1:], t[1:]) 

所以在達到最終狀態時無論是st是空的(或者它們兩者都是)。

這將產生所需輸出:

>>> alt('hello', 'bye') 
'hbeylelo' 

迭代版本是:

from itertools import chain 
try: 
    # Python 2 
    from itertools import izip_longest as zip_longest 
except ImportError: 
    # Python 3 
    from itertools import zip_longest 

def alt_iterative(s, t): 
    return ''.join(chain.from_iterable(zip_longest(s, t, fillvalue=''))) 

它使用itertools.zip_longest() function做的大部分工作。

0

問題本身不是固有的遞歸。在這種情況下,迭代解決方案可能更簡單。

的Python 2:

from itertools import izip_longest 
def alt(s, t): 
    return ''.join(a + b for a, b in izip_longest(s, t, fillvalue='')) 

的Python 3:

from itertools import zip_longest 
def alt(s, t): 
    return ''.join(a + b for a, b in zip_longest(s, t, fillvalue='')) 
+1

的OP使用Python 3而不是2,所以你會在這裏得到一個導入錯誤。 'zip_longest'(和2中的'izip_longest')帶一個'fillvalue'參數,只需將其設置爲''''。 –

+1

只使用'''.join()'而不是'reduce()'.. –

+0

@MartijnPieters當然,感謝提示。有時你看不到樹木。 –

0

如果你喜歡使用itertools.chainzip(或itertools.zip_longest/izip_longest)一個班輪:

# Python 2 
return ''.join(chain(*zip(s, t))) + s[len(t):] + t[len(s):] 
# or 
return ''.join(chain(*izip_longest(s, t, fillvalue=''))) 

# Python 3 
return ''.join(chain(*zip_longest(s, t, fillvalue=''))) 
+0

如果你已經使用了'itertools',爲什麼不在你使用'itertools.zip_longest()'的時候? –

+0

@MartijnPieters保持它與Python 2兼容。我想。 – schwobaseggl

相關問題