2014-10-18 22 views
-6

任何人都可以解決這個遞歸功能問題嗎?解決這個遞歸函數的問題?

編寫一個程序,確定一個電話號碼的所有字母翻譯。如果輸入字符串中出現不可翻譯的字符,則應將其作爲常量傳遞。 輸入:7位數字串的序列,每行一個。終止於一個7 0的字符串。

樣品輸入:

borla63 
0000000 

輸出示例:

borlamd,borlame,borlamf,borland,borlane,borlanf,borlaod,borlaoe,borlaof 
#data5.py 
import string 
lets=["","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"] 
def rep(numb,index): 
    if index<len(numb) and (numb[index]) not in assi at +"01" 
    for letter in lets[int(numb[index])]: 
     rep(numb[:index] +letter+numb[index+1:],index+1) 
    elif index>= len(numb: 
     print(numb) 
    else: 
     rep(numb,index+1) 
while True: 
     number=input() 
     if number=="0000000": 
        break 
        rep(number,0) 
+4

歡迎來到Stack Overflow!看起來你希望我們爲你寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。證明這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出和實際獲得的輸出(控制檯輸出,堆棧跟蹤,編譯器錯誤 - 無論是適用)。您提供的細節越多,您可能會收到的答案就越多。 – 2014-10-18 15:54:29

+0

是的,有人可以 – UnholySheep 2014-10-18 15:54:35

+0

這個問題來自以前的比賽,我抄下了一部分解決方案,但我錯誤地複製了它的一部分,並設法打破了代碼。社區是否願意爲我解決這個問題?注意它不會產生輸出。 – Lilyk27 2014-10-18 15:58:58

回答

0

我瞭解下投票,截止投票,請你以後不要在這裏表現出絲毫的努力。另一方面,這是一個不平凡的問題。我會假設你真的對這個問題的解決方案感興趣,我會告訴你我會如何寫這個(沒有太多看你發佈的代碼)。

lets=("", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz") 

def trans(pnum, res = ""):   # res is the current result (initially the empty string) 
    if not pnum: 
     yield res     # phone number is empty string, so we're done, return res 
    else: 
     digit = pnum[0]    # get first digit 
     try: 
      repls = lets[int(digit)] # if it is an integer, get replacements 
      if not repls:   # if replacements is an empty string, 
       repls = digit  # fall back to initial digit 
     except ValueError: 
      repls = digit   # not an integer - fall back to initial character 
     for i in repls:    # for every replacement character 
      yield from trans(pnum[1:], res+i) # recursively process the rest of the phone number 

for pnum in ["borla63", "h3llo"]: 
    print(list(trans(pnum))) 

這將產生

['borlamd', 'borlame', 'borlamf', 'borland', 'borlane', 'borlanf', 'borlaod', 'borlaoe', 'borlaof'] 
['hdllo', 'hello', 'hfllo'] 

現在我不知道問題的禁令是如何工作的,但我希望你用你的「超時」,研究該代碼一點點,然後進行適當的改變上面的一個。

請注意,這是Python 3.3+,如果它很重要。

希望這會有所幫助!

+0

非常感謝!星期四我對comp sci團隊選拔測試感到有點緊張,所以你的回答非常有幫助! – Lilyk27 2014-10-19 16:33:46

+0

@ Lilyk27沒問題。我相信你會回到以後更好地準備好的問題;-)祝你好運! – uselpa 2014-10-19 16:44:22