2016-12-13 23 views
-1

所以我有這個項目運行良好,唯一的問題是我得到的文件內寫入的返回值。這裏是我的代碼:如何在寫入模式下使用「返回值」

def write_substrings_to_file(s,filename): 
if type(s) != str: 
    raise TypeError ("You have entered something other than a sting, please enter a string next time!") 
if s=="" or filename=="": 
    raise ValueError 
why=open(filename,"wt") 
output="" 
if len(s)==1: 
    return s[0] 
for i in range(0,len(s)): 
    for n in range(0,len(s)): 
     output+=s[i:n+1] 
    break 
return output+write_substrings_to_file(s[1:],filename) 
why.write() 
why.close() 

在我需要的最後三行是

return output+write_substrings_to_file(s[1:],filename) 
why.write(return) 
why.close() 

但我不能使用這樣的方式回報換句話說,我收到以下錯誤

TypeError: cannot concatenate 'str' and 'type' objects

+0

你能解釋一下函數應該做什麼嗎? – mitoRibo

+0

讓我們說輸入的是 'ABC' 打開一個文件,寫上如下: 一個 AB ABC b BC Ç 另一個解釋,輸入:大 摹 克 GRE 格雷亞 大 [R 重新 意圖 不動產資產信託 Ë EA 吃 一個 在 牛逼 ,然後保存該文件,另一件事是h作爲遞歸函數 – Enigma

回答

1

我不明白你在你的函數中想要完成什麼,所以這可能不是你想要的,但是你的問題是你試圖寫出return這是一個函數,當我想你想要寫你建立遞歸代替,然後返回字符串:

my_ret = output+write_substrings_to_file(s[1:],filename) 
why.write(my_ret) 
why.close() 
return my_ret 

感謝解釋的問題,這是代碼,我會用:

def my_write(s, ind = 0, step = 1): 
    ret = [] 

    if ind+step <= len(s): 
     ret.append(s[ind:ind+step]) 
     step += 1 
    else: 
     step = 1 
     ind += 1 

    if ind < len(s): 
     ret += my_write(s,ind,step) 

    return ret 

ret = my_write('abc') 
print ret #<- outputs ['a', 'ab', 'abc', 'b', 'bc', 'c'] 

而對於代碼高爾夫球:

def break_word(s): 
    ret = [s[:x] for x in range(1,len(s)+1)] 
    ret += break_word(s[1:]) if len(s) > 1 else [] 
    return ret 

ret = break_word('abc') 
print ret #<- outputs ['a', 'ab', 'abc', 'b', 'bc', 'c'] 
相關問題