If anyone can help me with the recursion part?
I omitted some part thnking that it was not necessary but after that function didn't work.
class node(object):
def __init__(self,value):
self.data=value
self.left=None
self.right=None
def insert(Node,value):
if Node is None:
Node=node(value)
else:
if value<Node.data:
## if Node.left is None: Node.left=node(value)
## else: insert(Node.left,value)
insert(Node.left,value)
else:
## if Node.left is None: Node.left=node(value)
## else: insert(Node.left,value)
insert(Node.right,value)
Because you'll need to create new node instances for your empty branches.
Let's see what happens with both definitions, printing out the values of the Node parameter:
def insert(Node, value):
print(Node)
if Node is None:
Node=node(value)
else:
if value<Node.data:
insert(Node.left,value)
else:
insert(Node.right,value)
On the REPL:
In [17]: badTree = node(10)
In [18]: badTree.data
Out[18]: 10
In [20]: badTree.left.data
----------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-20-3cb52def2967> in <module>()
----> 1 badTree.left.data
AttributeError: 'NoneType' object has no attribute 'data'
In [21]: badTree.right.data
----------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-21-b6f1267c9d29> in <module>()
----> 1 badTree.right.data
AttributeError: 'NoneType' object has no attribute 'data'
Let's see what happens if we insert an element to badTree:
In [22]: insert(badTree, 2)
<__main__.node object at 0x7f706bf34d30>
None
In [23]: badTree.left.data
----------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-3cb52def2967> in <module>()
----> 1 badTree.left.data
AttributeError: 'NoneType' object has no attribute 'data'
It fails to insert the element, but why? In badTree, both left and right branches are None (empty), what means that we need to create new trees there as we won't be able to recursively add new values, as we lose the reference to the main Node. This is, if we call insert(Node.left, value) before assigning a new object to Node.left, it will be equivalent to call insert(None, value) (this the value None, you can see it when we called insert on badTree), which will call recursively to insert and execute None = node(value) which will do nothing.
What happens if we use this definition instead:
def insert(Node, value):
print(Node)
if Node is None:
Node = node(value)
else:
if value < Node.data:
if Node.left is None:
Node.left = node(value)
else:
insert(Node.left, value)
else:
if Node.right is None:
Node.right = node(value)
else:
insert(Node.right, value)
On the REPL:
In [25]: newTree = node(4)
In [26]: insert(newTree, 10)
<__main__.node object at 0x7f706bf30668>
In [27]: insert(newTree, 12)
<__main__.node object at 0x7f706bf30668>
<__main__.node object at 0x7f706bf30a58>
Now see that it doesn't fail anymore, as we are keeping track of the memory addresses in the tree nodes and thus we can reference those objects (trees) which will let us do the insertions in-place.
Related
I need help,
I want to implement "Chain" Class in python with the following features:
>>> Chain(2.5)(2)(2)(2.5) # sum
9
>>> Chain(3)(1.5)(2)(3) # sum
9.5
>>> Chain(64) == 64
True
>>> Chain('Alex')('Smith')('is')('the')('best.') # concat with space
'Alex Smith is the best.'
>>> Chain('abc')('defg') == 'abc defg'
True
throw Exception when:
>>> Chain('Alex')(5) # raising exception with the following message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: invalid operation
>>> Chain(9)([1, 2]) # raising exception with the following message
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: invalid operation
class Chain:
def __init__(self,n):
self.Sum = n
def __call__(self,nums):
def __repr__(self):
pass
def __eq__(self,other):
return type(self) == type(other)
This should work with lists or any other object that has a __iadd__ method. I'm not sure if the items in an array should all be the same object for this assignment. Otherwise, you'll have implement it.
class Chain:
def __init__(self, n):
self.sum = n
def __call__(self, item):
try:
if isinstance(item, str):
self.sum += ' ' + item
else:
self.sum += item
except TypeError:
raise Exception('invalid operation')
return self
def __repr__(self):
return repr(self.sum)
def __eq__(self, other):
return self.sum == other
I have two different modules (files) where I store different objects.
The work flow is - call objects from different files and return the values from the database. If I call object from file_1 below, it returns required values from the database. However when I call object from file_1 in file_2, it returns 'None' even though input parameter is supplied.
file_1
class Database(object):
database = None
host = None
port = None
def __init__(self, host=None, port=None):
self.host=None
self.port=None
def client_(self):
return MongoClient()
def find_spefic_director(self, db=None, coll=None, directorId=None):
'''If when a specific director id is supplied it returns director related information'''
project={'_id': 0}
filter={'directorid': directorId}
print(directorId)
if not directorId is None:
result = self.client_()[db][coll].find(projection=project,
filter=filter)
return [i for i in result]
else:
return 'valid Id is required'
if __name__ == "__main__":
Database()
file_2
class Graph(object):
def __init__(self, host=None, port=None):
self.host=None
self.port=None
self.directorId=None
def minMaxDate(self, db=None, coll=None, directorId=None):
dr= Database(self.host, self.port).find_spefic_director(self.directorId)
drt=dr(directorId)
return drt
if __name__ == "__main__":
Graph()
Now I am trying to call Database() in file 2 for further processing in a different file
from file_1 import Database
from file_2 import Graph as gc
gc(directorId=340769.0).minMaxDate(db, coll='directory', directorId=340769.0)
when I run, it returns
None
TypeError Traceback (most recent call last)
<ipython-input-3-2d56a89c0288> in <module>
----> 1 gc().minMaxDate(db, coll='crsp_na_wrds_company_director_names', directorId=340769.0)
~/graph_construct.py in minMaxDate(self, db, coll, directorId)
25
26 dr= Database(self.host, self.port).find_spefic_director(self.directorId)
---> 27 drt=dr(directorId)
28
29
TypeError: 'str' object is not callable
What should be done to return the values stored in the database?
While trying to create a minimal, reproducible example for another problem in Python 3.7.3, I ran into a NoneType Error that I wasn't expecting.
Main program:
import worker
def multiply_worker_value(arguments):
current_Worker = arguments[0]
multiplier = arguments[1]
new_worker = current_Worker.change_value(multiplier)
return new_worker
current_worker = worker.Worker()
print("Printing value:")
print(current_worker.get_value()[0])
while(current_worker.get_value()[0] < 10):
paramList = [current_worker,2]
current_worker = multiply_worker_value(paramList)
print(current_worker.get_value()[0])
Worker class:
import numpy
class Worker():
def __init__(self):
self.values = numpy.random.rand(10)
def change_value(self,multiplier):
self.values = numpy.sum(self.values*multiplier)
def get_value(self):
return self.values
When this is run, I get:
Printing value:
0.10619190084595542
Traceback (most recent call last):
File "F:\Visual Studio\repos\Projects2020\tests\concurrent_test\concurrent_test\main.py", line 14, in <module>
while(current_worker.get_value()[0] < 10):
AttributeError: 'NoneType' object has no attribute 'get_value'
Press any key to continue . . .
and I am not sure why this is happening.
Inside the while loop, your current_worker gets overwritten with None:
current_worker = multiply_worker_value(paramList)
this calls:
new_worker = current_Worker.change_value(multiplier)
Your Worker.change_value method does not have a return statement, so it implicitly returns None.
Then, in the second iteration of your loop, your code tries to call get_value on None, which fails.
I was trying to implement some basic operations of Binary search tree in Python3.7. I have just started coding problems from Hackerrank and I got stuck while implementing levelOrder traversal in BST. What should I do to resolve this AttributeError: 'int' object has no attribute 'data'?
I am using queue to solve this problem, initially, the queue will point to root node, then checks for left and right children. If found, the children will get append to the queue and the process continues until the queue is empty. I am popping out the first element in each iteration and storing it in temp variable. This way i will get nodes at each level of tree.
class Node:
def __init__(self, data):
self.data = data
self.leftChild = None
self.rightChild = None
def insert(self, data):
if self.data is not None:
if data < self.data:
if self.leftChild is None:
self.leftChild = Node(data)
else:
self.leftChild.insert(data)
elif data > self.data:
if self.rightChild is None:
self.rightChild = Node(data)
else:
self.rightChild.insert(data)
else:
self.data = data
def traverseLevelOrder(self):
queue = []
queue.append(self.data)
while queue:
# Print front of queue and remove it from queue
print(queue[0].data)
temp = queue.pop(0)
# Enqueue left child
if temp.leftChild is not None:
queue.append(temp.leftChild)
# Enqueue right child
if temp.rightChild is not None:
queue.append(temp.rightChild)
class BST:
def __init__(self):
self.rootNode = None
def insert(self, data):
if self.rootNode is None:
self.rootNode = Node(data)
else:
self.rootNode.insert(data)
def traverseLevelOrder(self):
if self.rootNode is None:
return
else:
self.rootNode.traverseLevelOrder()
bst = BST()
bst.insert(2)
bst.insert(4)
bst.insert(1)
bst.insert(3)
bst.traverseLevelOrder()
The code should return the level traversal order like one given below(within a level it should print first left node then right node):
2
1
4
3
Instead, I am having the below error:
Traceback (most recent call last):
print(queue[0].data)
AttributeError: 'int' object has no attribute 'data'
You're appending an integer, self.data to the queue, then attempting to access a property on the integer with queue[0].data, causing the AttributeError to be raised.
Instead, append the node itself with:
queue.append(self)
queue.append(self.data)
Did you mean:
queue.append(self)
?
Right now you're only adding a number to the queue, not the whole object.
I tried to monkey patch an object in Python.
class C:
def __init__(self):
self.__n = 0
def f(self):
self.__n += 1
def __str__(self):
return str(self.__n)
c = C()
def up(self):
self.__n += 2
import types
c.up = types.MethodType(up, c)
c.up()
But I got an AttributeError
Traceback (most recent call last):
File "untitled4.py", line 19, in <module>
c.up()
File "untitled4.py", line 15, in up
self.__n += 2
AttributeError: 'C' object has no attribute '__n'
How can I fix the error?
As your up function isn't declared inside a class, it is not possible to apply name mangling rules to its locals, while it is applied for the attribute name. Therefore you'd need to apply the name mangling manually in your function:
def up(self):
self._C__n += 2