1

Below the code for counting the no of '1' character in String.

count2=0 #global variable
def Ones(s):
    no=0;
    global count2 #wanted to eliminate global variable
    if(count2>=len(s)):
        return no
    if(s[count2]=='1'):#count2 is the index of current character in String
        no = no+1
        count2=count2+1
        return no + Ones(s)
    else:
        count2=count2+1
        return Ones(s)

in the above code using count2 as a global variable , is there any possible way to declare and use count2 variable as a local inside the function , have tried like but no luck

def Ones(s):
    count2=0 # but everytime it get reset to zero

Note: number of parameter of function should be remain only one and no any other helper function have to use.

4
  • Could you describe what the algorithm is trying to do? Is count2 the index of the current character to assess? Could you have a second parameter with a default value, making it effectively a single parameter function? Commented Apr 9, 2017 at 9:02
  • @jonrsharpe yes count2 is index of current character Commented Apr 9, 2017 at 9:04
  • Then that's not a very good name for it. Also unless you have a specific need for recursion return Counter(s)['1'] would do it. Commented Apr 9, 2017 at 9:06
  • @jonrsharpe ok for variable name i agreed , but i have do it by recursive Commented Apr 9, 2017 at 9:31

2 Answers 2

2

The avoidance of explicit state variables is an important part of the recursion concept.

The method you are calling only needs the remainder of the string to find 1s in it. So instead of passing a string, and the position in the string, you can pass only the remainder of the string.

Python's powerful indexing syntax makes this very easy. Just look at it this way: Each instance of the method can take away the part it processed (in this case: one character), passing on the part it didn't process (the rest of the string).

Sign up to request clarification or add additional context in comments.

Comments

2

Just like @ypnos said, if you really want to use recursion, here is the code:

def Ones(s):
    if not s:
        return 0
    if s[0]=='1':
        return 1 + Ones(s[1:])
    else:
        return Ones(s[1:])

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.