开发者

convert nested brackets into decimals

I have only just started working with Python and开发者_StackOverflow社区 one of the exercises I got from my tutor is to convert a tuple (number of nested brackets) into decimals; I have been working on this for hours now, but I got nowhere... e.g. input = (((()))) output = 3

I started like this:

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

could anyone give me a hint where I´ve gone wrong - PLEASE!!!!


You never change x. Presumably you want to add one to it before recursing. Also, constructs such as (()()) will trip you up.


print len(s) / 2

Assuming you want to do this by recursion, you need to think about it a bit first. The point of recursion is to break the problem into smaller pieces which you know how to solve, and then to build up the solution for a large problem from the solutions to the smaller problems. Can you do that in this case? Yes: given a string, check that the first character is ( and the last character is ), then solve the problem for the remaining string and add one.

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

See if you can write that.


Well, here is something that takes care of complex (()((()))):

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)

testing:

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

I'm not sure how pythonic and fast it is though.


You can look at this ques

I had asked the same question but it was more for evaluation. In this look at the use of re to calculate inner () and then you can just increment the counter.

I hope this helps :)


This is easy if you can use real tuples. They are hard to read in the Python syntax though

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜