Any practical differences in between "==" vs "in" or "if in" when checking string index? - python-3.8

Are there any practical differences between examples below and is better use one than others?
s = 'this#mail.is'
for i in range(len(email)):
print('#' in email[i])
#vs
for i in range(len(email)):
print(email[i] == '#')
#or
if '#' in email:

There is no practical difference... for your example here...
In essence, (as explained here and here), with in, python calls the underlying __contains__ function.
Thus, in your example. It makes no difference.
On the other hand, one could create a module and define a differente behavior for the __contains__ function.
I guess this would be done more for of an academic purpose, but it could still be made.

in checks for substrings
"a" in "apple" > True
== checks if it is exactly the same
b=10;
if(b==10)

Related

Is it acceptable to use `to` to create a `Pair`?

to is an infix function within the standard library. It can be used to create Pairs concisely:
0 to "hero"
in comparison with:
Pair(0, "hero")
Typically, it is used to initialize Maps concisely:
mapOf(0 to "hero", 1 to "one", 2 to "two")
However, there are other situations in which one needs to create a Pair. For instance:
"to be or not" to "be"
(0..10).map { it to it * it }
Is it acceptable, stylistically, to (ab)use to in this manner?
Just because some language features are provided does not mean they are better over certain things. A Pair can be used instead of to and vice versa. What becomes a real issue is that, does your code still remain simple, would it require some reader to read the previous story to understand the current one? In your last map example, it does not give a hint of what it's doing. Imagine someone reading { it to it * it}, they would be most likely confused. I would say this is an abuse.
to infix offer a nice syntactical sugar, IMHO it should be used in conjunction with a nicely named variable that tells the reader what this something to something is. For example:
val heroPair = Ironman to Spiderman //including a 'pair' in the variable name tells the story what 'to' is doing.
Or you could use scoping functions
(Ironman to Spiderman).let { heroPair -> }
I don't think there's an authoritative answer to this.  The only examples in the Kotlin docs are for creating simple constant maps with mapOf(), but there's no hint that to shouldn't be used elsewhere.
So it'll come down to a matter of personal taste…
For me, I'd be happy to use it anywhere it represents a mapping of some kind, so in a map{…} expression would seem clear to me, just as much as in a mapOf(…) list.  Though (as mentioned elsewhere) it's not often used in complex expressions, so I might use parentheses to keep the precedence clear, and/or simplify the expression so they're not needed.
Where it doesn't indicate a mapping, I'd be much more hesitant to use it.  For example, if you have a method that returns two values, it'd probably be clearer to use an explicit Pair.  (Though in that case, it'd be clearer still to define a simple data class for the return value.)
You asked for personal perspective so here is mine.
I found this syntax is a huge win for simple code, especial in reading code. Reading code with parenthesis, a lot of them, caused mental stress, imagine you have to review/read thousand lines of code a day ;(

keyword - FFL: Where vs. Let

I was trying to understand the following code:
def() ->commands
if(deferred_passive_abilities != [],
let [{ability: class passive_ability, creature: class creature}] items = [];
let found = false;
map(deferred_passive_abilities,
if(cmd = null, add(items, [value]), [cmd, set(found, true)])
where cmd = value.ability.static_effect(me, value.creature));
if(found,
set(deferred_passive_abilities, items);
evaluate_deferred_passive_abilities(),
set(deferred_passive_abilities, []))
)
Haskell appears to have both let and where, but I didn't learn much by a superficial reading of their haskell docs. They also have a let...in, which I didn't understand but it would be good to know if FFL has that.
So, what is the significance of using let versus where? Was it necessary to use let here? (Also, possibly another question: why does it need those semicolons?)
Using let introduces a variable that can be modified. Note how found and items are modified. By contrast, where always introduces immutable symbols.
Semi-colons are used in FFL to create a command pipeline. Normally in FFL, an entire formula is evaluated, resulting in a command or list of commands, and then the commands are executed.
When a semi-colon is present, everything before the semi-colon is treated as an entirely separate formula to everything after the semi-colon. The first formula is evaluated and executed and then the second formula is evaluated and executed.
Semi-colons effectively allow a much more procedural programming style in FFL, without semi-colons it is a purely functional language.
Never knew of let in FFL before this, must be very rare.
Regardless of the insights, the semicolon has to be absolutely necessary, in order to force execution before using the bound variable. In other words, until used the semicolon, the variable does not exist. Does not have a bound value.
This is a big difference to where, which doesn't need of semicolons.
Given the semicolon is not a construction for complete beginners, I could somewhat recommend beginners about variables to stick in where until understanding the trickery of the semicolons.

Why not have operators as both keywords and functions?

I saw this question and it got me wondering.
Ignoring the fact that pretty much all languages have to be backwards compatible, is there any reason we cannot use operators as both keywords and functions, depending on if it's immediately followed by a parenthesis? Would it make the grammar harder?
I'm thinking mostly of python, but also C-like languages.
Perl does something very similar to this, and the results are sometimes surprising. You'll find warnings about this in many Perl texts; for example, this one comes from the standard distributed Perl documentation (man perlfunc):
Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It looks like a function, therefore it is a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful:
print 1+2+4; # Prints 7.
print(1+2) + 4; # Prints 3.
print (1+2)+4; # Also prints 3!
print +(1+2)+4; # Prints 7.
print ((1+2)+4); # Prints 7.
An even more surprising case, which often bites newcomers:
print
(a % 7 == 0 || a % 7 == 1) ? "good" : "bad";
will print 0 or 1.
In short, it depends on your theory of parsing. Many people believe that parsing should be precise and predictable, even when that results in surprising parses (as in the Python example in the linked question, or even more famously, C++'s most vexing parse). Others lean towards Perl's "Do What I Mean" philosophy, even though the result -- as above -- is sometimes rather different from what the programmer actually meant.
C, C++ and Python all tend towards the "precise and predictable" philosophy, and they are unlikely to change now.
Depending on the language, not() is not defined. If not() is not defined in some language, you can not use it. Why not() is not defined in some language? Because creator of that language probably had not need this type of language construction. Because it is better to let things be simpler.

What is your preferred boolean pair: 1/0 Yes/No True/False?

When dealing with MySQL, I typically use the BOOLEAN type, which is equivalent to TINYINT(1), or 1/0
In most languages I work with, true/false is preferred
When displaying forms, sometimes "Yes / No" makes more sense
enum Bool
{
True,
False,
FileNotFound
};
http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
In code: true/false.
In the UI: Yes/No or OK/Cancel
true and false makes a lot more sense to me, in code - partly through familiarity, I'm sure. I suspect I'd get used to yes and no pretty quickly. 1 and 0 really doesn't work for me though.
Consider the expression
age == 5
It's a test for truth-hood. Is the value of age 5? Yes, it's true. Both "yes" and "no" would be fine for me, but the idea that the answer to the question "Is the value of age 5?" is "1" seems pretty counter-intuitive to me. Just because that's the typical binary representation of truth-hood doesn't mean it's a useful one at a higher abstraction.
Which is easier to read?
while(true) {}
while(yes) {}
while(1) {}
I'll stick with true for most cases.
Here are rules I live by...
Rule #1
Use well defined constants in the programming languages that you use to communicate with the CPU, i.e., true/false in most modern cases for boolean values. If a database offers a boolean type or some such equivalent, of course it should be used.
Rule #2
Interact with users of your software by using their preferred language and idiom, i.e., Yes/No questions should offer Yes/No (or perhaps an alternative to No, such as Cancel).
Rule #3
Uncertainty should be expressed in terms of scope, i.e., "that depends", which will be followed up by the question "on what?". I know developers who answer the question by copying and pasting just about every dependency they may need into every code file of a project as a 'using' statement. That's just sloppy, and please bother to alphabetize or at least group namespaces together.
When a bool Just Isn't Enough
Incidentally, an interesting twist to this, available in C#, is Nullable;
The you can write
Nullable<bool> RespondToIritatingQuestion()
{
return new Nullable<bool>();
}
OR
bool? RespondToIritatingQuestionWithSytle()
{
return new bool?();
}
and the questioner would need to evaluate your response before even knowing what the answer, if there is one, might be...
bool? answer = RespondToIritatingQuestionWithStyle();
if (answer.HasValue)
Trace.WriteLine("The bloke responded with " + answer.Value.ToString());
else
Trace.WriteLine("The bloke responded with 'depends'.");
1 or 0 for SQL. SQL has a boolean type for a reason. Also, in very large databases, it can effect performance.
I use booleans for true/false fields in databases. Some people use ENUM('true', 'false'), but thats not my preference. For programming languages, I always use true/false, even if setting it to 0 or 1 will work. And if the form requires 'yes'/'no', I still use booleans to represent the values, but display them as strings that are more logical.

What advantages are there to using either AND or &&?

Currently, I'm using && and || instead of AND and OR because that's how I was taught. In most languages, however, both are valid syntax. Are there any advantages to one or the other in any language?
I did try to search for this question, but it's a bit hard. It doesn't interpret my input correctly.
You ask “Are there any advantages to one or the other in any language?” This is, of course, dependent on the programming language.
Languages that implement both and and && (and correspondingly or and ||) will do it one of two ways:
Both behave exactly the same way. In which case, there is no advantage provided by the language in using one over the other.
Each behaves differently. In which case, the advantage is that you can get different behaviour by using one or the other.
That all sounds a bit facetious, but it's really as specific as one can get without talking about a specific language. Your question explicitly wants to know about all languages, but it's a question that needs to be answered per language.
Perl has all four of {&& || and or} but they differ in their precedence. "and" and "or" have really low precedence so you can do things like "complex-function-call-here or die $!" and you won't accidentally have "or" slurp up something on its left side that you didn't want it to.
it depends on the language, but on PHP, I'd be careful about using && versus "and". The ones i often use are "&&" and "||"
http://us3.php.net/manual/en/language.operators.logical.php
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
In some languages && will have a higher operator precedence than AND.
If both works fine, then I would say it's really personal preference, in most cases, they are compiled into same binary code like this : 11100010001000101001001010 [not real code, just an example].
&& = two keystrokes of the same key.
AND = three keystrokes of different keys.
I'm not sure what language you are using, but some languages differentiate between a normal boolean operator and a short-circuit operator. For example, the following are normal boolean operators in MATLAB:
C = or(A,B);
C = A | B; % Exactly the same as above
However, this is a short-circuit operator:
C = A || B;
The short-circuit syntax will evaluate the first argument and then, depending on the value, will potentially skip over evaluating the second argument. For example, if A is already true, B doesn't have to be evaluated for an OR operation, since the result is guaranteed to be true. This is helpful when B is replaced with a logical operation that involves some kind of expensive computation.
Here's a wikipedia link discussing short-circuit operators and their syntax for a few languages.
Unless there aren't any precedence issues, I'd say there are differences in readability. Consider the following:
if (&x == &y && &y == &z) {
// ..
}
#define AND &&
if (&x == &y AND &y == &z) {
// ..
}