Can I prevent GNU bc from spewing out zeros? - bc

Suppose I want to solve the equation x + 3 = 40 using GNU bc. One way I could do this would be to start by checking to see if 0 is a solution, then checking 1, and so on, until I get to the right answer. (Obviously not the best way to do algebra, but oh well.) So I enter the following code into GNU bc:
int solver(int x);
define solver(x){
if(x + 3 == 40) return x;
x = x + 1;
solver(x)
}
solver(0)
It produces 37 - the right answer, of course - but the 37 is then followed by 37 zeros. Based on some experimentation, it seems like each zero comes from an instance of the if statement being false, but how do I prevent the zeros from showing up? I'm using GNU bc to solve more complicated functions and create more complex lists of numbers, so it really isn't practical for me to sort through all the zeros. Any help would be appreciated, since I haven't yet figured anything out.

For each operation that isn't an assignment, bc prints an exit status. One way to suppress that is to assign to the dummy value . (which is just the value of the last result anyway), another way is to make sure you explicitly print exactly what you need.
I would have written your function like this:
#!/usr/bin/bc -q
define solver(x) {
if (x + 3 == 40) return x
return solver(x+1)
}
print solver(0), "\n"
quit
A few remarks for your attempt:
I don't understand what your first line is supposed to do, I just dropped it
I've indented the code, added some whitespace and removed the semicolons – mostly a matter of taste and readability
I've simplified the recursive call to avoid the solver(x) line stand on its own, as this produces the spurious 0
As for your suspicion that the if statement produces the zeroes: try, in an interactive session, the following:
1 == 2 # Equality test on its own produces output
0
1 == 1 # ... for both true and false statements
1
if (1 == 2) print "yes\n" # No output from false if condition
if (1 == 1) print "yes\n" # If statement is true, print string
yes

Related

Elm - Executing multiple lines per if branch

For example, in one branch, I want see how many times a number is divisible by 1000, then pass the starting number less that amount into the function recursively. This is what I have written:
if num // 1000 > 0 then
repeat (num // 1000) (String.fromChar 'M')
convertToRom (num % 1000)
However, I get the following error in the REPL when testing:
> getRomNums 3500
-- TYPE MISMATCH ----------------------------------------- .\.\RomanNumerals.elm
Function `repeat` is expecting 2 arguments, but was given 4.
34| repeat (num // 1000) (String.fromChar 'M')
35|> convertToRom (num % 1000)
Maybe you forgot some parentheses? Or a comma?
How can I write multiple lines of code for a single if branch?
Unrelated side note: The format system makes the double slash a comment, but in Elm the double slash is integer division. Not sure how to fix that.
In Elm (and other functional languages like Haskell), you don't write code in iterative steps like you do in imperative languages. Every function has to return a value, and every branch of logic has to return a value. There is no single answer around how to "do multiple things" in Elm but with Elm's type system, tuples, and recursion, you'll find that the lack of imperative doesn't really hold you back from anything. It's just a paradigm shift from writing code in an imperative style.
For your purposes of writing a roman numeral conversion function, I think an immediate answer lies in using explicit recursion and string concatenation on the result:
convertToRom : Int -> String
convertToRom num =
if num // 1000 > 0 then
String.repeat (num // 1000) (String.fromChar 'M') ++ convertToRom (num % 1000)
else if ...
else
""
As you grow your functional programming toolset, you'll find yourself explicitly using recursion less and less and relying on higher levels of abstraction like folds and maps.

How can I check if two cells are equal in brainf*ck?

How can I check if the value in cell #0 is equal to the value in cell #1? I am trying to write code equivalent to:
if(a == b)
{
//do stuff
}
else
{
//do something else
}
I have read Brainfuck compare 2 numbers as greater than or less than, and the second answer gave me a general idea of what I'd need to do, but I cannot figure it out. (That solution gives if a < b, else.)
I am thinking I need to do something along the lines of decrementing both values, and if they reach 0 at the same time, then they are true. But I keep getting stuck at the same exit point every time I think about it.
How can I check if two cells are equal in brainfuck?
I think I have it, I'm not a brainfuck expert but this question looked interesting. There might be a simpler way to do it, but I went with your method of decrementing values one by one.
In this case, if the two values in cell 0 and 1 are equal jump a ton forward, if they are not equal jump a little forward (second brackets is the not equal case, third brackets is the equal case)
Note that I'm using brainfucks while statements as a ghetto if (cell != 0)
+++++++++++++++++
>
+++++++++++++++++
>+<
[ - < - >] <[>>>>>] >> [>>>>>>>>>>>>>>>>>>>>>]
Try it online: http://fatiherikli.github.io/brainfuck-visualizer/#KysrKysrKysrKysrKysrKysKPgorKysrKysrKysrKysrKysrKwo+KzwKWyAtIDwgLSA+XSA8Wz4+Pj4+XSA+PiBbPj4+Pj4+Pj4+Pj4+Pj4+Pj4+Pj4+XQoKCg==
An example implementation, print T (true) if the two values are equal, F (false) if they are not equal
http://fatiherikli.github.io/brainfuck-visualizer/#KysrCj4KKysrKwo+KzwKWyAtIDwgLSA+XSA8Wz4+PgorKysrKysrKysrKysrKysrKysrKworKysrKysrKysrKysrKysrKysrKworKysrKysrKysrKysrKysrKysrKworKysrKysrKysrCi4KPgoKXSA+PiBbCisrKysrKysrKysrKysrKysrKysrCisrKysrKysrKysrKysrKysrKysrCisrKysrKysrKysrKysrKysrKysrCisrKysrKysrKysrKysrKysrKysrCisrKwouCj4KXQ==
+>>(a+++++)>(b+++++)>>+<<<
[[->]<<]
<
[>>>>>-<<<<<
a>b
]
>>
[->>-<
a<b
]
>>
[-
a=b
]
Pointer ends on the same pointer in the same state but the code within the appropriate brackets has been executed.
I came up with this for my bf compiler thing
basically it subtracts and then checks if the result is 0.
Can be easily changed to execute stuff in if/else-ish way
Layout:
[A] B
>[-<->]+<[>-<[-]]>
Output
0 [result]
Result is 1 if equal

Shortened method to reduce statements in an Ada procedure?

I am creating a procedure that uses an if statement to perform a decision.
I have four variables: Altitude, Velocity, Angle and Temperature.
The procedure is as follows:
procedure Test3 is
begin
if (Integer(Status_System.Altitude_Measured)) >= Critical_Altitude
and (Integer(Status_System.Velocity_Measured)) >= Critical_Velocity
and (Integer(Status_System.Angle_Measured)) >= Critical_Angle
and (Integer(Status_System.Temperature_Measured)) >= Critical_Temperature
then
DT_Put ("message 1");
else
null;
end if;
end Test3;
This procedure is bassicaly taking the idea that if all the critcal values for the variables are met for each and every variable then it will print a message.
I want to be able to have a shorter way of paring up the statements so I can do the following:
If I have 4 variables: Altitude, velocity, angle and temperature
and I want to have a statement that says, If atleast 3 of these varibles (doesnt matter which three) are all exceeding their critical values
then display a message.
Is it even possible to do this?
I would hate to think that I would have to write each and every possible combination for the if statements.
In short, I want an if statement that says at least 3 of the variables shown are at their criticle value so print a message.
The same would be good for atleast 2 of these variables as well.
First, you should try to use specific types for altitude, velocity, angle and temperature. By using different types you'll leverage strong typing provided by Ada and avoid mistakes such as mixing or comparing altitudes and temperatures. Your example suggests that all of them are Integer. One possible definition could be (there are many others):
type Temperature is digits 5 range -273.15 .. 300.0;
type Angle is digits 5 range -180.0 .. 180.0;
The advantage of such definition is that you define both the range of values and the precision (captors all have a finite precision).
Counting the number of errors is one way do that.
In Ada 2012, you could write:
EDIT
Errors : Natural := 0;
...
Errors := Errors + (if Altitude_Measured > Critical_Altitude then 1 else 0);
Errors := Errors + (if Velocity_Measured > Critical_Velocity then 1 else 0);
Errors := Errors + (if Angle_Measured > Critical_Angle then 1 else 0);
Errors := Errors + (if Temperature_Measured > Critical_Temperature then 1 else 0);
if Errors >= 2 then
...
end if;
Boolean is an enumeration type with values (False, True). As with any enumeration type, the 'Pos attribute can be used to get the position of a value in the list of enumeration literals. Thus, Boolean'Pos(B) equals 0 if B is false, 1 if B is true.
Thus you could say
True_Count := Boolean'Pos(Integer(Status_System.Altitude_Measured) >= Critical_Altitude)
+ Boolean'Pos(Integer(Status_System.Velocity_Measured) >= Critical_Velocity)
+ Boolean'Pos(Integer(Status_System.Angle_Measured) >= Critical_Angle)
+ Boolean'Pos(Integer(Status_System.Temperature_Measured)) >= Critical_Temperature);

Wrong print out statement in python 2.7

The Question:
5.Now write the function is_odd(n) that returns True when n is odd and False otherwise.
Finally, modify it so that it uses a call to is_even to determine if its argument is an odd integer.
I had to write a function for is_even(n) that returns True when n even and False otherwise. Here is my code:
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n):
print "This is an even integer."
else:
print "This is an odd integer."
return n % 2 != 0
My Question:
I am a total beginner and find programming very hard but I love it for some reason, but why does this not work? I defined the function is_even(n) and is_odd(n), put is_even(n) into the is_odd(n) function, wrote and if/else else statement making if the function is_even is equal to true it should print out it is an even integer... When I put in is_odd(3); it prints out "This is an even integer" and returns True even though it should print out "This is an odd integer."
Update:
I changed my code to this and works fine.
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n) == False:
print "This is an odd integer."
return n % 2 != 0
You're encountering IndentationError because you're being inconsistent with your indentation. As soon as you indent in Python, you have created a new block. You do this after block-introducing keywords, like if, while, for, etc. Python doesn't care how many spaces or tabs or whatever you use before your first block, but once you make the choice the first time, you must keep using the same number. I've added a line to your posted code to show you:
See how the r in return aligns with the f in if? It needs to align with the i. In this example your if is not at the proper indentation level relative to the first block, producing the error in question.

Solving a linear equation in one variable

What would be the most efficient algorithm to solve a linear equation in one variable given as a string input to a function? For example, for input string:
"x + 9 – 2 - 4 + x = – x + 5 – 1 + 3 – x"
The output should be 1.
I am considering using a stack and pushing each string token onto it as I encounter spaces in the string. If the input was in polish notation then it would have been easier to pop numbers off the stack to get to a result, but I am not sure what approach to take here.
It is an interview question.
Solving the linear equation is (I hope) extremely easy for you once you've worked out the coefficients a and b in the equation a * x + b = 0.
So, the difficult part of the problem is parsing the expression and "evaluating" it to find the coefficients. Your example expression is extremely simple, it uses only the operators unary -, binary -, binary +. And =, which you could handle specially.
It is not clear from the question whether the solution should also handle expressions involving binary * and /, or parentheses. I'm wondering whether the interview question is intended:
to make you write some simple code, or
to make you ask what the real scope of the problem is before you write anything.
Both are important skills :-)
It could even be that the question is intended:
to separate those with lots of experience writing parsers (who will solve it as fast as they can write/type) from those with none (who might struggle to solve it at all within a few minutes, at least without some hints).
Anyway, to allow for future more complicated requirements, there are two common approaches to parsing arithmetic expressions: recursive descent or Dijkstra's shunting-yard algorithm. You can look these up, and if you only need the simple expressions in version 1.0 then you can use a simplified form of Dijkstra's algorithm. Then once you've parsed the expression, you need to evaluate it: use values that are linear expressions in x and interpret = as an operator with lowest possible precedence that means "subtract". The result is a linear expression in x that is equal to 0.
If you don't need complicated expressions then you can evaluate that simple example pretty much directly from left-to-right once you've tokenised it[*]:
x
x + 9
// set the "we've found minus sign" bit to negate the first thing that follows
x + 7 // and clear the negative bit
x + 3
2 * x + 3
// set the "we've found the equals sign" bit to negate everything that follows
3 * x + 3
3 * x - 2
3 * x - 1
3 * x - 4
4 * x - 4
Finally, solve a * x + b = 0 as x = - b/a.
[*] example tokenisation code, in Python:
acc = None
for idx, ch in enumerate(input):
if ch in '1234567890':
if acc is None: acc = 0
acc = 10 * acc + int(ch)
continue
if acc != None:
yield acc
acc = None
if ch in '+-=x':
yield ch
elif ch == ' ':
pass
else:
raise ValueError('illegal character "%s" at %d' % (ch, idx))
Alternative example tokenisation code, also in Python, assuming there will always be spaces between tokens as in the example. This leaves token validation to the parser:
return input.split()
ok some simple psuedo code that you could use to solve this problem
function(stinrgToParse){
arrayoftokens = stringToParse.match(RegexMatching);
foreach(arrayoftokens as token)
{
//now step through the tokens and determine what they are
//and store the neccesary information.
}
//Use the above information to do the arithmetic.
//count the number of times a variable appears positive and negative
//do the arithmetic.
//add up the numbers both positive and negative.
//return the result.
}
The first thing is to parse the string, to identify the various tokens (numbers, variables and operators), so that an expression tree can be formed by giving operator proper precedences.
Regular expressions can help, but that's not the only method (grammar parsers like boost::spirit are good too, and you can even run your own: its all a "find and recourse").
The tree can then be manipulated reducing the nodes executing those operation that deals with constants and by grouping variables related operations, executing them accordingly.
This goes on recursively until you remain with a variable related node and a constant node.
At the point the solution is calculated trivially.
They are basically the same principles that leads to the production of an interpreter or a compiler.
Consider:
from operator import add, sub
def ab(expr):
a, b, op = 0, 0, add
for t in expr.split():
if t == '+': op = add
elif t == '-': op = sub
elif t == 'x': a = op(a, 1)
else : b = op(b, int(t))
return a, b
Given an expression like 1 + x - 2 - x... this converts it to a canonical form ax+b and returns a pair of coefficients (a,b).
Now, let's obtain the coefficients from both parts of the equation:
le, ri = equation.split('=')
a1, b1 = ab(le)
a2, b2 = ab(ri)
and finally solve the trivial equation a1*x + b1 = a2*x + b2:
x = (b2 - b1) / (a1 - a2)
Of course, this only solves this particular example, without operator precedence or parentheses. To support the latter you'll need a parser, presumable a recursive descent one, which would be simper to code by hand.