Using raw_input after print, not executing in the correct order - python-2.x

I'm writing a very simple prompt-input sequence:
print "question",
a = raw_input()
print "question",
b = raw_input()
print "question",
c = raw_input()
print "question",
d = raw_input()
print "Your answers were: %r, %r, %r and %r" % (a, b, c, d)
The problem is: when running the code in bash, it asks directly for all four inputs before printing the questions. Any idea why this could be happening?
Edit: the solution offered in the duplicate candidate "solves" the problem (although after the first input the questions are printed with one space indentation, for some reason I don't yet know). I'm working from an exercise book that insists the code should be transcribed exactly and makes no mention of flushing the buffer.

Related

Syntax error on else in my quiz

I'm new to a program called Pythonista. I'm doing a quiz and when I try to test it I get a syntax error.
Here is the error:
Your else indentation is not proper at line number 10
your code with proper indentation:
def quiz():
score = 0
begin = raw_input("do you want to start ?")
if begin == "yes":
print "A : 56"
print "B : 48"
print "C : 45"
q1 = raw_input("what is 12*4")
if q1 in ["b","B"]:
print "congrats !! well done!1"
score += 1
else:
print "sorry!! you are wrong try next one !! good luck"
print "A : Another ice age"
print "B : A meteor will hit the earth"
print "C : Aliens will invade earth"
q2 = raw_input("what will happen in 50 years?")
if q2 in ["a","A"]:
print "nice !! keep going!1"
score += 1
else:
print "sorry!! you are wrong try next one !! good luck"
return score
else:
print "ok bye"
return 0
This is just an edit on top of your code. But I won't suggest this approach as you are writing same code for both question again and again.Instead of that I will suggest to use one proper data structure and loop through that then it will be dynamic enough to do more quiz.You can use one array of dictionary like this-
[{"question":"what is 5*4 ?","options":[10,20,30],"answer_index":1},{"question":"what is 10*4 ?","options":[40,50,60,30],"answer_index":0}]
I'm not familiar with Pythonista, but, from a quick search, it uses significant white-space. In which case, your else is indented when it should be at the same level as its corresponding if. There are further errors like this later on.
See here for more details: http://omz-software.com/pythonista/docs/tutorial/controlflow.html

Haskell breaks my type when I call show/read

I have defined a new type in my haskell code, which takes a list of lists of strings as a record. An example might be
Board{size=(4,7),pieces=[["OA","AA","AA"],["BBB","BOO"],["OCCC","CCCO","OOCO"]]}
I've set it up as a derived instance of Show and Read. If I just input the code above into ghci, then I get out exactly what I put in, which is fine. However, if I call it with show, I get
"Board {size = (4,7), pieces = [[\"OA\",\"AA\",\"AA\"],[\"BBB\",\"BOO\"],[\"OCCC\",\"CCCO\",\"OOCO\"]]}"
The speech marks are fine, but I've no idea why the backslashes are there. Are you not allowed to next speech marks or something? In any case, this now totally breaks if I try to call read to get it back. I get a long error trying to tell me that none of the strings are data constructors - I don't know why it thinks they are.
Is there any way round this?
Given
> data Board = Board { size :: (Int, Int), pieces :: [[String]] } deriving (Show, Read)
> let b = Board{size=(4,7),pieces=[["OA","AA","AA"],["BBB","BOO"],["OCCC","CCCO","OOCO"]]}
The result of show b is a String
> show b
"Board {size = (4,7), pieces = [[\"OA\",\"AA\",\"AA\"],[\"BBB\",\"BOO\"],[\"OCCC\",\"CCCO\",\"OOCO\"]]}"
The quotes in any String are escaped when show-ing a string. If you output the string instead you'll see that it doesn't contain the \ characters.
> putStrLn $ show b
Board {size = (4,7), pieces = [["OA","AA","AA"],["BBB","BOO"],["OCCC","CCCO","OOCO"]]}
The string produced by show can be read back in again as a board by read
> (read . show $ b) :: Board
Board {size = (4,7), pieces = [["OA","AA","AA"],["BBB","BOO"],["OCCC","CCCO","OOCO"]]}
GHCI already calls show. When you type show something under GHCI, it’s as if you called show $ show something.

Ruby String/Array Write program

For a project that I am working on for school, one of the parts of the project asks us to take a collection of all the Federalist papers and run it through a program that essentially splits up the text and writes new files (per different Federalist paper).
The logic I decided to go with is to run a search, and every time the search is positive for "Federalist No." it would save into a new file everything until the next "Federalist No".
This is the algorithm that I have so far:
file_name = "Federalist"
section_number = "1"
new_text = File.open(file_name + section_number, 'w')
i = 0
n= 1
while i < l.length
if (l[i]!= "federalist") and (l[i+1]!= "No")
new_text.puts l[i]
i = i + i
else
new_text.close
section_number = (section_number.to_i +1).to_s
new_text = File.open(file_name + section_number, "w")
new_text.puts(l[i])
new_text.puts(l[i+1])
i=i+2
end
end
After debugging the code as much as I could (I am a beginner at Ruby), the problem that I run into now is that because the while function always holds true, it never proceeds to the else command.
In terms of going about this in a different way, my TA suggested the following:
Put the entire text in one string by looping through the array(l) and adding each line to the one big string each time.
Split the string using the split method and the key word "FEDERALIST No." This will create an array with each element being one section of the text:
arrayName = bigString.split("FEDERALIST No.")
You can then loop through this new array to create files for each element using a similar method you use in your program.
But as simple as it may sound, I'm having an extremely difficult time putting even that code together.
i = i + i
i starts at 0, and 0 gets added to it, which gives 0, which will always be less than l, whatever that value is/means.
Since this is a school assignment, I hesitate to give you a straight-up answer. That's really not what SO is for, and I'm glad that you haven't solicited a full solution either.
So I'll direct you to some useful methods in Ruby instead that could help.
In Array: .join, .each or .map
In String: .split
Fyi, your TA's suggestion is far simpler than the algorithm you've decided to embark on... although technically, it is not wrong. Merely more complex.

array within an array ruby

Input: <ArrayOfSMSIncomingMessage xmlns=\"http://sms2.cdyne.com\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><SMSIncomingMessage><FromPhoneNumber>19176230250</FromPhoneNumber><IncomingMessageID>cf8ef62d-9169-4908-a527-891fca056475</IncomingMessageID><MatchedMessageID>6838594b-288f-4e9a-863c-3ad9f4d501ca</MatchedMessageID><Message>This is a test</Message><ResponseReceiveDate>2013-04-07T17:19:06.953</ResponseReceiveDate><ToPhoneNumber>13146667368</ToPhoneNumber></SMSIncomingMessage><SMSIncomingMessage><FromPhoneNumber>19176230250</FromPhoneNumber><IncomingMessageID>ebf11b38-c176-439a-a2d0-7a2bb35390df</IncomingMessageID><MatchedMessageID>6838594b-288f-4e9a-863c-3ad9f4d501ca</MatchedMessageID><Message>Does it wotk</Message><ResponseReceiveDate>2013-04-07T17:19:17.303</ResponseReceiveDate><ToPhoneNumber>13146667368</ToPhoneNumber></SMSIncomingMessage></ArrayOfSMSIncomingMessage>
Expected Output: [["191760250", "This is a test", "2013-04-07T17:19:06.953", "13146636 8"],["191760250", "Does it wotk", "2013-04-07T17:19:17.303", "131466368"]]
I am a newbie but i can't solve this problem or find an answer. The objective is to parse a text. The problem is that I put the information into an array b and then I put array b into array c. However, what happens is that c[0] becomes equal to c[1] even thought they should have different information. I don't know how to fix this.
data='"<ArrayOfSMSIncomingMessage xmlns=\"http://sms2.cdyne.com\" xmlns:i=\" <FromPhoneNumber>191760250</FromPhoneNumber>'
data=data+'<Message>This is a test</Message><ResponseReceiveDate>2013-04-07T17:19:06.953</ResponseReceiveDate>'
data=data+'<ToPhoneNumber>13146636 8</ToPhoneNumber></SMSIncomingMessage><SMSIncomingMessage><FromPhoneNumber>191760250'
data=data+'</FromPhoneNumber><Message>Does it wotk</Message><ResponseReceiveDate>2013-04-07T17:19:17.303</ResponseRecei'
data=data+'veDate><ToPhoneNumber>131466368</ToPhoneNumber></SMSIncomingMessage></ArrayOfSMSIncomingMessage>'
a=[['<FromPhoneNumber>','</FromPhoneNumber>'],['<Message>','</Message>'],
['<ResponseReceiveDate>','</ResponseReceiveDate>'],['<ToPhoneNumber>','</ToPhoneNumber>']]
b=[]
c=[]
d=true
ii=-1
while data.index(a[0][0])!=nil do
ii+=1
for i in 0..3
print "\ni is #{i} first term: #{a[i][0]} second term #{a[i][1]}\n"
b[i]= data[data.index(a[i][0])+a[i][0].length..data.index(a[i][1])-1]
print "b[i] is #{b[i]}\n"
end
print "b is #{b}\n"
print "c is #{c}\n"
c.push(b)
print "c is #{c}\n"
d=data.slice!(0,data.index('</SMSIncomingMessage>')+5)
print "d is #{d}\n"
print "data is #{data}\n"
end
I really don't understand what your code is trying to accomplish, but regarding what you say isn't working as you expect, (However, what happens is that c[0] becomes equal to c[1] even thought they should have different information.), the issue is that you are pushing b (which is a reference) onto c, so when you change b, you get the appearance of the contents of c changing.
Change
c.push(b)
to
c.push(b.dup)
if you want what you push onto c to stay the same even after you change b.
You are parsing XML. Don't waste time trying to manipulate strings, because all you'll do is generate fragile code.
Instead, use a real XML parser, which lets you navigate through the structure, and pick what you want.
First, your XML is malformed, but I worked around that by supplying a closing tag, turning it into damaged XML, but not fatally so.
require 'nokogiri'
xml = '<ArrayOfSMSIncomingMessage xmlns="http://sms2.cdyne.com" xmlns:i="">
<SMSIncomingMessage>
<FromPhoneNumber>191760250</FromPhoneNumber>
<Message>This is a test</Message>
<ResponseReceiveDate>2013-04-07T17:19:06.953</ResponseReceiveDate>
<ToPhoneNumber>131466368</ToPhoneNumber>
</SMSIncomingMessage>
<SMSIncomingMessage>
<FromPhoneNumber>191760250</FromPhoneNumber>
<Message>Does it wotk</Message>
<ResponseReceiveDate>2013-04-07T17:19:17.303</ResponseReceiveDate>
<ToPhoneNumber>131466368</ToPhoneNumber>
</SMSIncomingMessage>
</ArrayOfSMSIncomingMessage>'
doc = Nokogiri::XML(xml)
pp doc.search('SMSIncomingMessage').map{ |incoming_msg|
%w[FromPhoneNumber Message ResponseReceiveDate ToPhoneNumber].map{ |n| incoming_msg.at(n).text }
}
Which outputs:
[["191760250", "This is a test", "2013-04-07T17:19:06.953", "131466368"],
["191760250", "Does it wotk", "2013-04-07T17:19:17.303", "131466368"]]

ruby interview question

I got this question in a previous interview and couldnt do it , any idea?
What does this do:
`$=`;$_=\%!;($_)=/(.)/;$==++$|;($.,$/,$,,$\,$",$;,$^,$#,$~,$*,$:,#%)=(
$!=~/(.)(.).(.)(.)(.)(.)..(.)(.)(.)..(.)......(.)/,$"),$=++;$.++;$.++;
$_++;$_++;($_,$\,$,)=($~.$"."$;$/$%[$?]$_$\$,$:$%[$?]",$"&$~,$#,);$,++
;$,++;$^|=$";`$_$\$,$/$:$;$~$*$%[$?]$.$~$*${#}$%[$?]$;$\$"$^$~$*.>&$=`
This is Perl code that prints out "Just another Perl hacker."
While most of the $_, $=, etc. variables are available in Ruby as well, the presence of statements such as $,++ indicate Perl, which actually has pre- and post-increment operators, unlike Ruby.
I went in with Vim and replaced all the symbols with their English equivalent. I munged something up since the output is now "Just another Per hacker" (missing the L on Perl), but here's what I came up with:
use English;
`$FORMAT_LINES_PER_PAGE`;
$ARG=\%!;($ARG)=/(.)/;$FORMAT_LINES_PER_PAGE=++$OUTPUT_AUTOFLUSH;
($INPUT_LINE_NUMBER,$/,$OUTPUT_FIELD_SEPARATOR,$OUTPUT_RECORD_SEPARATOR,$LIST_SEPARATOR,$SUBSCRIPT_SEPARATOR,$FORMAT_TOP_NAME,$OFMT,$FORMAT_NAME,$MULTILINE_MATCHING,$FORMAT_LINE_BREAK_CHARACTERS,#%)=(
$!=~/(.)(.).(.)(.)(.)(.)..(.)(.)(.)..(.)......(.)/,$LIST_SEPARATOR),$FORMAT_LINES_PER_PAGE++;
$INPUT_LINE_NUMBER++;
$INPUT_LINE_NUMBER++; $ARG++;$ARG++;
($ARG,$OUTPUT_RECORD_SEPARATOR,$OUTPUT_FIELD_SEPARATOR)=($FORMAT_NAME.$LIST_SEPARATOR."$SUBSCRIPT_SEPARATOR$/$FORMAT_PAGE_NUMBER[$CHILD_ERROR]$ARG$OUTPUT_RECORD_SEPARATOR$OUTPUT_FIELD_SEPARATOR$FORMAT_LINE_BREAK_CHARACTERS$FORMAT_PAGE_NUMBER[$CHILD_ERROR]",$LIST_SEPARATOR&$FORMAT_NAME,$OFMT,);
$OUTPUT_FIELD_SEPARATOR++ ;
$OUTPUT_FIELD_SEPARATOR++;
$FORMAT_TOP_NAME|=$LIST_SEPARATOR;
`$ARG$OUTPUT_RECORD_SEPARATOR$OUTPUT_FIELD_SEPARATOR$/$FORMAT_LINE_BREAK_CHARACTERS$SUBSCRIPT_SEPARATOR$FORMAT_NAME$MULTILINE_MATCHING$FORMAT_PAGE_NUMBER[$CHILD_ERROR]$INPUT_LINE_NUMBER$FORMAT_NAME$MULTILINE_MATCHING${#}$FORMAT_PAGE_NUMBER[$CHILD_ERROR]$SUBSCRIPT_SEPARATOR$OUTPUT_RECORD_SEPARATOR$LIST_SEPARATOR$FORMAT_TOP_NAME$FORMAT_NAME$MULTILINE_MATCHING.>&$FORMAT_LINES_PER_PAGE`
Here, I changed all the special Ruby globals into single-letter variables and inserted some whitespace:
`a`
n = \%!
(n) = /(.)/
a = ++o
(b, c, d, f, e, g, h, i, j, k, l, #%) = (m =~ /(.)(.).(.)(.)(.)(.)..(.)(.)(.)..(.)......(.)/, e), a++
b++
b++
n++
n++
(n, f, d) = (j . e . "gcp[q]nfdlp[q]", e & j, i,)
d++
d++
h |= e
`nfdclgjkp[q]bjk${#}p[q]gfehjk.>&a`
Whoever wrote this doesn't understand Ruby. There's no increment operator in Ruby. Tokens like \%! and #% mean nothing in Ruby. You can't interpolate variables, even global variables, in strings or backquoted commands, as in "$=". The dot . is not a concatenation operator in Ruby. I don't think this is Ruby. It's like a hybrid of languages.
I am not a Ruby expert by any means by the first step should be make it into a format you can read. I broke it down by line.
`$=`;
$_=\%!;
($_)=/(.)/;
$==++$|;
($.,$/,$,,$\,$",$;,$^,$#,$~,$*,$:,#%)=($!=~/(.)(.).(.)(.)(.)(.)..(.)(.)(.)..(.)......(.)/,$"),$=++;$.++;$.++;
$_++;
$_++;
($_,$\,$,)=($~.$"."$;$/$%[$?]$_$\$,$:$%[$?]",$"&$~,$#,);
$,++;
$,++;
$^|=$";
`$_$\$,$/$:$;$~$*$%[$?]$.$~$*${#}$%[$?]$;$\$"$^$~$*.>&$=`
I cheated and tried to run it, and it doesn't work. I get an unexpected null error.
Don't feel bad if you can't do this. This seems pointless. Programming questions should try to test your skills not test you on something that if somebody is really using it would mean there application would be really bad.
This looks closer to Perl, to be honest, but in any case pretty nonsensical.
Not related to Ruby I think, above encoded message is given at https://en.wikipedia.org/wiki/Just_another_Perl_hacker with the help of only punctuation. Another one is also provided there.
''=~('(?{'.('-)#.)#_*([]#!#/)(#)#-#),#(##+#)'
^'][)#]`}`]()`#.#]#%[`}%[#`#!##%[').',"})')

Resources