"Translating" a strange pseudocode into python - pseudocode

I'm doing an assignment and in one of the questions, my professor put some strange pseudo code as a condition and frankly I'm not sure if I understood it correctly.
This is what he gave us:
LOOP if S>0 then {S:=S-1; exit} end_if;
END_LOOP
can I understand this as
while True:
if S>0:
S = S - 1
break
if I were to rewrite it in Python?
Or, should it be like this?
while S>0:
S = S -1
break

It's not 100% clear, but given that the first version will either go around once, or go around forever, it's likely to be the second one.

Related

I'm not sure how this works, never seen such an operator "= -"

I was reading someone's code and found out that he wrote the code (below following).
for example:
operandA = -operandA;
That works but I don't understand how this operator is working. Can anyone give any similar idea please?
In the program's logic, the given statement changes the movement of X (operandA) to reverse direction when it hits something.
I believe it is just setting operandA to the negative of operandA

Can a finite list be lazy in Perl 6?

Suppose I have a sequence where I know the start and end points and the generator is straightforward. Can I make it lazy?
my #b = 0 ... 3;
say 'Is #b lazy? ' ~ #b.is-lazy; # Not lazy
I'd like to combination that known list with itself an unknown number of times but not generate the entire list immediately. I want #cross to be lazy:
my #cross = [X] #b xx $n;
I know I can do this through other simple matters or programming (and my Perl 5 Set::CrossProduct does just that), but I'm curious if there is some simple and intended way that I'm missing. Some way that doesn't involve me counting on my own.
As a side question, what's the feature of a sequence that makes it lazy? Is it just the endpoint? Is there a sequence with a known endpoint that can still be lazy if the generator can make infinite values between? I wondered how much information I have to remove and tried something like this:
my $m = #*ARGS[0];
my #b = 0, * + $m ... ^ * > 3;
say 'Is #b lazy? ' ~ #b.is-lazy;
say '#b: ' ~ #b;
Still, this is not lazy.
The "is-lazy" method, in my opinion, is really a misnomer. The only thing it says, as cuonglm pointed out, is that just passes on that the underlying iterator claims to be lazy. But that still doesn't mean anything, really. An iterator can technically produce values on demand, but still claim it isn't lazy. And vice-versa.
The "is-lazy" check is used internally to prevent cases where the number of elements needs to be known in advance (like .roll or .pick): if the Seq / iterator claims to be lazy, it won't actually try, but fail or throw instead.
The only thing that .lazy does, is wrap the iterator of the Seq into another iterator that does claim to be lazy (if the given iterator claims it isn't lazy, of course). And make sure it won't pull any values unless really needed. So, adding .lazy doesn't tell anything about when values will be produced, only when they will be delivered. And it helps in testing iterator based logic to see how they would work with an iterator that claims to be lazy.
So, getting back to the question: if you want to be sure that something is lazy, you will have to write the iterator yourself. Having said that, the past months I've spent quite a lot of effort in making things as lazy as possible in the core. Notably xx N still isn't lazy, although it does produce a Seq nowadays. Making it lazy broke some spectests at some deep level I haven't been able to figure out just yet. Looking forward, I think you can be sure that things will be as lazy as makes sense generally, with maybe a possibility of indicating favouring memory over CPU. But you will never have complete control over builtins: if you want complete control, you will have to write it yourself.
Yes, you can, using lazy method:
> my #b = (0 ... 3).lazy;
[...]
> say 'Is #b lazy? ' ~ #b.is-lazy;
Is #b lazy? True
There's nothing special Seq that make it be lazy, just its underlying Iterator does.
As already pointed out, is-lazy does not really mean anything.
But I just wanted to mention that there is a page on rakudo wiki that gives a couple of clues on what you can expect from is-lazy.
You can make:
my #b = 0 ... 3;
lazy just by adding the lazy keyword in the right place, like this:
my #b = lazy 0 ... 3;
Or, as cuonglm pointed out, you can call the range's method, like this:
my #b = (0 ... 3).lazy;

Why won't finding polynomial whole number routes work?

So I want this to find me the roots of a polynomial. However, everytime I run it, it never gives me any roots, even if I use an obvious one like 2x-2. Why won't it work?
Input "Degree?",θ
Disp "Left to right"
Disp "coefficients"
1→V
For(Z,0,θ)
Input A
Q→R
P→Q
O→P
N→O
M→N
L→M
K→L
J→K
I→J
H→I
G→H
F→G
E→F
D→E
C→D
B→C
A→B
If V=1
Then
A→S
V=0
End
End
For(T,–A,A)
For(U,–W,W)
If T≠0
U/T→X
RX+Q→Y
YX+P→Z
ZX+O→Y
YX+N→Z
ZX+M→Y
YX+L→Z
ZX+K→Y
YX+J→Z
ZX+I→Y
YX+H→Z
ZX+G→Y
YX+F→Z
ZX+E→Y
YX+D→Z
ZX+C→Y
YX+B→Z
If Z=0
Then
Disp X
End
End
End
prgmRESET
RESET just resets the variable values. What is wrong with it?
Request: I have absolutely no idea what operation you are working off of, if you could please state that
Observation: You're using a lot of variables that haven't had any value assigned to them or initially cleared, I can see that you're trying to create a 'stream' of variables to work with, but if you do this without clearing the variables ahead of time then you create problems in your later calculations.
Coding Recommendations:
You state V=0, which does nothing in this context, instead of assigning it a value
You can change 'If T≠0' into just 'If T'
In your third 'For()' statement, "W" is undefined in the code.
You can change 'If Z=0:Then:Disp X:End', near the end of your code, into just 'If not(Z:Disp X'
Move prgmRESET to the top of your program
To be honest, I'm not entirely sure how you code is supposed to find the routes of a polynomial. Your error is most likely occurring somewhere in your mess of variable assigning/reassigning/swapping. I would redo your code using lists instead of basic variables.
If all you want to do is find the routes of a polynomial, I can give you a program for that.
:Prompt L1,X
:Repeat 1=dim(L1
:dim(L1->dim(L3
:seq(L1(A)(Ans-A),A,1,Ans-1->L2
:Repeat abs(Ans)<10^(-7
:L1(1->L3(1
:For(A,2,dim(L1
:XL3(A-1)+L1(A->L3(A
:End
:Ans->B
:L2(1->L3(1
:For(A,2,dim(L2
:XL3(A-1)+L2(A->L3(A
:End
:Ans^-1(AnsX-B->X
:B
:End
:Disp X
:L1(1->L2(1
:For(A,2,dim(L1)-1
:XL2(A-1)+L1(A->L2(A
:End
:L2->L1
:End
I'm not quite sure what you're trying to do here. You use a whole lot of variables without ever clearing or defining them, which probably means that all of your values will be 0.
Also, recommendation for future TI-BASIC questions:
PLEASE explain your variables. There's nothing worse than having a mess of variables and expecting the reader to do detective work to find out what they're supposed to do. Plus, it's helpful for you as well when you decide to come back to it for troubleshooting.

Why are else statements discouraged in Ruby?

I was looking for a Ruby code quality tool the other day, and I came across the pelusa gem, which looks interesting. One of the things it checks for is the number of else statements used in a given Ruby file.
My question is, why are these bad? I understand that if/else statements often add a great deal of complexity (and I get that the goal is to reduce code complexity) but how can a method that checks two cases be written without an else?
To recap, I have two questions:
1) Is there a reason other than reducing code complexity that else statements could be avoided?
2) Here's a sample method from the app I'm working on that uses an else statement. How would you write this without one? The only option I could think of would be a ternary statement, but there's enough logic in here that I think a ternary statement would actually be more complex and harder to read.
def deliver_email_verification_instructions
if Rails.env.test? || Rails.env.development?
deliver_email_verification_instructions!
else
delay.deliver_email_verification_instructions!
end
end
If you wrote this with a ternary operator, it would be:
def deliver_email_verification_instructions
(Rails.env.test? || Rails.env.development?) ? deliver_email_verification_instructions! : delay.deliver_email_verification_instructions!
end
Is that right? If so, isn't that way harder to read? Doesn't an else statement help break this up? Is there another, better, else-less way to write this that I'm not thinking of?
I guess I'm looking for stylistic considerations here.
Let me begin by saying that there isn't really anything wrong with your code, and generally you should be aware that whatever a code quality tool tells you might be complete nonsense, because it lacks the context to evaluate what you are actually doing.
But back to the code. If there was a class that had exactly one method where the snippet
if Rails.env.test? || Rails.env.development?
# Do stuff
else
# Do other stuff
end
occurred, that would be completely fine (there are always different approaches to a given thing, but you need not worry about that, even if programmers will hate you for not arguing with them about it :D).
Now comes the tricky part. People are lazy as hell, and thusly code snippets like the one above are easy targets for copy/paste coding (this is why people will argue that one should avoid them in the first place, because if you expand a class later you are more likely to just copy and paste stuff than to actually refactor it).
Let's look at your code snippet as an example. I'm basically proposing the same thing as #Mik_Die, however his example is equally prone to be copy/pasted as yours. Therefore, would should be done (IMO) is this:
class Foo
def initialize
#target = (Rails.env.test? || Rails.env.development?) ? self : delay
end
def deliver_email_verification_instructions
#target.deliver_email_verification_instructions!
end
end
This might not be applicable to your app as is, but I hope you get the idea, which is: Don't repeat yourself. Ever. Every time you repeat yourself, not only are you making your code less maintainable, but as a result also more prone to errors in the future, because one or even 99/100 occurrences of whatever you've copied and pasted might be changed, but the one remaining occurrence is what causes the #disasterOfEpicProportions in the end :)
Another point that I've forgotten was brought up by #RayToal (thanks :), which is that if/else constructs are often used in combination with boolean input parameters, resulting in constructs such as this one (actual code from a project I have to maintain):
class String
def uc(only_first=false)
if only_first
capitalize
else
upcase
end
end
end
Let us ignore the obvious method naming and monkey patching issues here, and focus on the if/else construct, which is used to give the uc method two different behaviors depending on the parameter only_first. Such code is a violation of the Single Responsibility Principle, because your method is doing more than one thing, which is why you should've written two methods in the first place.
def deliver_email_verification_instructions
subj = (Rails.env.test? || Rails.env.development?) ? self : delay
subj.deliver_email_verification_instructions!
end

What are the pros and cons of putting as much logic as possible in a minimum(one-liners) piece of code?

Is it cool?
IMO one-liners reduces the readability and makes debugging/understanding more difficult.
Maximize understandability of the code.
Sometimes that means putting (simple, easily understood) expressions on one line in order to get more code in a given amount of screen real-estate (i.e. the source code editor).
Other times that means taking small steps to make it obvious what the code means.
One-liners should be a side-effect, not a goal (nor something to be avoided).
If there is a simple way of expressing something in a single line of code, that's great. If it's just a case of stuffing in lots of expressions into a single line, that's not so good.
To explain what I mean - LINQ allows you to express quite complicated transformations in relative simplicity. That's great - but I wouldn't try to fit a huge LINQ expression onto a single line. For instance:
var query = from person in employees
where person.Salary > 10000m
orderby person.Name
select new { person.Name, person.Deparment };
is more readable than:
var query = from person in employees where person.Salary > 10000m orderby person.Name select new { person.Name, person.Deparment };
It's also more readabe than doing all the filtering, ordering and projection manually. It's a nice sweet-spot.
Trying to be "clever" is rarely a good idea - but if you can express something simply and concisely, that's good.
One-liners, when used properly, transmit your intent clearly and make the structure of your code easier to grasp.
A python example is list comprehensions:
new_lst = [i for i in lst if some_condition]
instead of:
new_lst = []
for i in lst:
if some_condition:
new_lst.append(i)
This is a commonly used idiom that makes your code much more readable and compact. So, the best of both worlds can be achieved in certain cases.
This is by definition subjective, and due to the vagueness of the question, you'll likely get answers all over the map. Are you referring to a single physical line or logical line? EG, are you talking about:
int x = BigHonkinClassName.GetInstance().MyObjectProperty.PropertyX.IntValue.This.That.TheOther;
or
int x = BigHonkinClassName.GetInstance().
MyObjectProperty.PropertyX.IntValue.
This.That.TheOther;
One-liners, to me, are a matter of "what feels right." In the case above, I'd probably break that into both physical and logic lines, getting the instance of BigHonkinClassName, then pulling the full path to .TheOther. But that's just me. Other people will disagree. (And there's room for that. Like I said, subjective.)
Regarding readability, bear in mind that, for many languages, even "one-liners" can be broken out into multiple lines. If you have a long set of conditions for the conditional ternary operator (? :), for example, it might behoove you to break it into multiple physical lines for readability:
int x = (/* some long condition */) ?
/* some long method/property name returning an int */ :
/* some long method/property name returning an int */ ;
At the end of the day, the answer is always: "It depends." Some frameworks (such as many DAL generators, EG SubSonic) almost require obscenely long one-liners to get any real work done. Othertimes, breaking that into multiple lines is quite preferable.
Given concrete examples, the community can provide better, more practical advice.
In general, I definitely don't think you should ever "squeeze" a bunch of code onto a single physical line. That doesn't just hurt legibility, it smacks of someone who has outright disdain for the maintenance programmer. As I used to teach my students: always code for the maintenance programmer, because it will often be you.
:)
Oneliners can be useful in some situations
int value = bool ? 1 : 0;
But for the most part they make the code harder to follow. I think you only should put things on one line when it is easy to follow, the intent is clear, and it won't affect debugging.
One-liners should be treated on a case-by-case basis. Sometimes it can really hurt readability and a more verbose (read: easy-to-follow) version should be used.
There are times, however when a one-liner seems more natural. Take the following:
int Total = (Something ? 1 : 2)
+ (SomethingElse ? (AnotherThing ? x : y) : z);
Or the equivalent (slightly less readable?):
int Total = Something ? 1 : 2;
Total += SomethingElse ? (AnotherThing ? x : y) : z;
IMHO, I would prefer either of the above to the following:
int Total;
if (Something)
Total = 1;
else
Total = 2;
if (SomethingElse)
if (AnotherThing)
Total += x;
else
Total += y;
else
Total += z
With the nested if-statements, I have a harder time figuring out the final result without tracing through it. The one-liner feels more like the math formula it was intended to be, and consequently easier to follow.
As far as the cool factor, there is a certain feeling of accomplishment / show-off factor in "Look Ma, I wrote a whole program in one line!". But I wouldn't use it in any context other than playing around; I certainly wouldn't want to have to go back and debug it!
Ultimately, with real (production) projects, whatever makes it easiest to understand is best. Because there will come a time that you or someone else will be looking at the code again. What they say is true: time is precious.
That's true in most cases, but in some cases where one-liners are common idioms, then it's acceptable. ? : might be an example. Closure might be another one.
No, it is annoying.
One liners can be more readable and they can be less readable. You'll have to judge from case to case.
And, of course, on the prompt one-liners rule.
VASTLY more important is developing and sticking to a consistent style.
You'll find bugs MUCH faster, be better able to share code with others, and even code faster if you merely develop and stick to a pattern.
One aspect of this is to make a decision on one-liners. Here's one example from my shop (I run a small coding department) - how we handle IFs:
Ifs shall never be all on one line if they overflow the visible line length, including any indentation.
Thou shalt never have else clauses on the same line as the if even if it comports with the line-length rule.
Develop your own style and STICK WITH IT (or, refactor all code in the same project if you change style).
.
The main drawback of "one liners" in my opinion is that it makes it hard to break on the code and debug. For example, pretend you have the following code:
a().b().c(d() + e())
If this isn't working, its hard to inspect the intermediate values. However, it's trivial to break with gdb (or whatever other tool you may be using) in the following, and check each individual variable and see precisely what is failing:
A = a();
B = A.b();
D = d();
E = e(); // here i can query A B D and E
B.C(d + e);
One rule of thumb is if you can express the concept of the one line in plain language in a very short sentence. "If it's true, set it to this, otherwise set it to that"
For a code construct where the ultimate objective of the entire structure is to decide what value to set a single variable, With appropriate formatting, it is almost always clearer to put multiple conditonals into a single statement. With multiple nested if end if elses, the overall objective, to set the variable...
" variableName = "
must be repeated in every nested clause, and the eye must read all of them to see this.. with a singlr statement, it is much clearer, and with the appropriate formatting, the complexity is more easily managed as well...
decimal cost =
usePriority? PriorityRate * weight:
useAirFreight? AirRate * weight:
crossMultRegions? MultRegionRate:
SingleRegionRate;
The prose is an easily understood one liner that works.
The cons is the concatenation of obfuscated gibberish on one line.
Generally, I'd call it a bad idea (although I do it myself on occasion) -- it strikes me as something that's done more to impress on how clever someone is than it is to make good code. "Clever tricks" of that sort are generally very bad.
That said, I personally aim to have one "idea" per line of code; if this burst of logic is easily encapsulated in a single thought, then go ahead. If you have to stop and puzzle it out a bit, best to break it up.

Resources