The following program is about extending the stack to perform operations push, pop and max (find the maximum value in stack)
class stack:
def __init__(self):
self.stack=[]
def push(self,n):
self.stack.append(n)
def pop(self):
assert(self.stack)
n=self.stack.pop(len(self.stack)-1)
def max(self):
new_list=self.stack
new_list.sort()
return new_list[-1]
In the max function, in the new_list, the list being copied also have the popped elements or the pop function is not being reflected in new_list, why is that?
Related
I am trying to use
class reader
def __init__(self, name, booksread)
self.name = name
self.booksread = booksread
while True
option = input("Choose an option: ")
if option = 1:
#What to put here?
I want to create an unlimited number of instances of the reader class, But I could only figure out how to do it a limited number of times by using variables for the class. I also need to call the info later (without losing it). Is it possible to do this with a class? Or would I be better off with a list, or dictionary?
First: if option == 1: is always false in python 3, input only reads strings there.
Second: python lists can be expanded until you run out of RAM.
So the solution would be to create a list in the surrounding code and call append on that every time you have a new item:
mylist = []
while True:
mylist.append(1)
It's perfectly possibly to populate a data structure (such as a list or dict) with instances of a class, given your code example you could put the instances into a list:
class reader
def __init__(self, name, booksread)
self.name = name
self.booksread = booksread
list = []
while True:
option = input("Choose an option: ")
if option == 1:
list.append(reader(name,booksread))
Note: I don't know how you are obtaining the values for 'name' or 'booksread', so their values in the list.append() line are just placeholders
To access the instances in that list, you can then iterate over it, or access elements by their indexes, e.g.
# access each element of the list and print the name
for reader in list:
print(reader.name)
#print the name of the first element of the list
print(list[0].name)
How can i duplicate a list of lists (or any other types) in a way that the resulting lists are new objects and not references to the old ones? As an example i have the following list of lists:
l=[[1,2],[3,4]]
what i want as result is:
l=[[1,2],[3,4],[1,2],[3,4]]
If i do l*=2 the new sub-lists are references to the old sub-lists.
Doing l[0].append("python") will result in
l=[[1,2,'python'],[3,4],[1,2,'python'],[3,4]]
Also creating a new list like:
l2=list(l)
or
l2=l[:]
doesn't solve the problem. I want to have new sub-lists which are independent of their origin and which upon changing have no impact on their old fellows. How can i do this i python?
In general, the best way to copy a nested data structure so that copies get made of all the references (not just the ones at the top level) is to use copy.deepcopy. In your nested list example, you can do:
l.extend(copy.deepcopy(l))
deepcopy will still work even if the data structure contains references to itself, or multiple references to the same object. It usually works for objects stored as attributes on an instances of custom classes too. You can define a __deepcopy__ method if you want to give a class special copying behavior (e.g. if some of its attributes are bookkeeping data that shouldn't be copied).
Here's a version of your nested list example code using instances of a linked list class rather than Python lists. copy.deepcopy does the right thing!
class linked_list(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def __repr__(self):
if self.next is not None:
return "({!r})->{!r}".format(self.value, self.next)
else:
return "({!r})".format self.value
lst = linked_list(linked_list(1, linked_list(2)),
linked_list(linked_list(3, linked_list(4))))
print(lst) # prints ((1)->(2))->((3)->(4))
lst.next.next = copy.deepcopy(lst)
print(lst) # prints ((1)->(2))->((3)->(4))->((1)->(2))->((3)->(4))
lst.value.value = 5
print(lst) # prints ((5)->(2))->((3)->(4))->((1)->(2))->((3)->(4))
This is the code I have written so far:
I am very new to python so am trying to use the most basic ways of accomplishing goals as possible as I currently don't know how to make it more efficient etc.
def simulateBeamRun(personlist, beam, times):
times = np.linspace(0,35,500)
templist = []
maxdeflectionlist = []
for t in times:
for i in personlist: #for each person instance
Tuple = personModel.person.loadDisplacement(t)
if 0 < Tuple(1) < beamModel.beam.L:
templist.append(Tuple)
else:
pass
return templist
File "beamSimulation.py", line 40, in simulateBeamRun
Tuple = personModel.person.loadDisplacement(t)
The error I am getting is:
TypeError: unbound method loadDisplacement() must be called with person instance as first argument (got float64 instance instead)
personlist is a list of lists each containing arrivalTime, weight, gait, speed for a given "person". This is so that it gives values to the constructor. Load displacement is the only other function in the person class:
class person(object):
"""This class models the displacement of a person's load as they run at
'speed' in one dimension. It assumes that the load is always concentrated
in a single point and that the displacement of that point is less than or
equal to the displacement of the person's centre of mass. Also the
displacement of the load will always be a multiple of 'gait'.
"""
def __init__(self, arrivalTime, weight, gait, speed):
"""This constructor function defines the person's weight, gait and
running speed as well as the time that they arrive at the position of
zero displacement.
"""
how do I fix this?
Given the limited code presented, some of this is just guessing, but it might point you in the right direction, at least:
There's no need to pass in the times argument if you're just going to immediately overwrite it with times = ....
You're not using maxdeflectionlist for anything, so it's not really needed (although maybe you're planning to later...).
Inside your for i in ... loop, i is your iteration variable, and should take each value successively from personlist. Guessing from variable names, these might be the person instances that you need to get displacements from, so the line that you're getting the error on should maybe be Tuple = i.loadDisplacement(t). If that's not the case, given your later comments, perhaps you need to instantiate a person object from the data in i - something like p = personModel.person(some, arguments, extracted, from, i), and then follow that with Tuple = p.loadDisplacement(t). Calling loadDisplacement() as you have is more appropriate for a class method or static method, not for an instance method, which is the essential meaning behind the error message you get. It's telling you that personModel.person is not a person instance - it's probably a class object.
The else: pass bit is sort of pointless.
I want to implement the built in data type set in python using a class and dictionary in python. I have included certain basic functions, but i could not perform the union and intersection operations defined on it. I wish to just write c=a+b where a and b are two dictionaries c is yet another dictionary whose keys give the union of 'a' and 'b'. I tried with try and except as given in my code below, but i want a better solution. can anyone help me with this?
class My_Set:
def __init__(self,listt):
if listt:
self.dictionary={}
i=0
for x in listt:
self.dictionary[x]=len(x)
i=i+1
else:
self.dictionary={}
def is_element(self,element):
if element in self.dictionary:
return True
else:
return False
def remove(self,element):
if element in self.dictionary:
self.dictionary.pop(element)
else:
print 'element missing'
def add_element(self,element):
self.dictionary.update({element:len(element)})
#return self.dictionary
def union(self,other):
self.dictionary.update(other.dictionary)
return self.dictionary.keys()
I'm building a python class to encapsulate a drop-down list and its buttons in one convenient widget and I ran across a problem.
class DropDownMenu(DropDown):
def __init__(self, **kwargs):
super(DropDownMenu, self).__init__(**kwargs)
self.The_Menu = DropDown()
self.The_Btns = []
self.Num_Btns = 0
def Set_Num_Btns(self):
self.Num_Btns = len(self.The_Btns)
def Create_Menu(self, Btn_Names):
# Populate List Size Property
if (self.Num_Btns == 0):
self.Set_Num_Btns()
# Add Buttons to the Drop-Down
for i in range(0, self.Num_Btns):
self.The_Btns.append(Button(text = Btn_Names[i], size_hint_y = None, height = 20))
self.The_Menu.add_widget(self.The_Btns[i])
It compiles fine and when I try to create a drop-down menu, I get what I want:
self.File_Menu = DropDownMenu()
self.File_Menu.Create_Menu(self.File_Menu_Names)
self.add_widget(self.File_Menu)
But, if I try to bind any of the buttons to anything, like so:
self.File_Menu.The_Btns[0].bind(on_release = self.Insert_File_Menu.open)
The compiler throws an exception saying the list was out-of-bounds. On further inspection, I realized that even though I'm calling the Create_Menu function, the value of The_Btns is not being changed from an empty list. So, my question is: how do I fix this problem?
Any help would be appreciated. Thanks!
First of all, python doesn't "compile" in the sense that you refer to, and doesn't have a compiler. Also, have a look at PEP8.
To answer your question, You are iterating over a range, 0 to Num_Btns. However, in Set_Num_Btns, you set the variable to len(self.The_Btns), which is an empty list, i.e. you are iterating over range(0, 0). I suspect you mean to do soemthing like this:
for name in Btn_Names:
self.The_Btns.append(Button(text=name, ...))
....