Calling a method in a class, in an if/elif statement - class

i'm creating trying to create a project, but i'm running into an error.
This is my code (not all of it, it's pretty lengthy, but the problem i'm running into):
class Rest(object):
def __init__(self, name, order=[], total=0):
self.name = name
self.order = []
self.total = 0
def end_order(self):
print("Here is your complete order: {0}".format(self.order))
print("Here is your total: {0}".format(self.total))
def order_menu(self):
loop = 1
while (loop == 1):
question_1 = raw_input("What would you like? Push S to Submit, Push C to Cancel")
if (question_1 == "1"):
self.total += 4.99
print("You added a cheeseburger, $4.99)
elif (question_1 == "S"):
end_order()
Okay, so under order_menu(self), under the elif statement, it gives me an error:
"Global name 'end_order()' is not defined".
There's a probably something silly i'm not doing, but I can't figure out what..

I believe the self keyword is required in Python when calling a class method. Try:
self.end_order()

Related

What's the correct way to delegate failable initializers in Swift?

Say I have this class:
class EvenNumber {
var num: Int
var stringValue: String
init?(n: Int) {
guard n % 2 == 0 else { return nil }
self.num = n
}
init?(str: String) {
guard let n = Int(str) else { return nil }
self.init(n: n)
//set stringValue?
}
}
In the init that takes a string, I delegate back to the one that takes an Int. How do I know whether it succeeded so I can continue initialization? What's the proper syntax / common pattern here?
You don't need to check that the delegated initialiser has succeeded. If the delegated initialiser has failed, the whole initialisation process fails.
This is evident in this code:
class EvenNumber {
var num: Int
var stringValue: String
init?(n: Int) {
guard n % 2 == 0 else { return nil }
self.num = n
stringValue = "" // you forgot to initialise stringValue in both of your initialisers
}
// you forgot "convenience"
convenience init?(str: String) {
guard let n = Int(str) else { return nil }
self.init(n: n)
print("hello")
stringValue = ""
}
}
EvenNumber(str: "5")
"hello" does not get printed, which means that the rest of the init(str:) does not get executed if init(n:) fails.
Here's some supporting documentation (you need to scroll down a bit, under "Propagation of Initialization Failure"):
In either case, if you delegate to another initializer that causes initialization to fail, the entire initialization process fails immediately, and no further initialization code is executed.
(This section is included for completeness' sake.)
Now you (or whoever comes to this question in the future) might ask, "but what if I want to do something else if the delegated initialiser fails?" In that case, you must check for the condition that causes the initialiser to fail:
if n % 2 == 1 {
self.init(n: n)
} else {
// do something else
}
Why is this so "clumsy"? Well, let's say you could do this (warning: made-up syntax):
if self.init(n: n) {
// success!
} else {
// fail
}
To get to the "fail" branch, we must have already run self.init(n:). self.init(n:), before it failed, might have already initialised some let properties. Recall that let properties can only be initialised once. So now self.init(n: n) has been executed, but the compiler doesn't know which let properties have been initialised. See the problem? How is the compiler going to verify that you have initialised every property exactly once in the "fail" branch?

LinkedList in Scala

For exercise I'm trying to implement a LinkedList in Scala.
Main problem is about Null reference.
But first some code:
class Node(xkey: String, xnext: Option[Node], xinfo: Int) {
val key: String = xkey;
var next = xnext.getOrElse(None);
var info: Int = xinfo;
def this(xkey: String, xinfo: Int) {
this(xkey, None, xinfo);
}
def this(xkey: String) {
this(xkey, None, -1);
}
#Override
override def toString: String = key + ":" + info
}
At this point, I'm already concerned about things.
I declare xnext in construct as a Option[Node], because the tail in this linkedList does not have a next.
In my first try, it was just a Node, but had problem with null object because compilator just told me that "null can't cast to Node" (or something like that, I do not remember now) - And so I switch to this Option.
But, is it ok? Because, you know, for me next should be a Node, not a Option, otherwise, I don't know, in the linkedList how to reference to next Node.
Whatever, second class (i.e. my Linked List)
class LinkedNode {
private var first: Option[Node] = None;
private var last: Option[Node] = None;
def addNode(newNode: Node) = {
if (first == null) {
first = Some(newNode);
last = Some(newNode);
first.next = last;
}
else {
last.next = newNode;
newNode.next = null;
last = newNode
}
}
def size(): Long = {
var currentNode : = first;
var size = 0L;
while (currentNode != null) {
size+=1;
currentNode = currentNode.next;
}
size
}
def findNodeByKey(key: String) : Node = {
var currentNode = first;
while(currentNode != null) {
if (currentNode.key.equals(key))
currentNode
else {
currentNode = currentNode.next;
}
}
currentNode;
}
def delNodeByKey(key : String) : Boolean = {
var currentNode = first;
var previousNode = first;
while(currentNode != null) {
if (currentNode.key.equals(key)) {
previousNode = currentNode.next;
return true;
}
previousNode = currentNode;
currentNode = currentNode.next;
}
return false;
}
}
And nothing. I'm already block to my constructor because first and last.
How should I declare them? Node? Or Option[Node]?
Problems are also in Add method.
When I add a node, I want to add a Node object, not an Option[Node].
And I don't get how to achieve things I want with all Option, Some and None classes.
I know I should not be so vague with my request, but any help?
P.S. I've already read this Q/A and it didn't help me
At this point, I'm already concerned about things. I declare xnext in construct as a Option[Node], because the tail in this linkedList does not have a next.
[...]
But, is ok? because, you know, for me next should be a Node, not a Option, otherwise, I don't know, in the linkedList how to reference to next Node.
This is a good solution to replacing null, which you definitely want to do to prevent null-pointer exceptions and the like. An Option[Node] is simply a Node wrapped in a container (or None). You can check whether or not it has a value with isEmpty or get its value with get (which will throw an exception if the Option is empty).
The only difference to null, as you'd use it in Java, is that you need to check if it isEmpty instead of checking for null, and that you need to unwrap (option.get) it explicitly when you're sure that it is not None.
A more paradigmatic (scala-typical) way of retrieving the value from an option is pattern matching:
option match {
case Some(x) => println(x)
case None => println("Whoops, no value :(")
}
Regarding your other questions, they are indeed a little vague.
How should I declere them? Node? or Option[Node]?
Use Option[Node] if the possibility exists that there's no value for the variable (i.e., if you'd set it to null sometimes in Java).
When I add a node, I want to add a Node object, not a Option[Node].
No, you want to add an Option[Node] internally, because you will need to check later on if a node is set or not. In Scala it is preferrable to do this via Option[Node].isEmpty compared to setting things to null. You're already doing this in some parts of your code (e.g., addNode), where you do Some(newNode) (I'd call this "wrapping the node in an Option", but I'm not entirely sure if that's the correct terminology).
And I don't get how to achieve things I want with all Option, Some and None class.
What you're doing in your addNode does seem correct to a degree, but you somehow try to use null again in the else branch. What about:
// We don't need Option[Node] for the parameter, because there
// _must_ be a Node value to be added
def addNode(newNode: Node) = {
if (first.isEmpty) {
first = Some(newNode)
last = Some(newNode)
first.next = last
} else {
newNode.next = None
last.next = Some(newNode)
last = Some(newNode)
}
}
(I didn't run that code, nor did I do an thorough check of your logic)

expectationForPredicate Fails test case

Recently started working on XCode UI test with SWIFT.
My problem is I need to wait until a element appears on iPhone screen.
I found a solution with '''expectationForPredicate''' and '''waitForExpectationsWithTimeout''' but the problem this is this methods are designed to fail test case if expected predicate not matched within timeout.
I need a code which can wait for element to appear on screen if the element did not appear and timeout exceeded then I don't want test case to fail. rather I would like to return true (element exists) / false (not exists)
I found a solution by avoiding the above mentioned functions as those are failing my tests instead of returning true or false
Below is the method i created
func waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) -> Bool {
let TIMEOUT: Double = 120 ;
var isFound = false;
let start = NSDate();
var diff : Double = 0;
repeat{
print("Is element \(element) found : \(element.exists)")
print("Printing debugDescription -> ")
print(XCUIApplication().debugDescription)
if(element.exists){
isFound = true;
break;
}
print("Waiting for element to exists... Time counter :\(diff)")
sleep(1)
let end = NSDate();
diff = end.timeIntervalSinceDate(start);
}while(diff <= TIMEOUT);
return isFound;
}
I hope this will help others, But if you still have any other better solution please answer here.

How would I create a constant that could be one of several strings depending on conditions?

I want to have a constant using let that may be one of several values.
For instance:
if condition1 {
constant = "hi"
}
else if condition2 {
constant = "hello"
}
else if condition3 {
constant = "hey"
}
else if condition4 {
constant = "greetings"
}
I'm not sure how to do this with Swift and the let feature. But I'm inclined to believe it's possible, as this is in the Swift book:
Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.
How would I accomplish this?
As pointed out in the other answers you can't directly do this. But if you're looking to just variably set the initial value of a constant, then yes, that is possible. Here's an example with a computed property.
class MyClass {
let aConstant: String = {
if something == true {
return "something"
} else {
return "something else"
}
}()
}
I think you are looking for variable which will be assigned later inside switch-case:
let constant :String
switch conditions {
case condition1:
constant = "hi"
case condition2:
constant = "hello"
case condition3:
constant = "hey"
case condition4:
constant = "greetings"
default:
constant = "salute"
}
One option would be something like this, using a closure:
let constant: String = ({ value in
if conditionOne {
return "Hi"
} else if conditionTwo {
return "Bye"
}
return "Oops!"
})(myData /*needed for condition*/)
Or, for another twist, using generics:
func fancySwitch<S, T>(val: S, fn: S -> T) -> T {
return fn(val)
}
let x: String = fancySwitch(3) { val in
if val == 2 {
return "Hi"
} else if val < 5 {
return "Bye"
}
return "Oops"
}
let y: String = fancySwitch((3, 4)) { (a, b) in
if a == 2 {
return "Hi"
} else if b < 5 {
return "Bye"
}
return "Oops"
}
I understand what you're looking for. In Scala and some other functional languages this can be done using the match statement (kind of like switch) because the entire statement resolves to a value like this:
val b = true
val num = b match {
case true => 1
case false => 0
}
This is unfortunately not directly possible in Swift because there is no way to get a value from a branch statement. As stated in the Swift book, "Swift has two branch statements: an if statement and a switch statement." Neither of these statements resolve to a value.
The closest code structure I can think of is to first use a variable to retrieve the correct value and then assign it to a constant to be used in any later code:
let b = true
var num_mutable: Int
switch b {
case true:
num_mutable = 1
default:
num_mutable = 0
}
let num = num_mutable
Just add the line let constant: String before your if/else statement.
Below, an excerpt from Swift 1.2 and Xcode 6.3 beta - Swift Blog - Apple Developer elaborates.
let constants are now more powerful and consistent — The new rule is
that a let constant must be initialized before use (like a var), and
that it may only be initialized, not reassigned or mutated after
initialization. This enables patterns like:
let x : SomeThing
if condition {
x = foo()
} else {
x = bar()
}
use(x)
This formerly required the use of a var even though there is no
mutation taking place. Properties have been folded into this model to
simplify their semantics in initializers as well.
I found the Swift blog post above from the article "Let It Go: Late Initialization of Let in Swift", which I found by googling: swift let constant conditional initialize.

Python3 objects passing from functions

The below code snippet is for deleting a node in linked list. My class contains two members namely data and next a pointer to hold other objects of that class type. When, I run my program, I don't get any error. If I try to delete the first item in the linked list, it enters the First for loop and displays the message "The data is found". But if I print my list, I am seeing the element in the list. I think this is because of assigning objects back, but I am not able to find where I have done that mistake. Any help is greatly appreciated.
def deleteNode(self, a_data):
flag = 0
if (self.data == a_data):
print("The data is found")
self = self.next
flag = 1
else:
while(self.next != None):
if (self.next.data == a_data):
self.next = self.next.next
flag = 1
break
else:
self = self.next
if(flag):
print("Data Deleted")
else:
print("Data not available")
Thanks
self = self.next in your code has no effect on the outside world: it just assigns to a local variable.
It looks like you are trying to delete a node from within Node class itself. You could use a function instead that accepts a list head and returns a (possibly new) list head with the corresponding item deleted:
def delete_node(head, data):
"""Delete the first node in the `head` list that has `data`."""
prev, node = None, head
while node is not None: # until the last node (`None` means empty list)
if node.data == data: # found node that has data
if prev is None: # we are at the very beginning of the list
assert head is node
head = node.next # remove the first node
else:
assert prev.next is node
prev.next = node.next # remove internal node
break
prev, node = node, node.next
return head
Friends,
I modified my function. I think the error may be because not assigning back the value to the original one, so I made my function to return value. Comments and other methods and any other reason for above than mine are cordially welcome.
def deleteNode(self, a_data):
flag = 0
if (self.data == a_data):
print("The data is found")
self = self.next
flag = 1
else:
while(self.next != None):
if (self.next.data == a_data):
self.next = self.next.next
flag = 1
break
else:
self = self.next
if(flag):
print("Data Deleted")
else:
print("Data not available")
return self
Thanks
S