Learning python from Udacity. Exercise is mentioned below. I cannot see where output 'None' is coming from. Is there something about classes that I am missing ? Thx in advance
Output is always
0
None
======= CODE BEGIN ==============
"""You can use this class to represent how classy someone
or something is.
"Classy" is interchangable with "fancy".
If you add fancy-looking items, you will increase
your "classiness".
Create a function in "Classy" that takes a string as
input and adds it to the "items" list.
Another method should calculate the "classiness"
value based on the items.
The following items have classiness points associated
with them:
"tophat" = 2
"bowtie" = 4
"monocle" = 5
Everything else has 0 points.
Use the test cases below to guide you!"""
class Classy(object):
def __init__(self):
self.items = []
self.classiness = 0
def getClassiness(self):
print(self.classiness)
def createList(self):
self.items.append(item)
def addItem(self, item):
if item=="tophat":
self.classiness+=2
elif item=="bowtie":
self.classiness+=4
elif item=="monocle":
self.classiness+=5
else:
self.classiness+=0
return self.classiness
# Test cases
me = Classy()
# Should be 0
print(me.getClassiness())
Your method getClassiness() is printing and the caller is also printing.
Maybe you meant to return a value rather than printing?
def getClassiness(self):
return self.classiness
class Classy(object):
def __init__(self):
self.items = []
self.classiness = 0
def getClassiness(self):
return self.classiness
def createList(self):
self.items.append(item)
def addItem(self, item):
if item=="tophat":
self.classiness+=2
elif item=="bowtie":
self.classiness+=4
elif item=="monocle":
self.classiness+=5
else:
self.classiness=0
Test cases
me = Classy()
Should be 0
print(me.getClassiness())
Related
For some reason the getClassiness Function does not work as it is not able to call the helper function getItemClassiness. Is there any reason this might be? Thanks!
class Classy(object):
def __init__(self):
self.items = []
def addItem(self, item):
self.items.append(item)
def getItemClassiness(item):
if item == "tophat":
return 2
if item == "bowtie":
return 4
if item == "monocle":
return 5
return 0
def getClassiness(self):
total = 0
for item in self.items:
x = getItemClassiness(item)
total += x
return total
# Test cases
me = Classy()
# Should be 0
print(me.getClassiness())
# Should be 2
me.addItem("tophat")
print(me.getClassiness())
me.addItem("bowtie")
me.addItem("jacket")
me.addItem("monocle")
print(me.getClassiness())
# Should be 11
me.addItem("bowtie\n")
print(me.getClassiness())
# Should be 15
You can use this class to represent how classy someone or something is. "Classy" is interchangable with "fancy". If you add fancy-looking items, you will increase your "classiness". Create a function in "Classy" that takes a string as input and adds it to the "items" list. Another method should calculate the "classiness" value based on the items. The following items have classiness points associated with them: "tophat" = 2 "bowtie" = 4 "monocle" = 5 Everything else has 0 points. Use the test cases below to guide you!
class Classy(object):
def __init__(self):
self.items = []
def addItem(self, string):
self.items.append(string)
def getClassiness(self):
sum = 0
for item in self.items:
if (item == "tophat"):
sum += 2
elif (item == "bowtie"):
sum += 4
elif (item == "monocle"):
sum += 5
else:
sum += 0
return sum
You should declare getItemClassiness as a static method because it doesn't require a specific instance. Then you can call the function as you would an instance method.
#staticmethod
def getItemClassiness(item):
...
def getClassiness(self):
...
for item in self.items:
x = self.getItemClassiness(item)
But still it won't give you 15 for the last test case, because "bowtie" != "bowtie\n". If you intend to ignore white space at the start or the end of the string, use str.strip().
In line 21 call for a class method is made without using the self keyword.
x = self.getItemClassiness(item)
Similarly on line 8 in self keyword is required with as parameter for function definition of getItemClassiness
def getItemClassiness(self, item):
Here is what I did using Static Method. Got the right output in Test Cases.
class Classy(object):
def __init__(self):
self.items = []
def addItem(self, item):
self.items.append(item)
#staticmethod
def getItemClassiness(item):
if item == "tophat":
return 2
if item == "bowtie":
return 4
if item == "monocle":
return 5
return 0
def getClassiness(self):
total = 0
for item in self.items:
x = self.getItemClassiness(item)
total += x
return total
This question already has answers here:
Function changes list values and not variable values in Python [duplicate]
(7 answers)
Closed 7 years ago.
The code below imports a linked list from LinkedQfile and creates a list object with some node objects.
If I run this code the output from check_something() becomes CD .
I thought linked_list in check_something() would become a local object inside the function and since I'm not assigning whatever I'm returning to anything it wouldn't change, that is I would expect the output ABCD. This is obviously not the case so I'm wondering if someone could explain to me what is going on here?
If linked_list was a global variable I would expect this outcome, my guess is that the return statements in each function returns some information to the object but I have no idea how and why! (I got the code from a lecture note and it works just like I want it to, I just want to know why!)
from LinkedQFile import LinkedQ
def check_something(linked_list):
check_first_element(linked_list)
check_second_element(linked_list)
print(linked_list)
def check_first_element(linked_list):
word = linked_list.dequeue()
if word == "A":
return
def check_second_element(linked_list):
word = linked_list.dequeue()
if word == "B":
return
def main():
list = LinkedQ()
list.enqueue("A")
list.enqueue("B")
list.enqueue("C")
list.enqueue("D")
check_something(list)
main()
And if needed, the LinkedQFile:
class Node:
def __init__(self, x, next= None):
self._data = x
self._next = next
def getNext(self):
return self._next
def setNext(self, next):
self._next = next
def getValue(self):
return self._data
def setValue(self, data):
self._data = data
class LinkedQ:
def __init__(self):
self._first = None
self._last = None
self._length = 0
def __str__(self):
s = ""
p = self._first
while p != None:
s = s + str(p.getValue())
p = p.getNext()
return s
def enqueue(self, kort):
ny = Node(kort)
if self._first == None:
self._first = ny
else:
self._last = self._first
while self._last.getNext():
self._last = self._last.getNext()
self._last.setNext(ny)
self._length += 1
def dequeue(self):
data = self._first.getValue()
self._first = self._first.getNext()
self._length = self._length - 1
return data
You're right about linked_list being a local variable, but just because a variable is local doesn't mean it can't reference something that isn't. In order for it to do what you expected, it would need to copy your entire linked list every time you pass it to a function, which wouldn't make sense.
Here's a simple example that illustrates the idea of a shared object. In this example, an empty list is created and assigned to a. Then a is assigned to b. This does not copy the list. Instead, there is a single list, referenced by both a and b. When it is modified, through either a or b, both a and b reflect the change:
>>> a = []
>>> b = a
>>> a.append("x")
>>> a
['x']
>>> b
['x']
>>>
The same thing is happening with your class objects. In fact, your linked lists wouldn't work at all if it didn't.
I must use a class to pass this list and implement LIFO.
class Sclass:
def __init__(self):
self.lst = []
def sadd(self,lst,a):
print "before append" self.lst
self.lst.append(a)
print "post append" self.lst
return lst
def sretrieve(self,lst):
self.lst.pop(-1)
my_list=Sclass()
lt=my_list.sadd(12)
print lt
How do I add multiple values into the list and then retrieve them until the whole list is empty
Here's a very simple example.
class LifoContainer(object):
def __init__(self):
self.lst = []
def push(self, item):
self.lst.append(item)
def pop(self):
return self.lst.pop()
container = LifoContainer()
container.push(3)
container.push(4)
container.push(5)
assert container.pop() == 5
assert container.pop() == 4
assert container.pop() == 3
I'm trying to go over some previous homework problems in my computer science class with regards to Linked List. This question is really bothering me on how I should go about this, where it wants me to implement a "Stack" and a "Queue" class to go along using my Linked List class I made a while back. That is all the question states, so would I have to use my ListNode class which is this.
class ListNode(object):
def __init__(self, item = None, link = None):
'''creates a ListNode with the specified data value and link
post: creates a ListNode with the specified data value and link'''
self.item = item
self.link = link
How would I go about making a stack class that can push and pop? Would my code look like this or will I be way off?
from ListNode import ListNode
class LinkedStack(object):
def __init__(self, ListNode.item):
stack = []
def push(self,item):
self.append(ListNode.item)
self.size += 1
def isEmpty(self):
return not self
I just based that code off examples I have seen on this web page. Any help to make a simple stack class based off a linked list? For some reason it wants me to test my code using this class that was given to me which was this.
def isPalindrome(phrase):
forward = Queue()
reverse = Stack()
extractLetters(phrase, forward, reverse)
return sameSequence(forward, reverse)
#------------------------------------------------------------
def extractLetters(phrase, q, s):
for ch in phrase:
if ch.isalpha():
ch = ch.lower()
q.enqueue(ch)
s.push(ch)
#------------------------------------------------------------
def sameSequence(q, s):
while q.size() > 0:
ch1 = q.dequeue()
ch2 = s.pop()
if ch1 != ch2:
return False
return True
Thanks to whoever helps me in advance!
one way to create stack using python list is using list's append & pop functions.
Example stack class:
class stack(object):
def __init__(self):
self.data = []
def pop(self):
if self.isEmpty():
print "Nothing to remove from stack"
return None
return self.data.pop()
def push(self, item):
self.data.append(item)
def isEmpty(self):
if len(self.data) == 0:
return True
return False
s = stack()
s.push(1)
s.push(2)
s.push(3)
print s.pop()
print s.pop()
print s.pop()
print s.pop()
Output:
3
2
1
Nothing to remove from stack
None
I am trying to solve this problem:
Imagine a (literal) stack of plates. If the stack gets too high, it
might topple. There- fore, in real life, we would likely start a new
stack when the previous stack exceeds some threshold. Implement a data
structure SetOfStacks that mimics this. SetOf- Stacks should be
composed of several stacks, and should create a new stack once the
previous one exceeds capacity. SetOfStacks.push() and
SetOfStacks.pop() should behave identically to a single stack (that
is, pop() should return the same values as it would if there were just
a single stack). Bonus: Implement a function popAt(int index) which
performs a pop operation on a specific sub-stack.
So I wrote the code:
#!/bin/env python
from types import *
class Stack:
def __init__(self):
self.items = []
self.capacity = 3
self.stackscount = 0
def create(self):
id = self.stackscount + 1
id = str(id) + "_stack"
# How to create a new instance of Stack class at runtime ?
# the __init__ must be run too.
def push(self, item):
if self.size() <= self.capacity:
self.items.append(item)
else:
self.create()
def pop(self):
return self.items.pop()
def popAt(self):
pass
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s = Stack()
s.push(10)
How do I create a new s type object dynamically at runtime? I searched on the internet and found that using new.instance or new.classobj is the solution but when I did so my new object did not seem to have items from __init__ function. In python3, type() seems to be the answer but the docs doesn't have any examples.
You've confused yourself by referring to a "type object". In Python that means the class itself, not its instances.
To create new Stack objects, simply do what you're already doing: call the Stack class. You can append them to a list:
stacks = [Stack() for _ in range(5)]
However, as jon points out, that won't solve your problem since you haven't defined the SetOfStacks class.
You could simply use a parent-child relation : when a Stack is full, it creates a child and delegate next pushes to it. It could lead to :
class Stack:
def __init__(self, parent = None, id=None):
self.stackscount = 0
self.capacity = 3
self.items = []
self.parent = parent
self.id = id
self.child = None
def create(self):
id = self.stackscount + 1
id = str(id) + "_stack"
return Stack(self, id)
def push(self, item):
if self.size() <= self.capacity:
self.items.append(item)
else:
if self.child is None:
self.child = self.create()
self.child.push(item)
def pop(self):
if self.child is not None:
item = self.child.pop()
if len(self.child.items) == 0:
self.child = None
else:
item = self.items.pop()
return item
def popAt(self):
pass
def peek(self):
if self.child is not None:
item = self.child.peek()
else:
item = self.items[len(self.items)-1]
return item
def size(self):
l = len(self.items)
if self.child is not None:
l += self.child.size()
return l
s = Stack()
s.push(10)
popAt is still to be implemented, but I tested it and it correctly creates new stacks when pushing and empties and removes them when popping.
The implementation of popAt will require some evolutions to current pop implementation, to allow removing an intermediate stack :
def pop(self):
if self.child is not None:
item = self.child.pop()
if len(self.child.items) == 0:
self.child = self.child.child
if self.child is not None:
self.child.parent = self
else:
item = self.items.pop()
return item
def popAt(self, stacknumber):
s = self
for i in range(stacknumber):
s = s.child
if s is None:
return None
if len(s.items) == 0:
return None
item = s.items.pop()
if len(s.items) == 0 and s.parent is not None:
s.parent.child = s.child
if s.child is not None:
s.child.parent = s.parent
return item
The type() function is indeed what you are looking for. Documentation can be found here: https://docs.python.org/2/library/functions.html#type
You can call it like this:
# Bases is a tuple of parent classes to inherit
bases = Stack,
# Dict contains extra properties for the class, for example if you want to add a class variable or function
dict_ = {}
# Construct the class
YourClass = type('YourClass', bases, dict_)
# Create an instance of the class
your_instance = YourClass()
It looks like you are just looking at instance creation though:
class Stack(object):
def create(self):
id = self.stackscount + 1
id = str(id) + "_stack"
# How to create a new instance of Stack class at runtime ?
# the __init__ must be run too.
stack = Stack()