How to construct binary tree from algebraic expression - data-structures

In my exam I got this expression and failed to construct binary tree. what would be the solution?
(5a-3b)^2*(3a+5b)^3
I drew the tree from above expression like
*
/ \
/ \
^ \
/ \ \
/ \ \
- 2 ^
/ \ / \
/ \ + 3
* * / \
/ \ / \ / \
5 a 3 b * *
/ \ / \
3 a 5 b
I got 0 from this answer! I could not understand the reason!
Can anybody help me?

Constructing a binary tree doesn't mean that you just draw the graphical representation which you have shown here.
I think It actually means to implement in code or may in pseudo code.
So think again using stack with the same expression
Convert the infix notation to postfix and you can solve it easily by using stack property.

I am currently taking a discrete mathematics course and we are on the subject of trees. You have to remember to put each level in its own (). So I believe the tree you created would look like this as an expression: ((5*a)-(3*b))^2*((3*a)+(5*b))^3. This is an Inorder traversal of the tree. For your answer you needed to have something more like this:
*
/ \
/ \
/ \
^ \
/ \ \
/ \ \
- 2 ^
/ \ / \
/ \ / 3
5a 3b +
/ \
/ \
3a 5b

Related

sqoop export from hdfs to mysql failed, need help to escape the characters

I have a file in hdfs and exporting it to sqoop table. please find the log details below:
Caused by: java.lang.RuntimeException: Can't parse input data: ' characters'
at tags.__loadFromFields(tags.java:335)
at tags.parse(tags.java:268)
at org.apache.sqoop.mapreduce.TextExportMapper.map(TextExportMapper.java:89)
... 10 more
sqoop export command
sqoop export \
--connect "**************************************" \
--username=**** \
--password=***** \
--table tags \
--export-dir /user/cloudera/movie_lens/tags_no_header.csv \
--batch \
--input-lines-terminated-by '\n' \
--input-fields-terminated-by ',' \
--num-mappers 9 \
Table Structure :
create table tags
(userId integer
,movieId integer
,tag varchar(150)
,timestamp decimal
);
Record failing :
660,260,"imaginary world, characters, story, philosophical",1436680217
As per my understanding It's failing because of ambiguous parsing caused by comma ',' in middle of string.
Please help me to understand usage of --input-enclosed-by and --input-escaped-by arguments in this case or Is there any other solution.
I have got it resolved using attribute --input-optionally-enclosed-by.
export command :
sqoop export \
--connect "jdbc:mysql://quickstart.cloudera:3306/movie_lens_db" \
--username=root \
--password=cloudera \
--table tags \
--export-dir /user/cloudera/escape_by_test.txt \
--batch \
--input-lines-terminated-by '\n' \
--input-fields-terminated-by ',' \
--input-optionally-enclosed-by '\"' \
--num-mappers 1 \
--outdir java_files
Table Data :
+--------+---------+---------------------------------------------------+------------+
| userId | movieId | tag | timestamp |
+--------+---------+---------------------------------------------------+------------+
| 660 | 260 | imaginary world, characters, story, philosophical | 1436680217 |
| 212 | 69712 | genuine characters | 1260688086 |
+--------+---------+---------------------------------------------------+------------+

Algorithmic Stock Trading - how to efficiently process an event-stream for updates of [ Mean, StDev, Median ] values?

I have implemented a simplified algorithm that maintains stock statistics from a stream of incoming data. The goal is to use efficient algorithms to compute simple statistics, mean, variance and median. The program will only maintain one value for each company, hence new values for a previously rated company should replace the previous value. Companies may also be removed from the current list, with a delete command. The input must be something like this:
A 111.12 Apple_Inc
A 745.29 Alphabet_Inc
A 17.10 Twitter_Inc
S
A 101.33 Apple_Inc
S
A 112.55 Facebook_Inc
S
D Apple_Inc
S
"A" means to input data, "D" means to delete data and when asked for"S", the program should give us this output: ( avg is average, s is a standard deviation, m is a median )
avg 291.17
s 156878.67
m 111.12 Apple_Inc
avg 287.91
s 158673.31
m 101.33 Apple_Inc
avg 244.07
s 113469.70
m 112.55 Facebook_Inc
avg 291.65
s 156621.88
m 112.55 Facebook_Inc
Just as a note, when we have to compute the median, if the number of companies is odd, it should return the bigger number in the middle with the respective name of company.
The statistic values should always be updated instead making new ones, as long as we insert, delete or add new values.
The most efficient processing would use a Finite-State-Machine
I dare to state this ( and can behold the resources-footprint / overall-performance / stream-processing latency ultimate extremes ) after almost half-century hands-on experience in the High-Tech ( sure, the term high creeps as time forwards :o) but surprisingly not inflating the acquired knowledge )
Given the rules above, the FSA has quite simple
FSA inputs:{ A, D, S }-prefixed-ValuePAIR-( aListedTitleVALUE, aListedTITLE )
FSA internal state variable: aListOfListedTitleValuePairsToPROCESS,empty on [X]-state ( an un-initialised state ( when FSA "off" ) )
FSA event processing:
as given above:
{ onA_aListedValuePairUPDATE, //.CHK aValuePAIR presence in FSA-state + .UPD { aValuePAIR | aValuePAIR.aListedTitleVALUE }
onD_aListedValuePairDELETE, //.DEL aValuePAIR from FSA-state
onS_ProcessAndPrintRESULTS //.DO {Mean,StDev,Median } on FSA-state + .PRINT
}
A formal topology - a Finite-State-Automaton diagram
[X]
\
( .onInit )->---[FSA.WAIT-STATE]
^ \ \ \
| \ \ ( .onA_aListedValuePairUPDATE )->---[FSA.UPDATE aListedValuePair]
| \ \ \
| \ \ ( .onDone )->---(*)-----------+
| \ \ |
| \ ( .onD_aListedValuePairDELETE )->---[FSA.DELETE aListedValuePair] |
| \ \ |
| \ ( .onDone )->---------------+ |
| \ | |
| ( .onS_ProcessAndPrintRESULTS )->---[FSA.PROCESS] | |
| \ | |
| ( .onDone )->---[FSA.PRINT] | |
| \ | |
| ( .onDone )->---+ | |
| | | |
+-----------------------------------------------------------------------------------------------------+-+-+
Design options:
depending on an input stream-processing latency v/s computing powers of the underlying hardware ( as FSA-s are so simple, it could be a minimalistic super-fast SoC-hardware implementation ) v/s (non-)blocking nature of the output processor, there might be faster to include a [FSA.PROCESS] as a sort of "pre-compute" part of the onS_ProcessAndPrintRESULTS already as a tail-activity after a ( .onA_aListedValuePairUPDATE )-> FSA-transition ref.: *

How to convert following into a Binary Tree?

What is the procedure to convert following into a binary tree? And what will be the output/answer ? A+(B+C+D+E)+F/G
A+(B+C+D+E)+F/G
result
|
A
A+(B+C+D+E)+F/G
result
| \
A obj1
A+(B+C+D+E)+F/G
result
| \
A obj2
/ \
obj1 F/G(could be linked to A for load balancing)
(B+C+D+E)
result
| \
A obj2
/ \
obj1 F/G
/
B
(B+C+D+E)
result
| \
A obj2
/ \
obj1 F/G
/ \
B C
(B+C+D+E)
result
| \
A obj2
/ \
obj3 F/G
| \
obj1 D
/ \
B C
(B+C+D+E)
result
| \
A obj2
/ \
obj4 F/G
| \
obj3 E
| \
obj1 D
/ \
B C
F/G
result
| \
A obj2
/ \
obj4 obj5
| \ |
obj3 E F
| \
obj1 D
/ \
B C
F/G
result
| \
A obj2
/ \
obj4 obj5
| \ | \
obj3 E F G
| \
obj1 D
/ \
B C
once tree is complete, start computing from bottom to top(all leafs) then all branchs whose leafs are complete.
B+C = obj1
B+C+D =obj3
B+C+D+E =obj4
F/G = obj5
(B+C+D+E)+F/G = obj2
A+(B+C+D+E)+F/G = result

Bash Shell Scripting - Dialog form variables

So, I just took up Shell Scripting and I'm developing an address book.
For the user to insert a contact I made this form:
form=$(dialog \
--title "INSERIR" \
--form "" \
0 0 0 \
"Nome:" 1 1 "$nome" 1 10 20 0 \
"Morada:" 2 1 "$morada" 2 10 20 0 \
"Telefone:" 3 1 "$telefone" 3 10 20 0 \
"E-Mail:" 4 1 "$mail" 4 10 20 0 \
2>&1 1>&3)
And I want to insert those values through a MySQL query. I saw somewhere that I had to use, for instance:
form[$1]
In order to access the variable $nome. However, it was a comment from 2008.
What is the easiest way to access those variables?
Thank you!
IFS=$'\n' read -r -d '' nome morada telefone mail < <( dialog ... )
Unlike dialog ... | { read; ... } (which scopes the variables which are read to a subshell), this approach puts dialog in the subshell, and your variables in the main shell -- much more convenient.
So, after a bit of tinkering I got what I was looking for.
Here is the new form:
exec 3>&1
dialog \
--separate-widget $'\n' \
--title "INSERIR" \
--form "" \
0 0 0 \
"Nome:" 1 1 "$nome" 1 10 30 0 \
"Morada:" 2 1 "$morada" 2 10 30 0 \
"Telefone:" 3 1 "$telefone" 3 10 30 0 \
"E-Mail:" 4 1 "$mail" 4 10 30 0 \
2>&1 1>&3 | {
read -r nome
read -r morada
read -r telefone
read -r mail
#The rest of the script goes here
}
exec 3>&-
So, you can really just put the output into an array and deal with that. Avoids all the subshell / subprocess garbage. (Just trust on the flippy redirect, yeah, it's ugly but you're basically just subbing out stdin and swapping it back.) Not sure why that's been so elusive after 5 years, but hey. I guess it's cool to be obscure.
response=$(dialog \
--title "INSERIR" \
--form "" \
0 0 0 \
"Nome:" 1 1 "$nome" 1 10 20 0 \
"Morada:" 2 1 "$morada" 2 10 20 0 \
"Telefone:" 3 1 "$telefone" 3 10 20 0 \
"E-Mail:" 4 1 "$mail" 4 10 20 0 \
3>&1 1>&2 2>&3 3>&-)
#convert the space separated string to an array.. the madness!!
responsearray=($response)
echo ${responsearray[0]} #nome
echo $(responsearray[1]} #morada
echo ${responsearray[2]} #telefone
echo ${responsearray[3]} #mail
...and bob's your uncle.
After several days looking for a way get those variables, here what I used, with your form:
nome=""
morada=""
telefone=""
mail=""
user_record=$(\
dialog \
--separate-widget $'\n' \
--title "INSERIR" \
--form "" \
0 0 0 \
"Nome:" 1 1 "$nome" 1 10 30 0 \
"Morada:" 2 1 "$morada" 2 10 30 0 \
"Telefone:" 3 1 "$telefone" 3 10 30 0 \
"E-Mail:" 4 1 "$mail" 4 10 30 0 \
3>&1 1>&2 2>&3 3>&- \
)
nome=$(echo "$user_record" | sed -n 1p)
morada=$(echo "$user_record" | sed -n 2p)
telefone=$(echo "$user_record" | sed -n 3p)
mail=$(echo "$user_record" | sed -n 4p)
echo $nome
echo $morada
echo $telefone
echo $mail
This way you can use those variables later on your script.
Hope it helps others.
The question regarding the easiest way to access the result depends partly on whether the items might contain blanks. If the items can contain arbitrary data, then line-oriented output (the default) seems the only way to go. If they are more constrained, e.g., not containing some readily-used punctuation character which can be used as a delimiter, then that makes it simpler.
The manual page mentions an option (and alias) which can be used to do this:
--separator string
--output-separator string
Specify a string that will separate the output on dialog's output from checklists, rather than a newline (for --separate-output) or a space. This applies to other widgets such as forms
and editboxes which normally use a newline.
For example, if the data does not include a : (colon), then you could use the option
--output-separator :
and get colon-separated values on a single line.
If there are no commas or quotes in the string, you could conceivably use
--output-separator \",\"
and embed the result directly in an SQL statement. However, commas occur more frequently than the other punctuation mentioned, so processing the form's output with sed is the most likely way one might proceed.

Trouble making ascii art in .bashrc file

I get these errors when trying to use: export PS1='ascii text at bottom'.
bash: command substitution: line 1: syntax error near unexpected token |'
bash: command substitution: line 1:/ ^ \ | |_) |'
bash: command substitution: line 3: syntax error near unexpected token |'
bash: command substitution: line 3: \ /\ / / _____ \ | |\ ---) |'
Could someone explain why this doesn't work?
________________. ___ .______
/ | / \ | _ \
| (-----| |----`/ ^ \ | |_) |
\ \ | | / /_\ \ | /
.------) | | | / _____ \ | |\ \-------.
|_________/ |__| /__/ \__\| _| `.________|
____ __ ____ ___ .______ ________.
\ \ / \ / / / \ | _ \ / |
\ \/ \/ / / ^ \ | |_) || (-----`
\ / / /_\ \ | / \ \
\ /\ / / _____ \ | |\ \---) |
\__/ \__/ /__/ \__\|__| `._______/
PS1 is not just a plain string; in it, certain characters have meaning to them. You can find a surprisingly long document telling you more about bash prompts than you ever wanted to know here; it's a bit dated, but most of it should still hold. The particular problem you run into is that backslashes and backticks need to be escaped -- backslashes because they're used to escape things, and backticks because they're used for command substitutions -- and newlines are best replaced with the \n control sequence to avoid mishaps with lines that end in \. Ultimately, you want the effect of writing
export PS1=' ________________. ___ .______ \n / | / \\ | _ \\\n | (-----| |----\`/ ^ \\ | |_) |\n \\ \\ | | / /_\\ \\ | /\n.------) | | | / _____ \\ | |\\ \\-------.\n|_________/ |__| /__/ \\__\\| _| \`.________|\n____ __ ____ ___ .______ ________.\n\\ \\ / \\ / / / \\ | _ \\ / |\n \\ \\/ \\/ / / ^ \\ | |_) || (-----\`\n \\ / / /_\\ \\ | / \\ \\\n \\ /\\ / / _____ \\ | |\\ \\---) |\n \\__/ \\__/ /__/ \\__\\|__| \`._______/'
...which is somewhat unwieldy. A way to do this on the fly so that it is easier on the eyes is
PS1=' ________________. ___ .______
/ | / \ | _ \
| (-----| |----`/ ^ \ | |_) |
\ \ | | / /_\ \ | /
.------) | | | / _____ \ | |\ \-------.
|_________/ |__| /__/ \__\| _| `.________|
____ __ ____ ___ .______ ________.
\ \ / \ / / / \ | _ \ / |
\ \/ \/ / / ^ \ | |_) || (-----`
\ / / /_\ \ | / \ \
\ /\ / / _____ \ | |\ \---) |
\__/ \__/ /__/ \__\|__| `._______/'
PS1="${PS1//\\/\\\\}"
PS1="${PS1//\`/\\\`}"
PS1="${PS1//
/\\n}"
export PS1 # <-- this isn't really necessary, by the way. PS1 is not
# usually used by processes the shell spawns.
Here ${variable//pattern/replacement} is a bash-specific parameter expansion that expands to the value of $variable with all occurrences of pattern replaced with replacement. That is to say:
PS1="${PS1//\\/\\\\}" # replaces \ with \\
PS1="${PS1//\`/\\\`}" # replaces ` with \`
PS1="${PS1// # replaces newlines with \n
/\\n}"

Resources