簡體   English   中英

在 Python 函數中使用遞歸輸出元組列表

[英]Using recursion in Python function to output a list of tuples

我對 python 很陌生,如果你願意,我會很感激任何幫助。基本上我輸入一個字符串並返回“編碼”的字符串。 但是我的功能有問題,我不知道我哪里出錯了。

def encode_it(x):
    output = []
    counter = 1
    while x[0] != x[-1]:
        if x[0] == x[1]:
            counter += 1
            return encode_it(x[1:])
        else:
            output += (x[0],counter)
            counter = 1
            return encode_it(x[1:])

    return output

我想要的結果是這樣的:

>>>encode_it("qqqqppttyl")
[("q",4),("p",2),("t",2),("y",1),("l",1)]

我真的很感激任何幫助,我只是在學習 python 並嘗試遞歸,如果有更簡單的方法來做到這一點而沒有遞歸,我將非常感激:)

謝謝你們!! 為了響應 L3viathan 的代碼,我對其進行了修改,因此它會輸出結果,但不會將最后一個字符添加到列表中:

def encode_it(x):
last_char = None
num = 0
result = []
for char in x:
    t = ( )
    if last_char == char:
        num += 1
    else:
        if last_char:
            t += last_char,num
            result += t
        last_char = char
        num = 1
return result 

如果我要調用 encode_it("qqqeerrw"),我會得到的結果是:

['q', 3, 'e', 2, 'r', 2] #it's leaving out the w here?

另外,我有一個空元組 't' 和一個空列表 'result' 的原因是,我希望每個字符都在它自己的元組中,並帶有它的計數......像這樣:

[("q",3),("e",2),("r",2),("w",1)]

這個任務很容易通過itertools.groupby完成:

def encode_it(txt):
    return ((c, len(tuple(grp))) for c, grp in itertools.groupby(txt))

然后:

>>> list(encode_it("qqqqppttyl"))
[('q', 4), ('p', 2), ('t', 2), ('y', 1)]

您的代碼的問題之一是每次遞歸調用時output被重新初始化為空列表。 在最后一種情況下,當您完成整個字符串時,將返回新創建的空列表(然后還通過所有遞歸調用返回)。


這是一個沒有遞歸的解決方案,作為一個生成器:

def encode_it(x):
    last_char = None
    num = 0
    for char in x:
        if last_char == char:
            num += 1
        else:
            if last_char:
                yield (last_char, num)
            last_char = char
            num = 1

用法:

>>> list(encode_it("qqqqppttyl"))
[('q', 4), ('p', 2), ('t', 2), ('y', 1)]

其工作方式是遍歷字符串,並測試當前字符是否與last_char保存的字符相同。 如果是這樣,我們只需增加一個計數器。 如果不是,我們yield最后一個字符的元組及其計數,並為last_charnum設置新值。

生成器不返回列表,而是返回生成器對象,因此要將其轉換為列表,您可以對其調用list()

一個簡單的遞歸(按照要求)解決問題:

def encode_it(x):
    if not x:  # base case: empty string
        return []
    i, c = 1, x[0] 
    while i < len(x) and c == x[i]:
        i += 1
    return [(c, i)] + encode_it(x[i:])

您可以輕松地使用count方法和單行for循環而無需遞歸。

def encode_it(x):
   return [(char,x.count(char)) for char in x]

list.count(x)返回 x 在列表中出現的次數。

凌亂的單線:

def encode_it(x):
    return [(c,x.count(c,i,next((i for i, v in enumerate(x) if v != c), -1))) for i, c in enumerate(x) if x.index(c) == i]

如果相同的字符也沒有按順序排列,則下面的解決方案也將起作用,而不使用遞歸函數。

例如給定的字符串是一些東西

>>>groupBy("qqqqqq1212")
[('q', 6), ('1', 2), ('2', 2)]

或者

>>>groupBy("qqqqqq1212tytl")
[('y', 1), ('q', 6), ('1', 2), ('l', 1), ('t', 2), ('2', 2)]

沒有遞歸函數的程序

str = "qqqqqq1212tytl"

def groupBy(str):
   result = []
   count = {}
   for c in str:
      if c in count:
          count[c] += 1
      else:
          count[c] = 1

   for key in count:
      if count[key] >= 1:
          result +=  [(key, count[key])]            

   return result           


print(groupBy(str))

請讓我知道,如何使用遞歸函數更好地編碼?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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