I just wrote a function to search the binary tree for the closest number in tree. This is what I wrote below. However, it seems that the self.res in the dfs function does not renew the self.res in closeestValue function. I know I can write the dfs into the closestValue to solve the problem. But I do want to write two seperated functions. Is there any solution for that? Thank you!
class Solution:
"""
#param root: the given BST
#param target: the given target
#return: the value in the BST that is closest to the target
"""
def closestValue(self, root, target):
# write your code here
if root is None:
return None
self.res = root.val
self.dfs(root, target)
return self.res
def dfs(self, aroot, atarget):
if not aroot:
return None
if abs(aroot - atarget) < abs(self.res - atarget):
self.res = aroot.val
if atarget > aroot.val:
self.dfs(aroot.right, atarget)
else:
self.dfs(aroot.left, atarget)
return aroot.val
Problem solved. The call of res is not a problem. The abs(aroot - atarget) should be abs(aroot.val - atarget).
Related
class Car:
def __init__(self,make,model,year):
self.make=make
self.model=model
self.year=year
self.odometer_reading=0
def get_details(self): #SELF allows access of attributes and methods of a class
details=print((f'The make is: {self.make}, the model is: {self.model}, & the year is: {self.year}\n'))
#return details without print function works? i.w. details=rest of the line without print + return details (next line)
def read_odometer(self): #reading the value (default)
print(f'\nReading: {self.odometer_reading}')
def update_odometer(self,mileage):
if mileage>=self.odometer_reading:
print('\nReading has been changed')
self.odometer_reading=mileage
else:
print('\nCan, not change ')
def increment_odometer(self,miles):
self.odometer_reading+=miles
x.get_details() #trying to modify print(x.get_details()) which does work. Why does print need to be supplied here?
#incrementing the odometer
print(x.increment_odometer(50)) #why is this none?
I am learning classes and am confused about some aspects:
Why is "return details" line needed for method get_details()? Normally a simple function call having def f(): print('a') works, hence the confusion.
print(x.increment_odometer(50)) is None. Perhaps a function return needed in increment_odometer() method?
Confusing points having been commented in the code. Please englighten me.
Sincerely.
I have two methods which take different number of arguments. Here are the two functions:
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
I am using a function which will return one of these functions to main.I have stored this returned function in a variable named operation.
Since the number of parameters are different for both,how do I identify which function has been returned?
if(operation == jumpMX):
operation(IAS,list)
elif(operation == addMX):
operation(IAS)
What is the syntax for this?Thanks in advance!
You can identify a function through its __name__ attribute:
def foo():
pass
print(foo.__name__)
>>> foo
...or in your case:
operation.__name__ #will return either "jumpMX" or "addMX" depending on what function is stored in operation
Here's a demo you can modify to your needs:
import random #used only for demo purposes
def jumpMX(self,IAS,list):
pass
def addMX(self,IAS):
pass
def FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove():
# This will randomly return either jumpMX()
# or addMX to simulate different scenarios
funcs = [jumpMX, addMX]
randomFunc = random.choice(funcs)
return randomFunc
operation = FunctionThatWillReturnOneOrTheOtherOfTheTwoFunctionsAbove()
name = operation.__name__
if(name == "jumpMX"):
operation(IAS,list)
elif(name == "addMX"):
operation(IAS)
You can import those functions and test for equality like with most objects in python.
classes.py
class MyClass:
#staticmethod
def jump(self, ias, _list):
pass
#staticmethod
def add(self, ias):
pass
main.py
from classes import MyClass
myclass_instance = MyClass()
operation = get_op() # your function that returns MyClass.jump or MyClass.add
if operation == MyClass.jump:
operation(myclass_instance, ias, _list)
elif operation == MyClass.add:
operation(myclass_instance, ias)
However, I must emphasize that I don't know what you're trying to accomplish and this seems like a terribly contrived way of doing something like this.
Also, your python code examples are not properly formatted. See the PEP-8 which proposes a standard style-guide for python.
I am trying to automate android game. I have so many methods so I break my code in 3 parts.
main, functions and collectors.
I have a method in functions which is:
def search_image(image, confidence=.6, click=True):
location = pyautogui.locateCenterOnScreen(image, confidence=confidence)
if location is not None:
if click:
pyautogui.click(location)
return location
else:
return False
But I cant access it in collectors, like this:
from functions import*
def collect_product():
if search_image(r'Resources\NewOrderAvailable.png') is not False:
search_image(r'Resources\NewOrderAvailable2.png')
for item in range(0, 6):
search_image(r'Resources\Collect.png', confidence=.8)
search_image(r'Resources\Back.png')
search_image(r'Resources\CloseOrderMenu.png')
else:
return False
I got NameError: name 'search_image' is not defined. I need to duplicate that method to make it work. I was wondering what went wrong and how to fix it?
Your function is not an instance of the class. You need to add a self keyword to make it accessible outside.
def search_image(self, image, confidence=.6, click=True):
location = pyautogui.locateCenterOnScreen(image, confidence=confidence)
if location is not None:
if click:
pyautogui.click(location)
return location
else:
return False
Try
import functions
functions.search_image('...')
I have a function in python which works like find command. So basically it will go into depth till it hit m_depth (maxdepth) and will not go into the directory if it is specified in ignore_dirs. It will return a list of files which is found in a walk. The code is really simple and uses recursion.
But for a large number of files or greater depth, the recursion is taking time and the list is getting bigger when returning. So I am seeking if anyway the generator can be used, so atleast the memory consumption is less for each iteration?
I tried with yielding the result but then it is exiting whenever a ignore_dirs is found.
This is the code I have:
def find(source_d, m_depth, ignore_dirs):
'''
This method does a recursive listing of files/directories from a given
path upto maximun recursion value provide as m_depth.
:param source_d: Given source path to start the recursion from
:param m_depth: Maximum recursion depth [determines how deep the method will traverse through the file system]
:param ignore_dirs: this paths will not be traversed. List of strings.
'''
def helper_find(path, ignore_dirs, m_depth, curr_depth=1):
files = []
if any(ignore_sub_dir == os.path.split(path)[-1] for ignore_sub_dir in ignore_dirs):
return []
if m_depth < curr_depth:
return []
else:
things = os.listdir(path)
for thing in things:
if(os.path.isdir(os.path.join(path, thing))):
files.extend(helper_find(os.path.join(path, thing), ignore_dirs, m_depth, curr_depth+1))
else:
files.append(os.path.join(path, thing))
return files
return helper_find(source_d, ignore_dirs, m_depth)
The answer is yes, you can make a recursive generator by using yield from (available only in Python 3):
def find(source_d, m_depth, ignore_dirs):
'''
This method does a recursive listing of files/directories from a given
path upto maximun recursion value provide as m_depth.
:param source_d: Given source path to start the recursion from
:param m_depth: Maximum recursion depth [determines how deep the method will traverse through the file system]
:param ignore_dirs: this paths will not be traversed. List of strings.
'''
def helper_find(path, ignore_dirs, m_depth, curr_depth=1):
if not any(ignore_sub_dir == os.path.split(path)[-1] for ignore_sub_dir in ignore_dirs)and m_depth >= curr_depth:
things = os.listdir(path)
for thing in things:
if(os.path.isdir(os.path.join(path, thing))):
yield from helper_find(os.path.join(path, thing), ignore_dirs, m_depth, curr_depth+1)
else:
yield os.path.join(path, thing)
return helper_find(source_d, ignore_dirs, m_depth)
I am trying to test each input then return that the number is cleared then do the math. For Example is a user inputs N instead of a number I want it to output that its not a number whereas if the user inputs 1 then I want it to move to the next function asking for a power then do the same thing and if that passes then goes to the final section which output the answer to the problem.
The program passes both the errors for the non number areas yet when it get to very last function it is telling me base nor power are defined.
Code is written in some Python2 and some Python3. All works fine though. I use python3 mostly.
[Test Picture/Error Msg][1]
# Below we are creating the recursive statement to do the math for us. We are calling Base and Power
# from the main function where the user Inputs the numbers.
def pow(base, power):
if power == 0:
return 1
if power == 1:
return base
else :
return base * pow(base, power - 1)
def determineBase():
while True:
try:
base = int(input ('Please Enter A Base: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return base
def determinePower():
while True:
try:
power = int(input ('Please Enter A Power: '))
except ValueError:
print("Please use whole numbers only. Not text nor decimals.")
continue
else:
return power
def main():
determineBase()
determinePower()
pow(base,power)
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
main()
def main():
determineBase()
determinePower()
pow(base,power)
Here, neither base nor power are defined. What you meant instead was to store the result from those function calls and pass those then:
def main():
base = determineBase()
power = determinePower()
pow(base, power)
The issue isn't inside the recursive function, it's inside your main function.
The problem is arising due to the fact that you are passing base as an argument to the pow() function without defining the variable base first (the same would subsequently be true for power).
In other words you need something along the lines of:
def main():
base = determineBase()
power = determinePower()
pow(base,power) #this line could probably be removed
print("The answer to",base,"to the power of", power,"is", pow(base,power),".")
As currently, you're not storing the values of these two functions.