How to use counter variable inside the body of recursive function - python

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.

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).

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.

Related

Python - I want to know using count method without brackets

word = input().upper()
word_list = list(set(word))
cnt = []
for i in word_list:
count = word.count
cnt.append(count(i))
if cnt.count(max(cnt)) > 1:
print("?")
else:
print(word_list[(cnt.index(max(cnt)))])
in this code, look at the line6, count=word.count, count function is used.
I know that count function must be used like '.count()' this formation.
But in this case, '' is not used.
So I want to know how it is possible and how it can run very well.
+) when I print(type(word.count)), <built-in method count of str object at 0x01DD8800> is returned!
word.count is a bound method of word. Normally, you'd bind the method and then call it immediately with word.count(i), but it's perfectly legal to bind the method (attaching the instance to it for when it's called in the future), then call it at some later point. That's all you did here, you made count equivalent to word.count, then called it later providing the argument it required, as if you'd called word.count(i) at that point.
When you do something like count = word.count() what you are doing is calling the word.count function and assign the value that the function returns to the count variable. When you do count = word.count what you are really doing is assing the function pointer to the count variable so now count points to the same thing as word.count and you can now use it call that with count() and now it is basically the same thing as word.count() and if you do print(word.count) and print(count) it will give you the same output in both saying you the pointer of the function

How do I get around functions being called when they are used as arguments for other functions

I want to use a function as a default argument for another function that can be overridden without calling the function.
Let's use this snippet:
def split():
word = input('Whats the word?')
return [letter for letter in word]
def do_something_with_letters(letters=split())
for letter in letters:
print(letter)
If I call do_something_with_letters like this:
do_somthing_with_letters()
The program works how I would expect it to but not in the order that I expect. The end result is that split is called and user input is used to define the word which is split then passed into do_something_with_letters. Now, this is happening during the declaration of do_somthing_with_letters rather than during the function call(where split() is used as a default value).
for instance if I override the default value i.e:
do_somthing_with_letters(['a', 'b', 'c'])
The following chain of events occurs: Split Declared > do_somthing_with_letters Declared > Split Called and assigned to letters(or stored in memory) > do_somthing_with_letters called with overridden value.
The user has been needlessly prompted for input when it should have been over-written.
Again I need a function to be the default value for letters any answer should have a way of keeping that.
Now, this is happening during the declaration of
do_somthing_with_letters rather than during the function call(where
split() is used as a default value).
Because the function split() is being called when the function is declared. You can initialise letters with the function name (actually the function object) without calling it by omitting the parentheses. Then you can test if the argument can be called, e.g because it is a function, callable class etc.
def do_something_with_letters(letters=split):
if callable(letters):
letters = letters()
for letter in letters:
print(letter)
Now if you call do_something_with_letters() without arguments, letters will default to the split() function and call it to get the letters to work on. If you were to pass a string or list then it would print the elements of those objects. You could even pass in a different function to have it obtain the input.
>>> do_something_with_letters()
Whats the word?hello
h
e
l
l
o
>>> do_something_with_letters('abcd')
a
b
c
d
>>> do_something_with_letters(lambda : 'a string')
a
s
t
r
i
n
g
>>> do_something_with_letters(range(5)) # not letters at all
0
1
2
3
4
You have a counter-intuitive design, combining program steps that aren't functionally related. As a result, you're trying to warp the module design to compensate. user input and pre-processing the input are not fully linked in your program design -- so why do you insist on putting them into a module where they are linked? Decouple those steps.
Your do_something function should not have to adapt to wherever the string originates. let it simply handle its string argument.
If you somehow do have a design that requires this contortion, you have a problem: the default value must be realized at the definition of do_something.
You can leave the function itself as an argument:
def do_something(source=split):
if not isstring(source):
letters = source(argument) # You still need to supply argument
However, this is still tortuous design.
Also, I strongly recommend that you not use split as a function name, since that is already a built-in string function.
I believe this sort of problem may call for a decorator. You can define a function, such as verbose (shown below), that when used to decorate a function that returns an iterable, modifies it according to the behavior as specified in do_something_with_letters from your post.
Then by simply decorating the split function, you can achieve the desired result.
def verbose(f):
def func(s):
for ch in f(s):
print(ch)
return func
#verbose
def split(s):
return (ch for ch in s)
if __name__ == '__main__':
s = input("Enter word: ")
split(s)
Now any other function may be modified in a similar way. For example, the upper_and_split function will print all characters in s in uppercase.
#verbose
def upper_and_split(s):
return (ch for ch in s.upper())

Change made to a variable in a function reverted when that function exits

I'm new to programming and stumbled upon this "weird" problem. Here is my code :
part_1 = ""
part_2 = ""
part_3 = ""
part_4 = ""
alphabet = "abcdefghijklmnopqrstuvwxyz"
import random
def random_part(part):
for x in range (0,4) :
part += random.choice(alphabet)
print(part)
random_part(part_1)
print(part_1)
The goal is to create a string composed of 4 random letters. Now when i run this code, i'm expecting it to print the string 2 times : 1 because of the "print" indication in the function and another because of the print(part_1).
Thing is, when i run it, i have a random string and an empty line , for example :
bdgv
*empty line*
In other words, the first printing indication located within the fuction works, but if i ask the variable after the function is done, it's resetted to " ".
What could be the reason for that ?
part += random.choice(alphabet) is a reassignment of the local variable part, not a mutation. The string passed as a parameter is unaffected. Strings are immutable in Python, so you can never pass them to any function and expect them to have changed. You'd have to return the new string object and have the caller assign it to the passed variable:
def random_part(part):
for x in range (0,4) :
part += random.choice(alphabet)
print(part)
return part
part_1 = random_part(part_1)
Btw, whether the += operation is a mutation or a reassignment depends on the involved type's implementation of the magic method __iadd__. For lists for example, it's a mutation and your passed parameter would have changed. Obviously, for immutable types it will never be a mutation.

How to make global empty integer?

How to declare global empty integer? I have simple code but i don't know how to declare a variable before def. In java I can do just that: public int a;
but how to do it in python? Without this, the third if not working
My code:
def abcd:
if s<0.72:
if e>30:
a=0
return a
else:
a=0
return a
else:
if a == 1:
a = 1
return a
else:
a=1
return a
while True:
abcd
Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.
You can declare as follow, if you want a non-value variable:
a = None
Or you can declare as follow, if you want a zero value int variable:
a = int()
At the top:
a = int()
int() returns 0 to start.
Also, you need to use proper function syntax:
def abcd():
If e or s are arguments passed to abcd, you need to add those to the function signature:
def abcd(e, s):
Python is a dynamic language with duck typing. So if you gonna declare an empty variable use None as it's initial value. That means no value.
Yes dont make it equal to zero, depending on what you are doing your program will not work if equal to zero.
REMEMBER ZERO IS NOT THE SAME AS NONE

google python exercises

I'm watching the instructional videos on you youtube and started doing some of the exercises at http://code.google.com/edu/languages/google-python-class but I'm puzzled by the below problem in the string1.py file.
What I can't seem to understand is, what is the "s" in both_ends(s): doing?
# B. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
# +++your code here+++
# LAB(begin solution)
if len(s) < 2:
return ''
first2 = s[0:2]
last2 = s[-2:]
return first2 + last2
At the bottom of strings1.py there are some functions:
def main()
print 'both_ends'
test(both_ends('spring'), 'spng')
if __name__ == '__main__':
main()
So how does the program know to substitute "spring" for (s) or is that not what it's doing? I can post the entire file if need be. It's only 140 lines.
'spring' is the literal string passed as a parameter into function both_ends(), and 's' is the formal parameter to the function. Replacing a formal parameter with an actual parameter is performed when the function is called.
The 'test()' function is just there to confirm that the function behaves as expected.
When you call a function, the values you give the function are assigned to the corresponding arguments in the function header. In code:
def my_func(a): #function header; first argument is called a.
#a is not a string, but a variable.
print a #do something with the argument
my_func(20) #calling my_func with a value of 20. 20 is assigned to a in the
#body of the function.
s is a variable that we presume to hold a string. We pass 'spring' in through as a parameter.
s in def both_ends(s) is the parameter for the input string. The length of this string is checked with the call to len(s) < 2, and various characters in the string are accessed by position with s[0:2] and s[-2:]
See http://docs.python.org/tutorial/controlflow.html#defining-functions for specifics. Also the tutorial at http://docs.python.org/tutorial/index.html is pretty good - I mostly learnt from it.
s is the parameter to the function, but you plug in real strings like hello or world into the function instead of just the letter s. Think of it like a math function: you have f(x) = x + 5. When you plug in a number, say 2, you get f(2) = 2 + 5. That's exactly what happens with the both_ends function. To make it simpler, here's some code:
def f(x):
return x + 5
f(2)
The way you plug into the function in the code here is the same way you plug a string into your original function.

Categories

Resources