implemention of "Sum" calss with Dunder in Python - python-3.x

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

Related

Python Pickle Problem - Output not matching with Hackerrank

I’m trying to solve the below question on Hackerrank.
It is working on Pycharm IDE but on Hackerrank the output is not matching with the expected output given. Below is the Code I used
import os
import builtins
import pickle
import sys
sys.tracebacklimit = 0
import traceback
import io
from logging import Logger
safe_builtins = {
'range',
'complex',
'set',
'frozenset'
}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
# Forbid everything else.
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
(module, name))
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
def func1(a):
try:
x = restricted_loads(pickle.dumps(a))
return a
except pickle.UnpicklingError:
s = traceback.format_exc()
return s
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0, 8, 3)))
return s[x]
except pickle.UnpicklingError:
s = traceback.format_exc()
return s
if __name__ == "__main__":
a = range(int(input()))
b = func1(a)
print(b)
y = tuple(input())
z = func2(y)
print(z)
Expected Output:
range(0, 50):
Traceback (most recent call last):
_pickle.UnpicklingError: global 'builtins.slice' is forbidden
Actual Output:
range(0, 50):
_pickle.UnpicklingError: global 'builtins.slice' is forbidden
Question: Why does the output not match in hackerrank when the code seems to be correct?
This is an acceptable answer for Hackerrank. I included sys.stdout.write("Traceback (most recent call last):\n") since we declared the traceback=0 initially and pickle.UnpicklingError class doesn't have a traceback message. Try the below code for Hacker rank.
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0, 8, 3)))
return s[x]
except pickle.UnpicklingError as e :
sys.stdout.write("Traceback (most recent call last):\n")
s = traceback.format_exc()
return s
PS: This is just an acceptable answer for Hackerrank. I just made simple modifications according to the output needs. This might not be a good practice everywhere. And I dont have full knowledge of it either.
import os
import builtins
import pickle
import sys
sys.tracebacklimit=0
import traceback
import io
from logging import Logger
safe_builtins = {
'range',
'complex',
'set',
'frozenset'
}
class RestrictedUnpickler(pickle.Unpickler):
def find_class(self, module, name):
# Only allow safe classes from builtins.
if module == "builtins" and name in safe_builtins:
return getattr(builtins, name)
# Forbid everything else.
raise pickle.UnpicklingError("global '%s.%s' is forbidden" %
(module, name))
def restricted_loads(s):
"""Helper function analogous to pickle.loads()."""
return RestrictedUnpickler(io.BytesIO(s)).load()
def func1(a):
try:
x = restricted_loads(pickle.dumps(a))
return a
except pickle.UnpicklingError:
s = traceback.format_exc()
return s
def func2(s):
try:
x = restricted_loads(pickle.dumps(slice(0, 8, 3)))
return s[x]
except pickle.UnpicklingError as e :
sys.stdout.write("Traceback (most recent call last):\n")
s = traceback.format_exc()
return s
if __name__ == "__main__":
a = range(int(input()))
b = func1(a)
print(b)
y = tuple(input())
z = func2(y)
print(z)

How to access the reference to the head node in this doubly linked list?

reference data types:
class DLLNode:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
class DLList:
def __init__(self):
self.head = None
self.tail = None
class Solution:
def sortedInsert(self, head, D):
I tried to access the head node's reference but it doesn't seem to work. What is the mistake that I'm doing here?
My Attempt:
class Solution:
def sortedInsert(self, head, D):
itr = head
while itr:
print(itr.val)
itr = itr.next
return head
The error:
Traceback (most recent call last):
File "main.py", line 107, in <module>
retval = Solution().sortedInsert( head, D )
File "main.py", line 86, in sortedInsert
print(itr.val)
AttributeError: 'DLList' object has no attribute 'val'

Insert function for bst not working

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.

Having trouble with Built-in Exception: ModuleNotFoundError

Having trouble with Built-in Exception: ModuleNotFoundError. I see nothing wrong with this solution, but am getting an Error. Checked out the docs but couldn't figure it out
folder structure
app
__init__.py
logic.py
test
__init__.py
test_logic.py
this error comes when i try to run the file from the command line directly --python test/test_logic.py
(tdd) D:\code\Outcome-15>coverage run test/test_logic.py
Traceback (most recent call last):
File "test/test_logic.py", line 3, in <module>
from app.logic import FizzBuzz
ModuleNotFoundError: No module named 'app'
logic.py
class FizzBuzz:
def fizz_buzz_service(self, num):
number_types = (int, float, complex)
if isinstance(num, number_types):
if num % 5 == 0 and num % 3 == 0:
return 'FizzBuzz'
elif num % 5 == 0:
return 'Buzz'
elif num % 3 == 0:
return 'Fizz'
else:
return num
else:
raise ValueError
test_logic.py
import unittest
from app.logic import FizzBuzz
class FizzBuzzServiceTestCases(unittest.TestCase):
"""
docstring for FizzBuzzServiceTestCases goes here!
"""
def setUp(self):
"""
Create an instance of fizz_buzz_service
"""
self.fizzbuzz = FizzBuzz()
def test_it_returns_a_number(self):
"""
Test for the default behavior of returning a number if not divisible by 3, 5 or both
"""
self.assertEqual(7, self.fizzbuzz.fizz_buzz_service(7))
def test_should_return_Fizz(self):
self.assertEqual("Fizz", self.fizzbuzz.fizz_buzz_service(3))
def test_should_return_Buzz(self):
self.assertEqual('Buzz', self.fizzbuzz.fizz_buzz_service(5))
def test_should_return_FizzBuzz(self):
self.assertEqual('FizzBuzz', self.fizzbuzz.fizz_buzz_service(15))
def test_should_return_error_message_if_arg_not_number(self):
with self.assertRaises(ValueError):
self.fizzbuzz.fizz_buzz_service('five')
if __name__ == '__main__':
unittest.main()

AttributeError when monkey patching an object in python

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

Resources