'int' Object Not Callable Heap Sort Function
Im trying to create a function that return a sorted list but im getting the following error: "new_value = sort_heap.deleteMin() 'int' object is not callable"
This is the code:
class MinHeap:
def __init__(self):
self.heap=[]
def __str__(self):
return f'{self.heap}'
__repr__=__str__
def parent(self,index):
# -- YOUR CODE STARTS HERE
if index>len(self) or index<=1:
return None
else:
return self.heap[index//2-1]
def leftChild(self,index):
# -- YOUR CODE STARTS HERE
if index<1 or 2*index>len(self):
return None
else:
return self.heap[2*index-1]
def rightChild(self,index):
if index<1 or 2*index>len(self):
return None
else:
return self.heap[2*index-1]
def __len__(self):
return len(self.heap)
def insert(self,x):
self.heap.append(x)
current = len(self)
while self.parent(current) is not None and self.parent(current)>x:
self.heap[current-1], self.heap[current//2-1] = self.heap[current//2-1], self.heap[current-1]
current = current//2
#property
def deleteMin(self):
if len(self)==0:
return None
elif len(self)==1:
out=self.heap[0]
self.heap=[]
return out
deleted = self.heap[0]
current = 1
self.heap[0] = self.heap[len(self)-1]
x = self.heap.pop()
moved_value = self.heap[0]
while self.leftChild(current) is not None:
left=self.leftChild(current)
right=self.rightChild(current)
if right is not None:
if left<=right and left<moved_value:
self.heap[current-1], self.heap[current*2] = self.heap[current*2], self.heap[current-1]
current = current *2
elif left>right and right<moved_value:
self.heap[current-1], self.heap[current*2] = self.heap[current*2], self.heap[current-1]
current = (current*2) + 1
else:
break
else:
if left<moved_value:
self.heap[current-1], self.heap[(current*2)-1] = self.heap[(current*2)-1], self.heap[current-1]
current = current*2
else:
break
return deleted
def heapSort(numList):
'''
>>> heapSort([9,7,4,1,2,4,8,7,0,-1])
[-1, 0, 1, 2, 4, 4, 7, 7, 8, 9]
'''
sort_heap = MinHeap()
for i in range (len(numList)):
sort_heap.insert(numList[i])
sortedList= []
lenght=len(numList)
while lenght >0:
new_value = sort_heap.deleteMin()
sortedList.append(new_value)
lenght -= 1
return sortedList
The MinHeap class is a given but I'm allow to modify it. Could Someone please help? Thanks
Seeing your (btw wrong formatted code, please redo the formatting) code I can see, that deleteMin is a #property and not a class method. Therefore you shuld write:
new_value = sort_heap.deleteMin
# ^ You see, no brackets here
Related
I've noticed that the code prints the date twice to the constructor and am having trouble understanding why since I believe I only instantiate the object once within my code.
This is the constructor
def __init__(self):
self.today = date.today()
print(self.today)
Here is where I instantiate it
self.data = database()
self.schedule_today = self.data.get_bulletin()
Full code for this section of the program with some unfinished functions
class database:
sch_today = ['apt: 8:00', "breakfast", "music", 'apt: 9:00', "therapy", 'apt: 12:00', "lunch"]
test_schedule = []
def __init__(self):
self.today = date.today()
print(self.today)
def get_parse_bulletin_list(self):
temp = []
index = 0
for i in self.sch_today:
if i[0:3] == 'apt':
while index%3 != 0:
temp.append('')
index+=1
temp.append(i)
else:
temp.append(i)
index += 1
return temp
def get_bulletin(self):
n_count = 1
temp = []
ref = self.get_parse_bulletin_list()
for i in ref:
if i[0:3] == 'apt':
temp.append(paper_scrap().get_layout())
n_count = 1
elif not i:
temp.append(Notecard().blank_layout())
#elif i[0:5] == '[hlf]':
#temp.append(Notecard())
elif n_count >= 3: #allign left
temp.append(Notecard())
else:
temp.append(Notecard())
n_count += 1
return temp
def update_schedule(self):
with open('calendar.txt') as r:
pass
class BulletinInterface(RelativeLayout):
def __init__(self, **kwargs):
super(BulletinInterface, self).__init__(**kwargs)
self.data = database()
self.schedule_today = self.data.get_bulletin()
self.l1 = BulletinArea(size_hint=(1,1),
padding=(38, 135, 37, 34),
orientation=('tb-lr'))
self.add_widget(self.l1)
self.b1 = Button(text="test",
background_color=(1, 1, 1, 1),
size_hint=(0.1, 0.1)
)
self.b1.bind(on_press=self.bulletin_init)
self.add_widget(self.b1)
# bulletin board initialize
self.bulletin_init()
def bulletin_init(self, touch=None):
self.init_bulletin(self.schedule_today)
def init_bulletin(self, element_list):
for i in element_list:
self.l1.add_widget(i)
Found the problem after reviewing the construction of the GUI. The KV language and regular python code were both instantiating the GUI, leading to duplicate function calls for everything.
everyone. I've got a bit of a problem I need to sort out, and I was hoping for some assistance on what to do. So, I have this Python 3.6 assignment I've been working on, regarding Singly Linked Lists. Most of my test cases for appending/prepending, removing from front and back, and deleting nodes altogether are going well so far. However, I have some issues with a few of my test cases. The issues revolve around my use of the __str__(self) and __repr__(self) functions.
Down below is the code I'm providing. (EDIT: I left only the test codes that has the faults that need fixing. All the other test cases are fine):
class LinkedList(object):
class Node(object):
# pylint: disable=too-few-public-methods
''' no need for get or set, we only access the values inside the
LinkedList class. and really: never have setters. '''
def __init__(self, value, next = None):
self.value = value
self.next = next
def __repr__(self):
return repr(self.value)
def __str__(self):
return str(self.value) + "; "
def __init__(self, initial=None):
self.front = self.back = self.current = None
def empty(self):
return self.front == self.back == None
def __iter__(self):
self.current = self.front
return self
def __str__(self):
string = 'List[ '
curr_node = self.front
while curr_node != None:
string += str(curr_node)
curr_node = curr_node.next()
string += ']'
return string
def __repr__(self):
nodes = []
curr = self.front
while curr:
nodes.append(repr(curr))
curr = curr.next
return '[' +', '.join(nodes) + ']'
def __next__(self):
if self.current:
tmp = self.current.value
self.current = self.current.next
return tmp
else:
raise StopIteration()
def push_front(self, value):
x = self.Node(value, self.front)
if self.empty():
self.front = self.back = x
else:
self.front = x
#you need to(at least) implement the following three methods
def pop_front(self):
if self.empty():
raise RuntimeError("Empty List")
x = self.front.value
self.front = self.front.next
if not self.front:
self.back = None
return x
def push_back(self, value):
if self.empty():
self.front = self.back = self.Node(value, None)
else:
x = self.Node(value, None)
self.back.next = x
self.back = x
def pop_back(self):
if self.empty():
raise RuntimeError("Empty List")
y = self.back.value
if not self.front.next:
self.front = self.back = None
else:
x = self.front
while x.next is not self.back:
x = x.next
x.next = None
self.back = x
return y
class TestInitialization(unittest.TestCase):
def test(self):
linked_list = LinkedList(("one", 2, 3.141592))
self.assertEqual(linked_list.pop_back(), "one")
self.assertEqual(linked_list.pop_back(), 2)
self.assertEqual(linked_list.pop_back(), 3.141592)
class TestStr(unittest.TestCase):
def test(self):
linked_list = LinkedList((1, 2, 3))
self.assertEqual(linked_list.__str__(), '1, 2, 3')
class TestRepr(unittest.TestCase):
def test(self):
linked_list = LinkedList((1, 2, 3))
self.assertEqual(linked_list.__repr__(), 'LinkedList((1, 2, 3))')
if '__main__' == __name__:
unittest.main()
Now, with the code out of the way, I'm going to provide the problems I'm getting in the console:
1) Error at TestInitialization. RuntimeError("Empty List")
2) Failure at TestRepr. AssertionError: '[]' != 'LinkedList((1, 2, 3))'
- []
+ LinkedList((1, 2, 3))
3) Failure at TestStr. AssertionError: 'List[ ]' != '1, 2, 3'
- List[ ]
+ 1, 2, 3
I hate to be a bother, but I'd like to ask for any advice or hints to help me correct my two failures and prevent the one error. So, is there any way I can use to try and do so? I would greatly appreciate it.
To make TestInitialization work, your init function hat to provide a linkage of
3.141592 -> 2 -> "one"
if init(...)ed with ("one", 2, 3.141592) - you can see that by inspecting the testcase, it pops from back and you need to match the values provided.
You can solve it by pushing each one onto the front in init:
def __init__(self, initial=None):
self.front = self.back = self.current = None
for i in initial:
self.push_front(i)
# I find this counterintuitive, blame your teacher.
To make TestStr work, you init it with (1,2,3) and have to provide an output of '(1,2,3)' - due to the way __init__ now works you need to collect all nodes into a list, and return it reverse-joined (or go from back to front through list):
def __str__(self):
elem = []
curr_node = self.front
while curr_node != None:
elem.append(str(curr_node.value)) # collect node values, not the "7; " str
curr_node = curr_node.next()
# join reversed list
return ', '.join(elem[::-1]) # need to reverse the list due to how __init__ works
To make TestRepr work, you need the __str__ output and prefix/postfix it with 'LinkedList((' and '))'
def __repr__(self):
return 'LinkedList(('+ str(self) + '))'
I can't test myself, as NameError: name 'unittest' is not defined.
I have an entire Deque Array class that looks like this:
from collections import deque
import ctypes
class dequeArray:
DEFAULT_CAPACITY = 10 #moderate capacity for all new queues
def __init__(self):
self.capacity = 5
capacity = self.capacity
self._data = self._make_array(self.capacity)
self._size = 0
self._front = 0
def __len__(self):
return self._size
def __getitem__(self, k): #Return element at index k
if not 0 <= k < self._size:
raise IndexError('invalid index')
return self._data[k]
def isEmpty(self):
if self._data == 0:
return False
else:
return True
def append(self, item): #add an element to the back of the queue
if self._size == self.capacity:
self._data.pop(0)
else:
avail = (self._front + self._size) % len(self._data)
self._data[avail] = item
self._size += 1
#def _resize(self, c):
#B = self._make_array(c)
#for k in range(self._size):
#B[k] = self._A[k]
#self._data = B
#self.capacity = capacity
def _make_array(self, c):
capacity = self.capacity
return (capacity * ctypes.py_object)()
def removeFirst(self):
if self._size == self.capacity:
self._data.pop(0)
else:
answer = self._data[self._front]
self._data[self._front] = None
self._front = (self._front + 1) % len(self._data)
self._size -= 1
print(answer)
def removeLast(self):
return self._data.popleft()
def __str__(self):
return str(self._data)
and when I try to print the deque in the main it prints out something like this,
<bound method dequeArray.__str__ of <__main__.dequeArray object at 0x1053aec88>>
when it should be printing the entire array. I think i need to use the str function and i tried adding
def __str__(self):
return str(self._data)
and that failed to give me the output. I also tried just
def __str__(self):
return str(d)
d being the deque array but I still am not having any success. How do I do i get it to print correctly?
you should call the str function of each element of the array that is not NULL, can be done with the following str function:
def __str__(self):
contents = ", ".join(map(str, self._data[:self._size]))
return "dequeArray[{}]".format(contents)
What I get when I try to q = dequeArray(); print(q) is <__main__.py_object_Array_5 object at 0x006188A0> which makes sense. If you want it list-like, use something like this (print uses __str__ method implicitly):
def __str__(self):
values = []
for i in range(5):
try:
values.append(self._data[i])
except ValueError: # since accessing ctypes array by index
# prior to assignment to this index raises
# the exception
values.append('NULL (never used)')
return repr(values)
Also, several things about the code:
from collections import deque
This import is never user and should be removed.
DEFAULT_CAPACITY = 10
is never used. Consider using it in the __init__:
def __init__(self, capacity=None):
self.capacity = capacity or self.DEFAULT_CAPACITY
This variable inside __init__ is never user and should be removed:
capacity = self.capacity
def _make_array(self, c):
capacity = self.capacity
return (capacity * ctypes.py_object)()
Though this is a valid code, you're doing it wrong unless you're absolutely required to do it in your assignment. Ctypes shouldn't be used like this, Python is a language with automated memory management. Just return [] would be fine. And yes, variable c is never used and should be removed from the signature.
if self._data == 0
In isEmpty always evaluates to False because you're comparing ctypes object with zero, and ctypes object is definitely not a zero.
class MyHashTable:
def __init__(self, capacity):
self.capacity = capacity
self.slots = [None] * self.capacity
def __str__(self):
return str(self.slots )
def __len__(self):
count = 0
for i in self.slots:
if i != None:
count += 1
return count
def hash_function(self, key):
slot = key % len(self.slots)
if key in self.slots:
return slot
elif (not key in self.slots) and len(self.slots) == self.capacity:
return slot
else:
for i in self.slots:
count = 0
if i == None:
return count
count += 1
def insert(self, key):
print(len(self.slots)) #Why does this show an output of 2?
if key in self.slots:
return -2
elif (not key in self.slots) and (len(self.slots) != self.capacity): #Now this cant execute
num = hash_function(key)
self.slots[num] = key
return num
elif (not key in self.slots) and len(self.slots) == self.capacity:
return -1
Im wondering why the commented part above in the insert(self, key) the print statement gives (2) instead of (0). The elif statement underneath wont execute since its giving a result of (2) instead of (0)
A function call of
x = MyHashTable(2)
print(len(x))
Should give: 0
You're initializing self.slots = [None] * self.capacity, so with capacity = 2, self.slots is [None, None], which is of length 2.
Your __len__ method doesn't run because len(self.slot) calls self.slot.__len__, not self.__len__. If you'd like to use your override method, you should be calling len(self) instead.
You have to call your __len__ function (by calling self.__len__() ) if you want the length of the elements which are not None. For lists None are valid entries.
By the way. It is always best to compare with None by a is None or a is not None instead of == or !=.
I need to operate on two separate infinite list of numbers, but could not find a way to generate, store and operate on it in python.
Can any one please suggest me a way to handle infinite Arithmetic Progession or any series and how to operate on them considering the fact the minimal use of memory and time.
Thanks every one for their suggestions in advance.
You are looking for a python generator instead:
def infinitenumbers():
count = 0
while True:
yield count
count += 1
The itertools package comes with a pre-built count generator.
>>> import itertools
>>> c = itertools.count()
>>> next(c)
0
>>> next(c)
1
>>> for i in itertools.islice(c, 5):
... print i
...
2
3
4
5
6
This is where the iterator comes in. You can't have an infinite list of numbers, but you can have an infinite iterator.
import itertools
arithmetic_progression = itertools.count(start,step) #from the python docs
The docs for Python2 can be found here
I have another python3 solution (read SICP chapter 3.5)
class Stream:
def __init__(self, head, tail):
self.head = head
self.tail = tail
self.memory = None
self.isDone = False
def car(self):
return self.head
def cdr(self):
if self.isDone:
return self.memory
self.memory = self.tail()
self.isDone = True
return self.memory
def __getitem__(self, pullFrom):
if pullFrom < 1 or self.memory == []:
return []
return [self.car()] + self.cdr()[pullFrom - 1]
def __repr__(self):
return "[" + repr(self.car()) + " x " + repr(self.tail) + "]"
def map(self, func):
if self.memory == []:
return []
return Stream(func(self.car()), lambda: Stream.map(self.cdr(), func))
def from_list(lst):
if lst == []:
return []
return Stream(lst[0], lambda:
Stream.from_list(lst[1:]))
def filter(self, pred):
if self.memory == []:
return []
elif pred(self.car()):
return Stream(self.car(), lambda: Stream.filter(self.cdr(), pred))
else:
return self.cdr().filter(pred)
def sieve(self):
return Stream(self.car(), lambda: self.cdr().filter(lambda n: n % self.car() > 0).sieve())
def foreach(self, action, pull = None):
if pull is None:
action(self.car())
self.cdr().foreach(action, pull)
elif pull <= 0:
return
else:
action(self.car())
self.cdr().foreach(action, pull-1)and run:
a = Stream(0, lambda: a.map((lambda x: x + 1)))
print(a[10])
which returns:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] .
But streams are lazily evaluated, so:
>>> a = Stream(0, lambda: a.map((lambda x: x + 1)))
>>> print(a)
prints:
[0 x [...]]
To create an object that acts like a "mutable" infinite list, you can overload the __getitem__ and __setitem__ methods in a class:
class infinite_list():
def __init__(self, func):
self.func = func
self.assigned_items = {}
def __getitem__(self, key):
if key in self.assigned_items:
return self.assigned_items[key]
else:
return self.func(key)
def __setitem__(self, key , value):
self.assigned_items[key] = value
Then, you can initialize the "infinite list" with a lambda expression and modify an item in the list:
infinite_thing = infinite_list(lambda a: a*2)
print(infinite_thing[1]) #prints "2"
infinite_thing[1] = infinite_thing[2]
print(infinite_thing[1]) #prints "4"
Similarly, it is possible to create an "infinite dictionary" that provides a default value for each missing key.
Perhaps the natural way to generate an infinite series is using a generator:
def arith(a, d):
while True:
yield a
a += d
This can be used like so:
print list(itertools.islice(arith(10, 2), 100))
My solution is:
from hofs import *
def cons_stream(head,tail):
return [head,tail,False,False]
def stream_cdr(strm):
if strm[2]:
return strm[3]
strm[3] = strm[1]()
strm[2] = True
return strm[3]
def show_stream(stream, num = 10):
if empty(stream):
return []
if num == 0:
return []
return adjoin(stream[0], show_stream(stream_cdr(stream), num - 1))
def add_streams(a , b):
if empty(a):
return b
if empty(b):
return a
return cons_stream(a[0] + b[0] , lambda : add_streams( stream_cdr(a), stream_cdr(b)))
def stream_filter( pred , stream ):
if empty(stream):
return []
if pred(stream[0]):
return cons_stream(stream[0], lambda : stream_filter(pred, stream_cdr(stream)))
else:
return stream_filter( pred , stream_cdr( stream ))
def sieve(stream):
return cons_stream(stream[0] , lambda : sieve(stream_filter(lambda x : x % stream[0] > 0 , stream_cdr(stream))))
ones = cons_stream(1, lambda : ones)
integers = cons_stream(1, lambda : add_streams(ones, integers))
primes = sieve(stream_cdr(integers))
print(show_stream(primes))
Copy the Python code above.
When I tried it, i got [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] which is 10 of an infinite list of primes.
You need hofs.py to be
def empty(data):
return data == []
def adjoin(value,data):
result = [value]
result.extend(data)
return result
def map(func, data):
if empty(data):
return []
else:
return adjoin(func(data[0]), map(func, data[1:]))
def keep(pred, data):
if empty(data):
return []
elif pred(data[0]):
return adjoin( data[0] , keep(pred, data[1:]))
else:
return keep(pred, data[1:])
I assume you want a list of infinite numbers within a range. I have a similar problem, and here is my solution:
c = 0
step = 0.0001 # the difference between the numbers
limit = 100 # The upper limit
myInfList = []
while c <= limit:
myInfList.append(c)
c = c + step
print(myInfList)