Python - I want to know using count method without brackets - python

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

Related

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

Call many python functions from a module by looping through a list of function names and making them variables

I have three similar functions in tld_list.py. I am working out of mainBase.py file.
I am trying to create a variable string which will call the appropriate function by looping through the list of all functions. My code reads from a list of function names, iterates through the list and running the function on each iteration. Each function returns 10 pieces of information from separate websites
I have tried 2 variations annotated as Option A and Option B below
# This is mainBase.py
import tld_list # I use this in conjunction with Option A
from tld_list import * # I use this with Option B
functionList = ["functionA", "functionB", "functionC"]
tldIterator = 0
while tldIterator < len(functionList):
# This will determine which function is called first
# In the first case, the function is functionA
currentFunction = str(functionList[tldIterator])
Option A
currentFunction = "tld_list." + currentFunction
websiteName = currentFunction(x, y)
print(websiteName[1]
print(websiteName[2]
...
print(websiteName[10]
Option B
websiteName = currentFunction(x, y)
print(websiteName[1]
print(websiteName[2]
...
print(websiteName[10]
Even though it is not seen, I continue to loop through the iteration by ending each loop with tldIterator += 1
Both options fail for the same reason stating TypeError: 'str' object is not callable
I am wondering what I am doing wrong, or if it is even possible to call a function in a loop with a variable
You have the function names but what you really want are the function objects bound to those names in tld_list. Since function names are attributes of the module, getattr does the job. Also, it seems like list iteration rather than keeping track of your own tldIterator index would suffice.
import tld_list
function_names = ["functionA", "functionB", "functionC"]
functions = [getattr(tld_list, name) for name in function_names]
for fctn in functions:
website_name = fctn(x,y)
You can create a dictionary to provide a name to function conversion:
def funcA(...): pass
def funcB(...): pass
def funcC(...): pass
func_find = {"Huey": funcA, "Dewey": funcB, "Louie": FuncC}
Then you can call them, e.g.
result = func_find["Huey"](...)
You should avoid this type of code. Try using if's, or references instead. But you can try:
websiteName = exec('{}(x, y)'.format(currentFunction))

python s=input().count What does input().count function do in python?

I saw this code on the internet:
s=input().count
print( max( (s('6')+s('9')+1)//2, max([s(i) for i in "01234578"])))
but I don't get what this line does :
s=input().count
I thought this function was to count how many letters are in the word. So I tried to print the s, but I got this error:
<built-in method count of str object at 0x7f4f8b859148>
what does input().count function do and what situation will it be used?
s=input().count is a function which you can call.
You could write
input().count('6')
to count how many times you get 6 in the input.
Or,
s('6')
is now a shorthand for this.
s = input().count
Basically you are binding the count method to s so when you call s like s(i), it converts the code to input().count(i) internally.
Let me give you a simple example:
p = print
p("hello world")
# hello world

How to use counter variable inside the body of recursive function

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.

Passing values through functions in Python

I am trying to pass a list of two integers created from one function so that I can manipulate them in succeeding functions.
def rollDie(number):
throw = []
for i in range(number):
roll = random.randint(1,6)
throw.append(roll)
return throw
So I have created another function game() that calls the rollDie() results:
def game(self,number):
if self.rollDie[0] != 1 or self.rollDie[1] != 1:
round_score = self.rollDie[0] + self.rollDie[2]
return round_score
But when I call the function game() it does not pull the two integers from rollDie():
print(game(2))
it returns error:
TypeError: game() missing 1 required positional argument: 'number'
I have researched here, here, here among other places inside stackoverflow. I am hoping someone can help. Many thanks for your patience.
The way you have defined the function, you have made it a non-static reference, i.e. it has to be called on an object.
You have to call game on whatever object you have defined. For example, instantiate your class as game1 and then call game1.game(2).
As #AAA pointed out, the way you are defining game() makes it look like a class function (you can read about classes here) but it does not look like you have defined a class anywhere. If you have defined a class elsewhere, then we need to see that code. If you didn't mean to create a class, then you need to take out the self references.
Also, I am not sure how self.rollDie[0] is supposed to work. Are you trying to reference a class list called rollDie? If so, I do not see that defined. If you are trying to call your def rollDie(number): function, then you need to do it like so: self.rollDie(). If you want to access the list indices, it would be best to make that equal to something: self.roll_list = self.rollDie(1) which you can then access by self.roll_list[0]
One thing to keep in mind is that lists are mutable objects, so if you are going to use your lists in multiple functions and you do not intend to create a class, thenit may be less confusing to initiate it on its own, outside of a function, as you can access it from any function.
I did a similar program:
Dice statistics 14.11.2015
from random import sample
result = [0, 0, 0, 0, 0, 0]
tosses = 10000
for i in range(tosses):
dice = sample(range(0, 6), 1)
new = str(dice).strip('[]')
result[int(new)] += 1
for i in range(0, 6):
print(i + 1, ' ====> ', result[i])

Categories

Resources