Byte size not increasing in a dynamic array in Python - python

import ctypes
import sys
class DynamicArray(object):
def __init__(self):
self.n =
self.capacity = 1
self.A = self.make_array(self.capacity)
def __len__(self):
return self.n
def __getitem__(self,k):
if not 0 <= k <self.n:
return IndexError('K is out of bounds!')
return self.A[k]
def append(self, ele):
if self.n == self.capacity:
self._resize(2*self.capacity)
self.A[self.n] = ele
self.n += 1
def _resize(self,new_cap):
B = self.make_array(new_cap)
for k in range(self.n):
B[k] = self.A[k]
self.A = B
self.capacity = new_cap
def make_array(self,new_cap):
return (new_cap * ctypes.py_object)()
When I use
arr = DynamicArray()
and after inserting about 10 to 20 numbers the byte size remains the same.
This is how I check the size of the array:
sys.getsizeof(arr)
The byte size shows to be 56 throughout.

Related

How to use a value from first method in second method (in the same class)?

I want to use the d value from can_add method for add method, but get error 'MoneyBox' object has no attribute 'd'. How to use d value for add method?
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
def can_add(self, v):
self.v = v
if self.capacity > self.v:
self.d = True
return d
else:
self.d = False
return self.d
def add(self, v):
self.can_add(v)
if self.d == True:
self.v += v
f = self.capacity - self.v
return f
a = MoneyBox(10)
a.add(5)
d isn't a variable of the class but only in can_add method hence you can't access it in add method.
more so, you don't need it anyway, just return true/false.
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
def can_add(self, v):
if self.capacity > v:
return True
else:
return False
def add(self, v):
if self.can_add(v) == True:
v += v
f = self.capacity - v
return f
a = MoneyBox(10)
a.add(5)
You are trying to return a class variable when you want to return a local variable.
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
def can_add(self, v):
self.v = v
if self.capacity > self.v:
d = True
return d
else:
d = False
return d
def add(self, v):
d = self.can_add(v)
if d == True:
self.v += v
f = self.capacity - self.v
return f
a = MoneyBox(10)
a.add(5)
If you want the value to be saved in a class variable you can do it like this
class MoneyBox:
def __init__(self, capacity = 0):
self.capacity = capacity
self.d = False
def can_add(self, v):
self.v = v
if self.capacity > self.v:
self.d = True
else:
self.d = False
def add(self, v):
self.can_add(v)
if self.d == True:
self.v += v
f = self.capacity - self.v
return f
a = MoneyBox(10)
a.add(5)

Why does self variable lose value after method invocation

I have this code to implement queue and stack data structures. The QueueT by itself works as desired.
When I call st.push(1), it agreeable calls push(self, v) and this in turn calls the enqueue method.
The issue I am facing is that after the statement self._q1.enqueue(v) is executed, self._q1 does not retain the value v.
Code for class QueueT:
class QueueT:
def __init__(self):
self._CAPACITY = 6
self._data = [None] * self._CAPACITY
self._length = 0
self._first = 0
def enqueue(self, val):
if self.size() == self._CAPACITY:
self._resize(self._CAPACITY * 2)
self.enqueue(val)
else:
new_place = (self._first + self.size()) % self._CAPACITY
self._data[new_place] = val
self._length += 1
def size(self):
return self._length
def _resize(self, new_capacity):
old = self._data
old_capacity = len(old)
self._data = [None] * new_capacity
k = self._first
self._first = 0
for j in range(self._length):
self._data[j] = old[k]
k = (1 + k) % old_capacity
self._CAPACITY = new_capacity
Now code from StackFromQ:
class StackFromQ:
def __init__(self):
self._q1 = QueueT()
self._top = -1
def push(self, v):
self._q1.enqueue(v)
self._top += 1
Caller function:
def stack_of_q():
st = StackFromQ()
st.push(1)
st.push(2)
Finally invocation:
stack_of_q()

Dynamic Array Type Error on making the list function

New to data structures and Algorithms trying out Dynamic Arrays
import ctypes
class DynamicArray(object):
def __init__(self):
self.count = 0
self.capacity = 1
self.A = self.make_array(self.capacity)
def __len__(self):
return self.count
def get(self, x):
if not 0 <= x < self.count:
return IndexError(f'Your value is {x} is out of bounds ')
return self.A[x]
def append(self, x):
if self.count == self.capacity:
self._resize(2 * self.capacity)
self.A[self.count] = x
self.count += 1
def _resize(self, new_cap):
B = self.make_array(new_cap)
for i in range(self.count):
B[x] = self.A[x]
self.A = B
self.capacity = new_cap
def make_array(self):
return (new_cap * ctypes.py_objects)()
arr = DynamicArray()
arr.append(1)
When I test run the code I get the error that
ln8: self.A = sekf.make_array(self.capacity) TypeError: make_array()
takes in 1 positional arguments and 2 were given
I do not understand because I only passed in one argument unless I am not understanding please help
On the function
def make_array(self, new_cap):
return (new_cap * ctypes.py_objects)()
The argument 'new_cap' was missing hence throwing the 1 argument error

Min stack solution not working for leetcode

I'm trying a leetcode min stack problem and my code is not working, tried finding a solution but can't see what's wrong. It seems to work for most inputs but fails "
["MinStack","push","push","push","top","pop","getMin","pop","getMin","pop","push","top","getMin","push","top","getMin","pop","getMin"]
[[],[2147483646],[2147483646],[2147483647],[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[],[],[],[]]" .
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.count = 0
self.minEle = -1
def push(self, x: int) -> None:
if self.count == 0:
self.minEle = x
self.stack.append(x)
elif x < self.minEle:
self.stack.append(2*x - self.minEle)
self.minEle = x
elif x >= self.minEle:
self.stack.append(x)
self.count += 1
def pop(self) -> None:
y = self.stack.pop()
if y < self.minEle:
self.minEle = 2*self.minEle - y
self.count -= 1
def top(self) -> int:
if self.count >=1:
return self.stack[(self.count - 1)]
else:
return 0
def getMin(self) -> int:
return self.minEle
Try:
class MinStack:
def __init__(self):
self.sc = []
self.sm = []
# #param x, an integer
# #return an integer
def push(self, x):
self.sc.append(x)
if x <= self.getMin():
self.sm.append(x)
return x
# #return nothing
def pop(self):
if self.sc.pop() == self.getMin():
self.sm.pop()
# #return an integer
def top(self):
return self.sc[-1]
# #return an integer
def getMin(self):
try:
return self.sm[-1]
except IndexError:
return self.top()
obj = MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
print(obj.getMin())
obj.pop()
print(obj.top())
print(obj.getMin())
param_3 = obj.top()
param_4 = obj.getMin()

Create an insert and pop method on list class

I need to implement an insert method (insert(self, index, val)), that inserts val before index, and a pop method (pop(self)), that removes the last element from mylist, onto the MyList class. The behavior should be identical to the methods already available in python.
Note: For the insert method, similarly with the append method already done, the capacity of the array should be doubled if there is no room for an additional element. The pop method should return the element removed from the list, and put None
in its place in the array. If pop was called on an empty list, an IndexError
exception should be raised.
My code thus far:
import ctypes # provides low-level arrays
def make_array(n):
return (n * ctypes.py_object)()
class MyList:
def __init__(self):
self.data = make_array(1)
self.capacity = 1
self.n = 0
def __len__(self):
return self.n
def append(self, val):
if(self.n == self.capacity):
self.resize(2 * self.capacity)
self.data[self.n] = val
self.n += 1
def resize(self, new_size):
new_array = make_array(new_size)
for ind in range(self.n):
new_array[ind] = self.data[ind]
self.data = new_array
self.capacity = new_size
def extend(self, other):
for elem in other:
self.append(elem)
def __getitem__(self, ind):
if not(0 <= ind <= self.n - 1):
raise IndexError('MyList index is out of range')
return self.data[ind]
def __setitem__(self, ind, val):
if not(0 <= ind <= self.n - 1):
raise IndexError('MyList index is out of range')
self.data[ind] = val
mylst1 = MyList()
for i in range(5):
mylst1.append(i)

Categories

Resources