Heap Structure with Key Function in initalizer - python-3.x

I'm basically trying to implement this Heap Structure in Python and I've editing the portions under def heap-iffy and def add but I'm not sure how to how to use the current initialize with a key function. This function will be used to extract a value from each element added to the heap; these values, in turn, will be used to order the elements. f no key function is provided, the default max-heap behavior should be used — the "lambda x:x" default value for the initialize method does just that.
class Heap:
def __init__(self, key=lambda x:x):
self.data = []
self.key = key
#staticmethod
def _parent(idx):
return (idx-1)//2
#staticmethod
def _left(idx):
return idx*2+1
#staticmethod
def _right(idx):
return idx*2+2
def _heapify(self, idx=0):
enter code here
while True:
l = Heap._left(idx)
r = Heap._right(idx)
maxidx = idx
if l < len(self) and self.data[l] > self.data[idx]:
maxidx = l
if r < len(self) and self.data[r] > self.data[maxidx]:
maxidx = r
if maxidx != idx:
self.data[idx], self.data[maxidx] = self.data[maxidx], self.data[idx]
idx = maxidx
else:
break
def add(self, x):
enter code here
self.data.append(x)
i = len(self.data) - 1
p = Heap._parent(i)
while i > 0 and self.data[p] < self.data[i]:
self.data[p], self.data[i] = self.data[i], self.data[p]
i = p
p = Heap._parent(i)
def peek(self):
return self.data[0]
def pop(self):
ret = self.data[0]
self.data[0] = self.data[len(self.data)-1]
del self.data[len(self.data)-1]
self._heapify()
return ret
def __bool__(self):
return len(self.data) > 0
def __len__(self):
return len(self.data)
def __repr__(self):
return repr(self.data)

Related

Trying to implement a hashMap using an array from LeetCode

I can't seem to pass all the tests that leetcode gives. I can pass 35/36 test cases and the one error that it has is the get key 623 on one of the test cases gives the wrong number. I have the test case that it didn't pass but it is really long so I don't want to post it on the question.
class pairValue:
def __init__(self, key, value):
self.key = key
self.value = value
class MyHashMap(object):
def __init__(self):
self.size = 0
self.capacity = 2
self.hashMap = [None, None]
def hash(self, key):
return key % self.capacity
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
# if key == 623:
# print(value)
if self.size >= self.capacity //2:
self.rehash()
index = self.hash(key)
while self.hashMap[index] != None and self.hashMap[index].key != -1:
if self.hashMap[index].key == key:
self.hashMap[index].value = value
# print(self.hashMap[index].key,value)
return
index += 1
index %= self.capacity
self.hashMap[index] = pairValue(key, value)
if self.hashMap[index].key != -1:
self.size += 1
def rehash(self):
self.capacity *= 2
newMap = [None] * self.capacity
oldMap = self.hashMap
self.hashMap = newMap
self.size = 0
for x in range(len(oldMap)):
if oldMap[x] != None:
self.put(oldMap[x].key, oldMap[x].value)
# print(self.hashMap)
def get(self, key):
"""
:type key: int
:rtype: int
"""
index = self.hash(key)
# print(self.hashMap[index].key, self.hashMap[index].value)
while self.hashMap[index] != None:
if self.hashMap[index].key == 623:
print(self.hashMap[index].value)
if self.hashMap[index].key == key:
return self.hashMap[index].value
index += 1
index %= self.capacity
# print(self.hashMap)
return -1
def remove(self, key):
"""
:type key: int
:rtype: None
"""
index = self.hash(key)
while self.hashMap[index] != None:
if self.hashMap[index].key == key:
self.hashMap[index].key = -1
self.hashMap[index].value = None
self.size -= 1
index += 1
index %= self.capacity
There are five functions which are to put, get, remove, hash, and rehash, along with the initialization.

"list object has no attribute " error while passing parameter to a function

I am trying to solve a problem to add two numbers using link list. I have used the below code which is complied correctly. But if I want to test it by passing parameters I am getting an error " list object has no attribute 'val'
#Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode)--> ListNode:
dummy = ListNode()
cur = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# new digit
val = v1 + v2 + carry
carry = val // 10
val = val % 10
cur.next = ListNode(val)
# update ptrs
cur = cur.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
a =Solution()
a.addTwoNumbers([1,2,3],[4,5,6])
edit
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def __init__(self):
self.head=None
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode()
cur = dummy
carry = 0
while l1 or l2 or carry:
v1 = l1.val if l1 else 0
v2 = l2.val if l2 else 0
# new digit
val = v1 + v2 + carry
carry = val // 10
val = val % 10
cur.next = ListNode(val)
# update ptrs
cur = cur.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return dummy.next
def insert_at_end(self,val):
if self.head is None:
self.head=ListNode(val,None)
return
itr=self.head
while itr.next:
itr=itr.next
itr.next=ListNode(val,None)
def print(self):
if self.head is None:
print("Linked List is empty")
return
itr=self.head
llstr=""
while itr:
llstr +=str(itr.val)
itr=itr.next
print(llstr)
ll=Solution()
ll.insert_at_end([1,2,3])
ll.insert_at_end([4,5,6])
ll.print()

Python - 'int' object is not callable

I'm writing a singly linked list that counts the number of words that get imported from a test file.
I initialized count inside of my class.
I defined the print function, that prints out each of the nodes, after they are sorted.
I defined a count class to iterate through the list and count up all the occurences of a word fed to it.
I want to pass in every node into count to count how many times it appears in my text file. When I try to do that I end up with 'int' object is not callable. Here is my code
class Linked_List:
def __init__(self):
self.head = None
self.count = 1
def print(self):
p = self.head
head = Linked_List_node(p.data)
while p is not None:
print(p.data, '-', self.count(p.data)) # This is where the error appears
p = p.next
def count(self, x):
# loop thru list for all x, if find x add 1 to count. Assign final count to that word.
with open('cleaned_test.txt', 'r') as f:
for line in f:
for word in line.split():
if word == x:
self.count += 1
def insert(self, x):
""""""
p = self.head
q = None
done = False
while not done:
if self.head == x:
done = True
elif p == None:
head = Linked_List_node(x)
q.next = head
done = True
elif x == p.data:
#head = Linked_List_node(x)
#head.counter += 1
done = True
elif x < p.data:
if self.head == p:
head = Linked_List_node(x)
head.next = p
self.head = head
done = True
else:
head = Linked_List_node(x)
head.next = p
q.next = head
done = True
q = p
if p is not None:
p = p.next
class Linked_List_node:
def __init__(self, value):
self.data = value
self.next = None
Relevant part from your code is:
class Linked_List:
def __init__(self):
# ...
self.count = 1
def count(self, x):
# ...
The self.count = 1 assignment overwrites the value of self.count for every Linked_List object that's created, so it refers to 1 instead of the method you defined on the class. Rename either the variable or the function.

Why does isinstance returns false after dynamic instance creating?

I have a problem while trying to create and instance based on the given dictionary.
My current code:
class Number(object):
def __init__(self, value):
self.value = value
def evaluate(self):
return self.value
def to_dict(self):
return self.value
class ArithmeticNode(object):
OPERATORS_TO_CLASSES = dict(map(lambda cls: (cls.OPERATOR, cls),
ArithmeticNode.__subclasses__()))
def __init__(self, val1, val2):
self.val1 = val1 if isinstance(val1, ArithmeticNode) else Number(val1)
self.val2 = val2 if isinstance(val2, ArithmeticNode) else Number(val2)
def to_dict(self):
v1 = self.val1.to_dict()
v2 = self.val2.to_dict()
return {self.OPERATOR: [v1, v2]}
#staticmethod
def from_dict(d):
cls_dict = ArithmeticNode.OPERATORS_TO_CLASSES
def create_node(d):
nonlocal cls_dict
if isinstance(d, dict):
for operator, (left_val, right_val) in d.items():
cls_inst_to_create = cls_dict[operator]
value_1 = create_node(left_val)
value_2 = create_node(right_val)
return cls_inst_to_create(value_1, value_2)
else:
return d
return create_node(d)
class AddNode(ArithmeticNode):
OPERATOR = '+'
def evaluate(self):
return self.val1.evaluate() + self.val2.evaluate()
When Im doing:
a = AddNode(3, AddNode(5, 3)) # Everything works just perfect
d = a.to_dict() # {'+': [3, {'+': [5, 3]}]}
c = ArithmeticNode.from_dict(d)
print(c) # <__main__.AddNode object at 0x7fac20def908>
# Trying to check if this is still the instance of ArithmeticNode
isinstance(c, ArithmeticNode)
> False
So my question is: why does isinstance returns False in this case, when:
a = AddNode(3, AddNode(5, 3))
isinstance(a, ArithmeticNode)
True
Sorry if it is obvious for you, but I can not find out why it works like that.

rewriting Tree like function without recursive

class block(object):
def __init__(self, N):
self.N = N; self.l, self.r, self.u, self.d = [None]*4
def move_lower(self):
res = []
for x in (self.u, self.d, self.l, self.r):
if x != None and x.N < self.N:
res.append(x)
return res
def move_lower_chain(self, res = [], history = []):
temp = self.move_lower()
if len(temp) == 0:
res.append(history + [self.N])
else:
for x in temp:
x.move_lower_chain(res, history + [x.N])
return res
I tried to change the 'move_lower_chain' function to Non-recursive function, but i couldn't and even didn't know how to solve. most difficult part was below:
for x in temp:
x.move_lower_chain(res, history + [x.N])
Is there anyone who can help me?

Resources