Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can somebody explain to me the algorithm for the Parenthesis Balancing problem?
"Is the string (code) syntax correct on account of matching parentheses couples?"
I can't figure it out apart from the fact that for each " ( " there should be another " ) " for the algorithm to return true.
Thanks!
I found this solution but I do not understand it and I don't want to copy and paste it:
def balance(chars: List[Char]): Boolean = {
def balanced(chars: List[Char], open: Int): Boolean = {
if (chars.isEmpty) open == 0
else
if (chars.head == '(') balanced(chars.tail,open+1)
else
if (chars.head == ')') open>0 && balanced(chars.tail,open-1)
else balanced(chars.tail,open)
}
balanced(chars,0)
}
This code recursively checks if string contains matching amount of opening and closing parentheses by calling balanced() on the string without first element.
Expectancy of parentheses in the string is kept in a kind of balance indicator open - positives indicate amount of needed ')' and negatives amount of needed '('. Initial balance is 0.
When recursion reaches end of string it checks if balance is ok (open == 0), e.g. there was matching amount of parentheses seen.
There is also a check (open > 0) to ensure that ')' wasn't encountered before there was '(' it could close.
Related
I'm reading text from a text file in Scala. I'm having difficulties with if statements.
for (line <- Source.fromFile(filename).getLines) {
if (line.length>7) {
println("b1 >" + line(7)+ "< " + line(0).getType)
if(line(7)=="#") {
println("hashtag")
}
}
}
below is 2 lines from my text file. the first line has 4 spaces followed by many hashtags. the second line is 4 spaces followed by 1 hashtag (the 4 spaces keep getting deleted by stack overflow)
##################################################################################################################################################
#
below is the output i recieve
//| b1 >#< 12
//| b1 > < 12
Question 1) why is getType returning 12? This is the strangest data type I've ever heard of.
Question 2) (possibly answered by Q1) why does the if(line(7)=="#") statement never returns true?
To answer your questions in reverse order:
Question 2. Because line is a String, line(7) is a Char which is never equal to a String. You want to compare it with '#' instead.
Question 1. Because of the above, this calls Char.getType method which
Returns a value indicating a character's general category.
(not that you can find it from Scala's own documentation). You probably wanted getClass instead.
The is_a? method doesn't work; I have tried it and it apparently it checks if the value is derived from an object or something.
I tried something like this:
printf "What is the Regular Price of the book that you are purchasing?"
regular_price=gets.chomp
if regular_price.to_i.to_s == regular_price
print "Thank You #{regular_price}"
break
else
print "Please enter your price as a number"
end
Can someone explain to me more what .to_i and .to_s do? I just thought they convert the user input to a string, or a Numerical Value. I actually don't know how to check input to see if what he put in was a float, a String, or a decimal.
I just keep getting Syntax errors. I just want to know how to check for any of the 3 values and handle them accordingly.
There's a lot to your question so I recommend that you read How do I ask a good question? to help you get answers in the future. I'll go through each of your questions and try to provide answers to point you in the right direction.
The is_a? method works by accepting a class as a parameter and returning boolean. For example:
'foo'.is_a?(String)
=> true
1234.is_a?(Integer)
=> true
'foo'.is_a?(Integer)
=> false
1234.is_a?(String)
=> false
1.234.is_a?(Float)
=> true
The .to_i method is defined on the String class and will convert a string to an Integer. If there is no valid integer at the start of the string then it will return 0. For example:
"12345".to_i #=> 12345
"99 red balloons".to_i #=> 99
"0a".to_i #=> 0
"hello".to_i #=> 0
The .to_s method on the Integer class will return the string representation of the Integer. For example:
1234.to_s
=> '1234'
The same is true of Float:
1.234.to_s
=> '1.234'
Now let's take a look at your code. When I run it I get SyntaxError: (eval):4: Can't escape from eval with break which is happening because break has nothing to break out of; it isn't used to break out of an if statement but is instead used to break out of a block. For example:
if true
break
end
raises an error. But this does not:
loop do
if true
break
end
end
The reason is that calling break says "break out of the enclosing block," which in this case is the loop do ... end block. In the previous example there was no block enclosing the if statement. You can find more detailed explanations of the behavior of break elsewhere on stackoverflow.
Your final question was "I just want to know how to check for any of the 3 values and handle them accordingly." This answer explains how to do that but the code example is written in a way that's hard to decipher, so I've rewritten it below in an expanded form to make it clear what's happening:
regular_price = gets.chomp
begin
puts Integer(regular_price)
rescue
begin
puts Float(regular_price)
rescue
puts 'please enter your price as an Integer or Float'
end
end
What this code does is first it attempts to convert the string regular_price to an Integer. This raises an exception if it can't be converted. For example:
Integer('1234')
=> 1234
Integer('1.234')
ArgumentError: invalid value for Integer(): "1.234"
Integer('foo')
ArgumentError: invalid value for Integer(): "foo"
If an exception is raised then the rescue line stops the exception from being raised and instead continues executing on the next line. In this case, we're saying "if you can't convert to Integer then rescue and try to convert to Float." This works the same way as converting to Integer:
Float('1.234')
=> 1.234
Float('foo')
ArgumentError: invalid value for Float(): "foo"
Finally, we say "if you can't convert to Float then rescue and show an error message."
I hope this helps and answers your questions.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have text as below,
TIME STAMP1
A1200 EVENT START
EVENT NAME = DOS
EVENT_INS = 1
EVENT_ID = 100
BUFFER = 233355
FORMAT = ATC
LOC = C:/User/data
;
TIME STAMP2
A1201 EVENT START
EVENT NAME = DOS
EVENT_INS = 0
EVENT_ID = 87
BUFFER = 773355
FORMAT = ETC
LOC = C:/User/data
;
how can I remove TIME STAMP2 based on A1201,need to remove from A1201 to ; using scala.A1201 sensor part will repeat at different location in the file. Wherever it comes, I need to remove from A1201 to ;..
How can I do with Scala Spark ?.
You can use the following simple solution
val rdd = sparkContext.wholeTextFiles("path to the text file")
rdd.map(x => x._2.replace("\n", "|*|").split(";").filter(!_.contains("A1201")).mkString(";").replace("|*|", "\n")+";")
where, wholeTextFiles would read the file in Tuple2 format with filename as first argument and text data as the second argument
x._2.replace("\n", "|*|") replaces the line feeds with special character which is to be used later
.split(";") splits the text at ; and forms array
.filter(!_.contains("A1201")) filters out all text from A1201 to ;
.mkString(";").replace("|*|", "\n")+";" converts the array of string to original format.
I hope the answer is helpful
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
Can anyone tell me the name of this cipher please?
I know it's a simple substitution cipher, I just don't know the name of it.
Cipher Key:
help
Cipher alphabet:
a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
h|e|l|p|a|b|c|d|f|g|i|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z
Text:
this is a test
Cipher text:
tdfs fs h tast
Isn't that just a simple substitution cipher? You've just moved the 4 letters of "help" to the front and shifted all the remaining letters to the right.
EDIT
Here's an implementation in python as an exercise in lambda, itertools, and star (*) arguments, and wasting time (and perhaps to rescue what could be an interesting discussion on coding ciphers in python):
import string
from itertools import izip, count, starmap
def cipher(s,key):
# characters you want to translate, e.g.
# 'abcd ... xyz '
raw = string.ascii_lowercase + ' '
# cipher with your key, e.g.
# 'helpabcdfgi...z '
sub = key + string.translate(raw, None, key)
# create a dictionary from a character to an index
# in the original raw value string
m = dict( izip( raw, count() ) )
# looks up the index in the map using: starmap(m.get, s)
# then gets the substitution character: map( lambda i:sub[i], ...)
# and joins them together
return ''.join( map( lambda i:sub[i], starmap( m.get, s ) ))
And some test code to verify it works:
ins = 'this is a test'
outs = cipher(ins, "help")
print ins,' -> ',outs
exp = "tdfs fs h tast"
if exp == outs:
print "pass :)"
else:
print "~~ FAIL ~~", " expected ", exp
Output:
D:\temp>cipher.py
this is a test -> tdfs fs h tast
pass :)
I think I have found the answer. A Caesar variant, a "Mixed Alphabet" substitution cipher.
Simple yes, but to add mor complexity you could put it in a block like this (becoming a mixture of Mixed Alphabet and Polyalphabetic):
|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z
------------------------------------------------------
1|h|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z
2|e|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z|h
3|l|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z|h|e
4|p|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z|h|e|l
5|a|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z|h|e|l|p
6|b|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z|h|e|l|p|a
7|c|d|f|g|I|j|k|m|n|o|q|r|s|t|u|v|w|x|y|z|h|e|l|p|a|b
8|d|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then be more of a Vigenere Cipher variant rather than a Caesar Cipher variant.
Still with the key:
help
The same message:
this is a test
Would become:
tfiv kx c hkep
Another level of complexity would be to group the letters either all together or into blocks:
tfivkxchkep
or blocked (3 characters):
tfi
vkx
chk
epz
With an extra z added to make up the missing character.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
Does anyone know of an existing method of automatically cleaning the indentation of a MATLAB/Octave script? I've got someone else's code (no, really!), and it's horrible - none of the loops or functions are indented, and half of the other lines are indented to apparently random depths.
The problem with MATLAB is that it doesn't use braces, so C++ style indenters aren't going to work. Python ones might, with a bit of modification, which I will try if I can't find a pre-existing solution.
Basically it'd just need to indent lines after lines starting with function, for, if, while... and un-indent lines starting with end*, I think...
Clarification: As pointed out by Jonas, MATLAB users can just select all, and ctrl+I to nicify the indentation. Unfortunately, I don't have access to the MATLAB editor, and it would also be nice to be able to auto-indent a batch of files all at once.
CTRL+A (to select all), followed by CTRL+I (to automatically indent) will do the trick in the Matlab editor.
Ah, I should have known emacs and vi would have answers. I really should learn one of them. Anyway, I got frustrated with the work I was doing, and wrote this as a displacement activity. Remove the + '.test.m' to replace files:
#!/usr/bin/env python
import re, sys
def startswith(line=""):
# these need some word-boundary condition, but \b isn't working
ctrlstart = '\s*(function|if|while|for|switch)'
ctrlcont = '\s*(elseif|else|case|catch|otherwise)'
ctrlend = '\s*(end|endfunction|endif|endwhile|endfor|endswitch)'
match = re.match(ctrlstart, line)
if ( match != None ) :
return ['start', match.group(0)]
match=re.match(ctrlcont, line)
if ( match!=None ) :
return ['cont', match.group(0)]
match=re.match(ctrlend, line)
if ( match!=None ) :
return ['end', match.group(0)]
else :
return [False, None]
def main( filelist = list() ) :
for filename in filelist:
nextindent = 0
indentmult = 2
file = open(filename, 'r')
filelines = file.readlines()
for ind in range(0, len(filelines)) :
indentlevel = nextindent
match = startswith(filelines[ind])
if match[0] == 'start' :
nextindent += 1
elif match[0] == 'cont' :
indentlevel -= 1
elif match[0] == 'end' :
indentlevel -= 1
nextindent -= 1
elif match[0] == False :
nextindent = indentlevel
filelines[ind] = ' '*indentlevel*indentmult + filelines[ind].lstrip().rstrip() +'\n'
outfile = open(filename + '.test.m', 'w')
outfile.writelines(filelines)
file.close()
outfile.close()
args = []
for arg in sys.argv[1:] :
args += [str(arg)]
main(args)
I tried the emacs way but it doesn't work, i am new to ubuntu and octave. So i took the easiest way :D, online site that indent the code for me and i can copy/paste the new clean code.
http://base-n.de/matlab/code_beautifier.html
Here is a vim plugin to automatically indent and syntax highlight for octave code
https://github.com/tranvansang/octave.vim