簡體   English   中英

制作具有挑戰性約束的遞歸 function

[英]To make a recursive function with challenging constraints

我想用輸入字符串(例如'abcdef')制作一個function,並以相反的順序'fedcba'返回它。

然而,挑戰在於 function

  • 必須使用遞歸 function
  • 沒有使用 for 循環
  • 沒有任何運算符
  • 沒有列表切片

這是我的嘗試,但不起作用:

def reverse(s: str) -> str
    if len(s) == 0:
       return None

    return

如何在這里使用遞歸 function 來反轉順序? 我試着去想它,但我是遞歸調用的新手

“不使用 for 循環或任何運算符或列表切片”似乎是一個奇怪的要求,但以下 function 可以:

>>> def reverse(s):
...     head, *tail = s
...     if tail:
...         return f'{reverse(tail)}{head}'
...     else:
...         return head
... 
>>> reverse('abcdef')
'fedcba'

詞法分析的scope中, *被視為運算符,因此我們可以將head, *tail = s替換為:

import re

def reverse(s):
    head, tail = re.split('(?!^)', s, maxsplit=1)
    [...]

或者,或者:

def reverse(s):
    __, head, tail = s.partition(next(iter(s))
    [...]

或者,還有另一種選擇:

def reverse(s):
    s = iter(s)
    head, tail = next(s), ''.join(s)
    [...]

編輯:我刪除了 '+' 運算符,以及對字符串中重復字符不起作用的lstrip() (感謝@philosofool)

這是一種無需列表切片的方法。 並澄清s[0]是列表索引而不是列表切片,對嗎?

def reverse(s):
    if len(s)==1:
        return s
    else:
        s1 = list(s)
        del s1[0]
        return ''.join([reverse(''.join(s1)), s[0]])
    
reverse('abccdefg')

output 是

'gfedccba'

這實際上不是一個解決方案。 它滿足除遞歸之外的所有要求。 這是一個不錯的純功能解決方案,但不是 OP 所要求的。 留下來以防有人感興趣....

from functools import reduce

def reverse_string(string):
    return reduce(lambda x, y: f'{y}{x}', string)

這個問題可以根據您的要求完成,但我只在 c++ 有想法,您可以將代碼轉換為 python。

void reverse(string s,int i=0,int j=s.size()-1){
    if(i<=j) return; 
    char temp=s[i];
    s[i]=s[j];
    s[j]=s[i];
    reverse(s,++i,--j);
}

僅使用函數

def reverse(strng, pos):
    if pos:
         next_pos = map(lambda x: x, range(pos,0,-1))
         next(next_pos) # skip first
         return ''.join((strng[pos],reverse(strng, next(next_pos)))
         
    else:
        return strng[pos]

另一個受@Ecin 啟發的

def reverse(strng : str):
   def inner(strng : list):
      return ''.join((strng.pop(), inner(strng) if strng else ''))
   return inner(list(strng))

暫無
暫無

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

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