Inserting node in a binary search tree using temporary variable - binary-search-tree

enter code here please help me to solve
import sys
class Node:
def init(self,d):
self.left=None
self.data=d
self.right=None
global r
r=None
def insert():
global r
d=int(input('enter data:'))
if(r is None):
r=Node(d)
else:
t=r
while(t!=None):
if(d>t.data):
t=t.right
else:
t=t.left
t=Node(d)
print(r.left)
print(t.data)
while(True):
print('1.insert')
print('2.delete')
print('3.display')
print('4.exit')
ch=int(input('enter choice:'))
if(ch==1):
insert()
if(ch==2):
delete()
if(ch==3):
display()
if(ch==4):
sys.exit()

this my code
import sys
class Node:
def __init__(self,d):
self.left=None
self.data=d
self.right=None
global r
r=None
def insert():
global r
d=int(input('enter data:'))
if(r is None):
r=Node(d)
else:
t=r
while(t!=None):
if(d>t.data):
t=t.right
else:
t=t.left
t=Node(d)
print(r.left)
print(t.data)
while(True):
print('1.insert')
print('2.delete')
print('3.display')
print('4.exit')
ch=int(input('enter choice:'))
if(ch==1):
insert()
if(ch==2):
delete()
if(ch==3):
display()
if(ch==4):
sys.exit()

Related

How to write python unittest cases to mock redis connection (redis.StrictRedis) in Django

How can I mock the following function for connecting to Redis?
import redis
class RedisCache:
redis_instance = None
#classmethod
def set_connect(cls):
redis_instance = redis.StrictRedis(host='0.0.0.0', port=6379, password='xyz', charset='utf-8', decode_responses=True, socket_timeout=30)
return redis_instance
#classmethod
def get_conn(cls):
cls.redis_instance = cls.set_connect()
return cls.redis_instance
I looked for some solutions, but they were basically using fakeredis module. I wanted to have a simpler way to mock these functions.
Note-
data returned by the function: Redis<ConnectionPool<Connection<host=127.0.0.1,port=6379,db=0>>>
You can use patch() function to mock out redis.StrictRedis class. See where-to-patch
E.g.
redis_cache.py:
import redis
class RedisCache:
redis_instance = None
#classmethod
def set_connect(cls):
redis_instance = redis.StrictRedis(host='0.0.0.0', port=6379, password='xyz',
charset='utf-8', decode_responses=True, socket_timeout=30)
return redis_instance
#classmethod
def get_conn(cls):
cls.redis_instance = cls.set_connect()
return cls.redis_instance
test_redis_cache.py:
from unittest import TestCase
import unittest
from unittest.mock import patch, Mock
from redis_cache import RedisCache
class TestRedisCache(TestCase):
def test_set_connect(self):
with patch('redis.StrictRedis') as mock_StrictRedis:
mock_redis_instance = mock_StrictRedis.return_value
actual = RedisCache.set_connect()
self.assertEqual(actual, mock_redis_instance)
mock_StrictRedis.assert_called_once_with(host='0.0.0.0', port=6379, password='xyz',
charset='utf-8', decode_responses=True, socket_timeout=30)
#patch('redis.StrictRedis')
def test_get_conn(self, mock_StrictRedis):
mock_redis_instance = mock_StrictRedis.return_value
RedisCache.get_conn()
self.assertEqual(RedisCache.redis_instance, mock_redis_instance)
if __name__ == '__main__':
unittest.main()
test result:
..
----------------------------------------------------------------------
Ran 2 tests in 0.004s
OK
Name Stmts Miss Cover Missing
------------------------------------------------------------------------------
src/stackoverflow/70016401/redis_cache.py 11 0 100%
src/stackoverflow/70016401/test_redis_cache.py 18 0 100%
------------------------------------------------------------------------------
TOTAL 29 0 100%

Simliest and pythonic way to Serialize/Deserialize Object <->dict <-> JSON in Python3.5+

I am new to python, and I know there are many answers, but most of the use the __dict__ which is not present in Python3 any more.
Let's say I have object:
class A(object):
def __init__(self, f1, f2):
self.f1 = f1
self.f2 = f2
now the f2 is another object:
class F2(object):
def __init__(self, f21, f22):
self.f21 = f21
self.f22 = f22
So A object is complex object. What is the simpliest way to:
serialize A to dict and than to json.
and then to deserialize it back from json -> A
all in Python 3.5+ and possibly without additional imports as our internal company nexus is limited.
import pickle
import base64
import json
class A(object):
def __init__(self, f1, f2):
self.f1 = f1
self.f2 = f2
a = pickle.dumps(A, 3)
j = base64.b64encode(a).decode('utf-8')
x = json.dumps([j])
print(a)
print(j)
print(x)
# output:
# b'\x80\x03c__main__\nA\nq\x00.'
# gANjX19tYWluX18KQQpxAC4=
# ["gANjX19tYWluX18KQQpxAC4="]
Deserialization would be the inverse; json.loads, string.encode base64.b64decode, pickle.loads.

QTableView no longer showing rows since update to 5.7.1

I recently updated from PyQt 5.7.0 to 5.7.1 and code that worked correctly prior to the update stopped working correctly. So, either my code was always wrong but PyQt5 allowed it to work, or a bug was introduced in PyQt 5.7.1.
I have a custom table view that inherits from QTableView using a custom model that inherits from QAbstractTableModel. When new rows are added to the model, they are not visible in the table view. In fact, no rows ever become visible. Through some debugging, I have validated that the number of rows is changing as expected in my derived model class.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import PyQt5.Qt
class JobTableModel(QAbstractTableModel):
def __init__(self, data, parent):
super(JobTableModel, self).__init__()
assert isinstance(parent, QTableView), "'parent' is not a QTableView object"
self._parent = parent
self._data = data
self._rows = 0
self._updateModel()
# end constructor
def updateRows(self, rows):
self.layoutAboutToBeChanged.emit()
self._rows = rows
self.layoutChanged.emit()
# end updateRows
def _updateModel(self):
# Only update rows that are visible to the user
# Note: self._parent is a QTableView
minRow = self._parent.rowAt(0)
if minRow >= 0:
maxRow = self._parent.rowAt(self._parent.height())
if maxRow < 0: maxRow = self._rows - 1
for row in range(minRow, maxRow + 1):
self.dataChanged.emit(self.index(row, 0), self.index(row, self.columnCount(None) - 1))
QTimer.singleShot(490, self._updateModel)
# end _updateModel
def headerData(self, section, orientation, role):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return str(section)
#
# end headerData
def rowCount(self, modelIndex):
return self._rows
# end rowCount
def columnCount(self, modelIndex):
return 8 # always the same number of columns
# end columnCount
def data(self, index, role):
if not index.isValid(): return None
if role == Qt.DisplayRole: return '{0}, {1}'.format(index.row(), index.column())
return None
# end data
class JobTableView(QTableView):
def __init__(self, data, parent):
super(JobTableView, self).__init__(parent)
self.setModel(JobTableModel(data, self))
self.setAlternatingRowColors(True)
self.setWordWrap(False)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.verticalHeader().setVisible(False)
self.verticalHeader().setDefaultSectionSize(23)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
if __name__ == '__main__':
app = QApplication(sys.argv)
tv = JobTableView(None, None)
tv.show()
tv.model().updateRows(1)
app.exec_()
I ran the test case using PyQt-5.7, PyQt-5.7.1 and PyQt-5.7.2.dev1701131704 (built with SIP-4.19.1.dev1701101411). The problem is reproducible in PyQt-5.7.1, but not in the other two versions. So, as was suggested in the comments, there is a bug in PyQt-5.7.1 which has already been fixed in the latest snapshots.

Python 3.4 / GTK / Async

I use tkinter with a async funktion.
Now I will use gtk3 in stead of tkinkter.
Is there also a way to run my async function?
How should I adapt the code
Here are some code fragments:
async def _event_loop(app, interval=0.05):
try:
while True:
app.update()
await asyncio.sleep(interval)
except tkinter.TclError as exc:
if "application has been destroyed" not in exc.args[0]:
raise
class SSHFrame(tkinter.Frame):
def __init__(self, parent):
super().__init__(parent)
...
...
async def _run(self, host, command, user, password):
try:
async with asyncssh.connect(host, username=user, password=password,
client_keys=None) as conn:
self._proc = await conn.create_process(command,
term_type='dumb')
while not self._proc.stdout.at_eof():
self._output(await self._proc.stdout.read(1024))
self._output('\n[Disconnected]\n')
except (asyncssh.Error, OSError) as exc:
self._output('[%s]\n' % str(exc))
finally:
self._proc = None
class App(tkinter.Frame):
def __init__(self, parent):
super().__init__(parent)
...
...
asyncio.get_event_loop().run_until_complete(_event_loop(App(tkinter.Tk())))
import asyncio
import sys
from gi.repository import Gtk, GLib
#asyncio.coroutine
def start(app):
yield from asyncio.sleep(0)
app.register()
app.activate()
def glib_update(main_context, loop):
while main_context.pending():
main_context.iteration(False)
loop.call_later(.01, glib_update, main_context, loop)
if sys.platform == "win32":
from asyncio.windows_events import ProactorEventLoop
loop = ProactorEventLoop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
# This is just a fake gtk appliaction here, you should create your own see
# http://python-gtk-3-tutorial.readthedocs.io/en/latest/application.html
my_gtk_app = Gtk.Application()
try:
main_context = GLib.MainContext.default()
asyncio.async(start(my_gtk_app))
glib_update(main_context, loop)
loop.run_forever()
finally:
loop.close()

Python: Anything wrong with dynamically assigning instance methods as instance attributes

I came up with the following code to decorate instance methods using a decorator that requires the instance itself as an argument:
from functools import wraps
def logging_decorator(tricky_instance):
def wrapper(fn):
#wraps(fn)
def wrapped(*a, **kw):
if tricky_instance.log:
print("Calling %s.." % fn.__name__)
return fn(*a, **kw)
return wrapped
return wrapper
class Tricky(object):
def __init__(self, log):
self.log = log
self.say_hi = logging_decorator(self)(self.say_hi)
def say_hi(self):
print("Hello, world!")
i1 = Tricky(log=True)
i2 = Tricky(log=False)
i1.say_hi()
i2.say_hi()
This seems to work great, but I fear that I may have overlooked some unintended side effects of this trick. Am I about to shoot myself in the foot, or is this safe?
Note that I don't actually want to use this for logging, it's just the shortest meaningful example I could come up with.
It's not really clear to me why you would ever want to do this. If you want to assign a new method type dynamically use types:
import types
class Tricky(object):
def __init__(self):
def method(self):
print('Hello')
self.method = types.MethodType(method, self)
If you want to do something with the instance, do it in the __init__ method. If you just want access to the method's instance inside the decorator, you can use the im_self attribute:
def decorator(tricky_instance):
def wrapper(meth):
print(meth.im_self == tricky_instance)
return meth
return wrapper
Personally, I think this is veering into Maybe-I-Shouldn't-Use-Decorators land.
I think I was trying to be needlessly smart. There seems to be an embarrassingly simpler solution:
from functools import wraps
def logging_decorator(fn):
#wraps(fn)
def wrapped(self, *a, **kw):
if self.log:
print("Calling %s.." % fn.__name__)
return fn(self, *a, **kw)
return wrapped
class Tricky(object):
def __init__(self, log):
self.log = log
#logging_decorator
def say_hi(self):
print("Hello, world!")
i1 = Tricky(log=True)
i2 = Tricky(log=False)
i1.say_hi()
i2.say_hi()