Can I give both an if and else statement another if and else statement? - python-3.8

enter image description here
So I am making a adventure game where you can choose your own path, but I don't know how I can assign the next row of options to one of the first two options and another row of options to the other option in the first option (look at picture for clearer understanding). So if you first choose plane, you get the two options for plane, but if you choose car, you get the options for car. But I don't know how to do that.
Does anyone know how I can do this?

Hi and welcome to programing #Valentinj.
You should use additional variables.
engine = input('plane/car')
if engine == 'plane':
direction = input('fly/go_back')
if direction == 'fly':
...
if direction == 'go_back':
...
if engine == 'car':
place = input('city/treasure')
if place == 'city':
...
if place == 'treasure':
...

Related

How to implement Linked List Recursion in KOtlin

I am learning linked list and came across a problem where you are required to reverse a linked list using recursion. Here is the code I wrote:
fun reverseRecurseTraverse1(firstNode: Node<Int>?): Node<Int>? {
if (firstNode?.next == null) {
return firstNode
} else {
val finalNode = reverseRecurseTraverse1(firstNode.next)
finalNode?.next = firstNode
firstNode.next = null
return finalNode
}
}
Input:
01234
Output:
40
I get the desired output If I change the line from
finalNode?.next = firstNode
to
firstNode.next!!.next = firstNode
What am I doing wrong here?
When I try to whiteboard finalNode?.next = firstNode makes perfect sense to me and based on my understanding those two lines are essentially doing the same thing.
Kindly help me understand this.
It would be useful if you share your "whiteboard logic" and why do you assume finalNode?.next = firstNode is correct and functionally the same as firstNode.next!!.next = firstNode.
Let's get your example: 01234. In the first step firstNode is 0 and after reversing of the remaining sublist, we get 4321. finalNode points at the first element of this reversed sublist, so at 4. Then you add 0 after 4 which is wrong. You should add 0 after 1.
On the other hand, firstNode.next is still pointing at the item that was next to 0 in the original list. It points at 1. By assigning to its next we add 0 where it should be - after 1.
You are almost there, but one line is wrong.
What you are doing is:
If your item is null, return it. That seems okay.
If your item is already the last item, return it as first item. Also looks okay.
If your item is not the last item, reverse the rest of the list. Okay.
Take the old last and now first item, and append your old first now last item to it? That doesn't seem right. Don't you want to append your old first and now last item to the last item of the reversed rest?
It would probably help to write a function
fun Node.last(): Node? = if(next == null) this else next!!.last()
that provides the last item of a linked list.
You could use that to append your previously first item to the last item of the reversed rest.
Considering a call reverseRecurseTraverse1(x), can we maybe always tell what reverseRecurseTraverse1(x).last() is without calculating it?

Streamsets Jython evaluator

I need a code on how to check all field of a record if it contains a certain string and write a header attribute if it has that character. Please see code below:
for record in records:
if record.value == "":
record.attributes["DATA"] = "BAD"
sdc.output.write(record)
else:
record.attributes["DATA"] = "GOOD"
sdc.output.write(record)
If anyone know another way to do this that would be great!!! record.values['/*'] doesnt work for me to get all the column.
Here's another rather compact way of writing it.
for (key,val) in record.value.iteritems():
if val == "some_string_value":
record.attributes["DATA"] = "some_header_value"
sdc.output.write(record)
Cheers,
Dash
For anyone facing the same problem, this might help!
for record in records:
for key in record.value:
if record.value[key] == "":
record.attributes["DATA"] = key
sdc.output.write(record)

Sentence segmentation and dependency parser

I’m pretty new to python (using python 3) and spacy (and programming too). Please bear with me.
I have three questions where two are more or less the same I just can’t get it to work.
I took the “syntax specific search with spacy” (example) and tried to make different things work.
My program currently reads txt and the normal extraction
if w.lower_ != 'music':
return False
works.
My first question is: How can I get spacy to extract two words?
For example: “classical music”
With the previous mentioned snippet I can make it extract either classical or music. But if I only search for one of the words I also get results I don’t want like.
Classical – period / era
Or when I look for only music
Music – baroque, modern
The second question is: How can I get the dependencies to work?
The example dependency with:
elif w.dep_ != 'nsubj': # Is it the subject of a verb?
return False
works fine. But everything else I tried does not really work.
For example, I want to extract sentences with the word “birthday” and the dependency ‘DATE’. (so the dependency is an entity)
I got
if d.ent_type_ != ‘DATE’:
return False
To work.
So now it would look like:
def extract_information(w,d):
if w.lower_ != ‘birthday’:
return False
elif d.ent_type_ != ‘DATE’:
return False
else:
return True
Does something like this even work?
If it works the third question would be how I can filter sentences for example with a DATE. So If the sentence contains a certain word and a DATE exclude it.
Last thing maybe, I read somewhere that the dependencies are based on the “Stanford typed dependencies manual”. Is there a list which of those dependencies work with spacy?
Thank you for your patience and help :)
Before I get into offering some simple suggestions to your questions, have you tried using displaCy's visualiser on some of your sentences?
Using an example sentence 'John's birthday was yesterday', you'll find that within the parsed sentence, birthday and yesterday are not necessarily direct dependencies of one another. So searching based on the birthday word having a dependency of a DATE type entity, might not be yield the best of results.
Onto the first question:
A brute force method would be to look for matching subsequent words after you have parsed the sentence.
doc = nlp(u'Mary enjoys classical music.')
for (i,token) in enumerate(doc):
if (token.lower_ == 'classical') and (i != len(doc)-1):
if doc[i+1].lower_ == 'music':
print 'Target Acquired!'
If you're unsure of what enumerate does, look it up. It's the pythonic way of using python.
To questions 2 and 3, one simple (but not elegant) way of solving this is to just identify in a parsed sentence if the word 'birthday' exists and if it contains an entity of type 'DATE'.
doc = nlp(u'John\'s birthday was yesterday.')
for token in doc:
if token.lower_ == 'birthday':
for entities in doc.ents:
if entities.label_ == 'DATE':
print 'Found ya!'
As for the list of dependencies, I presume you're referring to the Part-Of-Speech tags. Check out the documentation on this page.
Good luck! Hope that helped.

ruby on rails store sql result on a variable

Newbie here. I am trying to store the result of my search onto a variable.
#answer = q.answers.select(:name) which runs
"SELECT name FROM "answers" WHERE "answers"."question_id" = 1;" and returns
"t" for true.
It runs fine on the command line and shows the right result. But I want to compare that result to another variable.
How do i extract that result? #answer[0], or #answer, or answer_var = #answer[0]
i.e.
if #answer == some_other_variable OR
if #answer[0] == some_other_variable OR
if answer_var == some_other_variable
what value do #answer[0] and #answer[0] hold and how can I print the value to the log file? not the web page. I know it must be simple, but I can't get my head around it.
Thanks.
It's not really an answer to your question but...
If you want to follow "the rails way", you should better use Models and not deal with SQL at all.
E.g. :
#answer = q.answers.first # answers is an array, take the first
if #answer.name == ...
For the logging, I suggest you that : http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger

Need to extract information from free text, information like location, course etc

I need to write a text parser for the education domain which can extract out the information like institute, location, course etc from the free text.
Currently i am doing it through lucene, steps are as follows:
Index all the data related to institute, courses and location.
Making shingles of the free text and searching each shingle in location, course and institute index dir and then trying to find out which part of text represents location, course etc.
In this approach I am missing lot of cases like B.tech can be written as btech, b-tech or b.tech.
I want to know is there any thing available which can do all these kind of things, I have heard about Ling-pipe and Gate but don't know how efficient they are.
You definitely need GATE. GATE has 2 main most frequently used features (among thousands others): rules and dictionaries. Dictionaries (gazetteers in GATE's terms) allow you to put all possible cases like "B.tech", "btech" and so on in a single text file and let GATE find and mark them all. Rules (more precisely, JAPE-rules) allow you to define patterns in text. For example, here's pattern to catch MIT's postal address ("77 Massachusetts Ave., Building XX, Cambridge MA 02139"):
{Token.kind == number}(SP){Token.orth == uppercase}(SP){Lookup.majorType == avenue}(COMMA)(SP)
{Token.string == "Building"}(SP){Token.kind == number}(COMMA)(SP)
{Lookup.majorType == city}(SP){Lookup.majorType == USState}(SP){Token.kind == number}
where (SP) and (COMMA) - macros (just to make text shorter), {Somthing} - is annotation, , {Token.kind == number} - annotation "Token" with feature "kind" equal to "number" (i.e. just number in the text), {Lookup} - annotation that captures values from dictionary (BTW, GATE already has dictionaries for such things as US cities). This is quite simple example, but you should see how easily you can cover even very complicated cases.
I didn't use Lucene but in your case I would leave different forms of the same keyword as they are and just hold a link table or such. In this table I'd keep the relation of these different forms.
You may need to write a regular expression to cover each possible form of your vocabulary.
Be careful about your choice of analyzer / tokenizer, because words like B.tech can be easily split into 2 different words (i.e. B and tech).
You may want to check UIMA. As Lingpipe and Gate, this framework features text annotation, which is what you are trying to do. Here is a tutorial which will help you write an annotator for UIMA:
http://uima.apache.org/d/uimaj-2.3.1/tutorials_and_users_guides.html#ugr.tug.aae.developing_annotator_code
UIMA has addons, in particular one for Lucene integration.
You can try http://code.google.com/p/graph-expression/
example of Adress parsing rules
GraphRegExp.Matcher Token = match("Token");
GraphRegExp.Matcher Country = GraphUtils.regexp("^USA$", Token);
GraphRegExp.Matcher Number = GraphUtils.regexp("^\\d+$", Token);
GraphRegExp.Matcher StateLike = GraphUtils.regexp("^([A-Z]{2})$", Token);
GraphRegExp.Matcher Postoffice = seq(match("BoxPrefix"), Number);
GraphRegExp.Matcher Postcode =
mark("Postcode", seq(GraphUtils.regexp("^\\d{5}$", Token), opt(GraphUtils.regexp("^\\d{4}$", Token))))
;
//mark(String, Matcher) -- means creating chunk over sub matcher
GraphRegExp.Matcher streetAddress = mark("StreetAddress", seq(Number, times(Token, 2, 5).reluctant()));
//without new lines
streetAddress = regexpNot("\n", streetAddress);
GraphRegExp.Matcher City = mark("City", GraphUtils.regexp("^[A-Z]\\w+$", Token));
Chunker chunker = Chunkers.pipeline(
Chunkers.regexp("Token", "\\w+"),
Chunkers.regexp("BoxPrefix", "\\b(POB|PO BOX)\\b"),
new GraphExpChunker("Address",
seq(
opt(streetAddress),
opt(Postoffice),
City,
StateLike,
Postcode,
Country
)
).setDebugString(true)
);
B.tech can be written as btech, b-tech or b.tech
Lucene will let you do fuzzy searches based on the Levenshtein Distance. A query for roam~ (note the ~) will find terms like foam and roams.
That might allow you to match the different cases.