2010-12-08 96 views
0

我剛剛開始使用Python,我從我的導師那裏獲得的練習之一是將元組(嵌套括號的數目)轉換爲小數;我一直在這個工作了幾個小時,但我沒有去... 輸入=(((()))) 輸出= 3將嵌套括號轉換爲小數

我開始是這樣的:

def add (x,y): 
    if y == '()': 
     return x 
     else: 
     length = len(y) 
     return successor(add (x,y[1:length-1])) 

任何人都可以給我一個提示,其中從來就出了問題 - 請!!!!

+1

您是否字面上計算括號的數目併除以二? – katrielalex 2010-12-08 21:25:16

+0

`((()())`的輸出是什麼? 2,我猜? – khachik 2010-12-08 21:27:03

+0

是的,我想這就是我應該做的.. – Curly 2010-12-08 21:31:41

回答

1

你永遠不會改變x。大概你想在遞歸之前添加一個。另外,諸如(()())之類的構造將會讓你感到興奮。

0
print len(s)/2 

假設你想通過遞歸來做到這一點,你需要先考慮一下。遞歸的要點是將問題分解成小部分,你知道如何解決,然後從小問題的解決方案構建解決大問題的解決方案。你能在這種情況下做到嗎?是的:給定一個字符串,檢查第一個字符是(,最後一個字符是),然後解決剩餘字符串的問題並添加一個。

def depth(parens): 
    # is the string empty? if so return 0 
    # check that the first character is (
    # check that the last character is) 
    # take off the first character and the last character 
    # calculate depth(the remaining string) 
    # add one and return 

看看你能不能寫出來。

0

嗯,這裏是一些需要複雜(()((())))護理:

def tuples(string, found=0): 
    if not string: return found 
    start = string.find('()') 
    end = start + len('()') 
    sub = string[:start] + string[end:] 

    if start != 0 and end != len(string): 
    return tuples(sub, found+1) 
    else: 
    return tuples(sub, found) 

測試:

print tuples('') - 0 
print tuples('()') - 0 
print tuples('()()') - 0 
print tuples('(()())') - 2 
print tuples('(())') - 1 
print tuples('(()') - 0 
print tuples('((()) (()()) ((())))'.replace(' ', '')) - 8 

我不知道它是怎麼雖然Python的和快速的。

0

你可以看一下這個ques

我曾問過同樣的問題,但它更多的評價。在這裏看看使用re來計算inner(),然後你可以遞增計數器。

我希望這有助於:)

0

這很簡單,如果你可以使用真正的元組。雖然它們很難在Python語法中讀取,但是

def f(t): 
    return len(t) + sum(map(f, t)) 

print f(()) 
print f(((),())) 
print f(((),)) 
print f((((),),((),()),(((),),)))