An alternative to Multiple Combinational Conditions in Python - memory-management

Is there an efficient and faster way in dealing with Multiple Combinational Conditions such as this:
if(condition1 and condition2):
statements
elif((condition1 or condition2) and not condition3):
statements
elif((condition3 and condition2) and not condition1):
statements
elif(condition1 or condition2):
statements
else:
statements
my colleagues said that I should implement a switch case (dict), but I'm not sure how to implement the multiple combined conditions.
Thank You in Advance.

Related

Lucene simulation for ElasticSearch queries - the NOT clause

I'm building a pure lucene-based implementation for legacy system that should locally (in-process) run arbitrary (more or less) queries. I receive queries in textual form, like term1:A OR term2:B. My default operator for queries is AND. For compatibility reasons I'm using lucene 5.5. I'm basing the solution on MemoryIndex single-document implementation.
My main problem is with how lucene deals with NOT clause: in query of sort
termA:(NOT 0) term2:(xxx) lucene would produce the following query:
+(-termA:0) +term2:xxx. While logically pretty sound, in practice this query shall always produce nothing since the negate-only clause always returns no_docs response and AND with it shall always produce empty result. The only workaround that I found (here on SOF) for this is to inject a MatchAllDocs clause together with the negative clause, like termA:(*:* NOT 0), but this is an error prone approach since it involves intricate clause parsing - the MatchAllDocs should only be injected if there are no positive clauses inside the parenthesis.
I'm looking for a more robust/generic approach to this problem, preferable some library that can parse/handle it for me, maybe something in contrib or similar.

What is the difference between write and respond in prolog

Based on the code I've got, there is no explicit difference between those two procedures. I can use both of them to print things I want to.

How to keep only one return statement in a function?

Despite the discussion here, Should a function have only one return statement?, are there some simple tips or method to keep only one return statement? Or how to refactor a multiple return statement to a only one return statement?
First of all it is not clear why you want to do this as in the thread it is already mentioned that this feature was added in modern languages due to some reasons and to allow the user to get more functionality.
The wiki says a lot on it:
Some people make sure each function has a single entry, single exit
(SESE). These people argue that The use of a return statement violates
structured programming: it is an unstructured exit from the function,
resulting in multiple exit points, rather than the single exit point
required by structured programming. It has thus been argued[5] that
one should eschew the use of the explicit return statement except at
the textual end of a subroutine, considering that, when it is used to
"return early", it may suffer from the same sort of problems that
arise for the GOTO statement. Conversely, it can be argued that using
the return statement is worthwhile when the alternative is more
convoluted code, such as deeper nesting, harming readability.
Other people say that one or more "guard clauses" -- conditional
"early exit" return statements near the beginning of a function --
often make a function easier to read than the alternative.[6][7][8][9]
The most common problem in early exit is that cleanup or final
statements are not executed – for example, allocated memory is not
unallocated, or open files are not closed, causing leaks. These must
be done at each return site, which is brittle and can easily result in
bugs. For instance, in later development, a return statement could be
overlooked by a developer, and an action which should be performed at
the end of a subroutine (e.g., a trace statement) might not be
performed in all cases. Languages without a return statement, such as
standard Pascal don't have this problem. Some languages, such as C++
and Python, employ concepts which allow actions to be performed
automatically upon return (or exception throw) which mitigates some of
these issues – these are often known as "try/finally" or similar.
Ironically, functionality like these "finally" clauses can be
implemented by a goto to the single return point of the subroutine. An
alternative solution is to use the normal stack unwinding (variable
deallocation) at function exit to unallocate resources, such as via
destructors on local variables, or similar mechanisms such as Python's
"with" statement.
But even then if you want to achieve the Single entry and Single exit functionality then the best way to do is to get invalid cases out of the way first, either simply exiting or raising exceptions as appropriate, put a blank line in there, then add the "real" body of the method.
Also check Where did the notion of “one return only” come from?

Is LINQ faster or just more convenient?

Which of theses scenarios would be faster?
Scenario 1:
foreach (var file in directory.GetFiles())
{
if (file.Extension.ToLower() != ".txt" &&
file.Extension.ToLower() != ".bin")
continue;
// Do something cool.
}
Scenario 2:
var files = from file in directory.GetFiles()
where file.Extension.ToLower() == ".txt" ||
file.Extension.ToLower() == ".bin"
select file;
foreach (var file in files)
{
// Do something cool.
}
I know that they are logically the same because of delayed execution, but which would be the faster? And why?
Faster isn't usually the issue per se, especially in a scenario like this where there is not going to be a meaningful performance difference (and in general, if the code is not a bottleneck it just doesn't matter). The issue is which is more readable and more clearly expresses the intent of the code.
I think the second block of code more clearly expresses the intent of the code. It reads as "query a collection of file names for some file names with a certain property" and then "for each of those file names with that property, do something." It declares what is happening, rather than how it is going to happen. Separating the what from the mechanism is what makes the second block of code clearer and where LINQ really shines. Use LINQ to declare the what, and let LINQ implement the mechanism instead of in the past where the what would be muddled with the mechanism.
Is LINQ faster or just more convenient?
So, to answer the question in your title, LINQ usually does not materially hinder performance but it makes code more clear by allowing the coder to declare what they want done instead of having to focus on how they want something done. At the end of the day, we don't care about the how, we care about the what.
I know that they are logically the same because of delayed execution, but which would be the faster?
Probably the imperative version because there is a tiny amount of overhead in using LINQ. But if you really must know which is faster be sure to use a profiler, and be sure to test on real-world data.
And why?
Because LINQ adds a little bit of overhead. But the trade off is significantly clearer and more maintainable code. That is a huge win compared to the usually irrelevant performance loss.
It would be faster to do a GetFiles("*.txt") and GetFile("*.bin") if the directory contains lots of files or is on a network drive.
Compared to that the extra overhead for LINQ is just noise.
Linq isn't faster and it's not really about convenience. Rather, Linq pulls the higher-order functions Fold, Map, and Filter into .NET (with different names). These functions are valuable because they allow us to DRY-up our code. Every time you set up an iteration with a secondary collection or result, you open yourself up to a bug. Linq allows you to focus on what happens inside the iteration and feel fairly confident that the iteration mechanics are bug-free.
This doesn't mean that Linq is strictly slower than manual iteration. As others have mentioned, you'll have to benchmark case-by-case.
I wrote an article on Code Project that benchmarked linq and Stored procedures as well as using compiled linq.
Please take a look.
http://www.codeproject.com/KB/cs/linqsql2.aspx
I understand you are looking at local file parsing, the article will give you some idea of what is involved and what linq is doing behind the scenes.

Should 'if' statement always have an 'else' clause? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This may be a religious argument, but it has been debated ad-nauseum here at my work whether all IF statements should include an ELSE clause - even if the ELSE clause only contains a comment stating that it was 'intentionally left blank'.
I have heard arguments for both sides:
The 'For' camp - ensures that the code has actually addressed whether the condition requires an ELSE clause
The 'Against' camp - code is harder to read, adds too much noise
I am interested in any other points of view as I have to resolve this debate with an answer that would satisfy both parties.
Seems like useless typing to me... and a possible cause for confusion. If you don't need it, don't put it!
No. If you don't need to run any code on the else side, you don't need an else clause.
It is clear by the responses here that no one feels an unused else is needed. I have never heard nor read of such a thing. The more important issue before you is dealing with co-workers/developers who somehow believe adamantly that this is how If Then is to be used.
It sounds like you are not the senior person in this scenario so you cannot simply decree it to be so. I suggest asking the "empty else" parties to show where such a process is suggested in a book (blogs don't count) about development. Better yet, in 3 books about development. I have read my share of programming books across programming languages since 1982 and I have never seen such a suggestion.
This way you are not telling them that they are wrong which they could take personally. Instead you are willing to accept such a position but would like to see some documentation. The onus is on them to find the proof. Either they find it or they are left to argue that every programming book ever written is wrong while only they are right.
Good luck.
The golden rule: put it in if it makes your code clearer and easier to understand, and leave it out otherwise. An experienced programmer will be able to make these judgements on a case-by-case basis.
Are you talking about Algol-derived languages?
In Lisp, I'd say yes: every IF should have an else-clause. Otherwise, you should be using WHEN.
As you say, this may be a question of style, but I would not dream of putting in empty else-blocks in my code just because "every if-block should have one". In my opinion, it adds nothing else than some more characters in the code and one more point (of very little value) to spend time on during code reviews.
Requiring an else stinks. Use it when needed. All programmers understand the construct and the implication of a missing else. It's like a pointless comment that echoes the code. It's plain daft IMO.
I tend to use "early if" statements as means of reducing the level of nested braces (or indentation in Python) like so:
if (inParam == null) {
return;
}
if (inParam.Value < 0) {
throw new ArgumentException(...,...);
}
// Else ... from here on my if statements are simpler since I got here.
Of course, .Net 4.0 now has code contracts, which is great! But, most languages do not have that just yet, so "early ifs" (for the lack of better term) are great precisely because they eliminate a number of else clauses and nested ifs. I do not think it is beneficial to have an else clause in high-level languages ... heck, even in assembly! The idea is: if you checked and did not jump, then the condition was false and we can carry on. Makes logical sense to me ...
EDIT: Check out this article as well to see why else clauses are not of much help:
http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html
"ensures that the codes has actually
addressed whether the condition
requires an ELSE clause"
This is no more true than requiring a catch clause in every method ensures that all possible exceptions has been properly handled.
No. Guard conditions are a great example. You could nest the rest of the method logic in else clauses but it could get ugly really quickly.
Having an "else" with just an empty line of a code comment can usually mean the developer thought-through the condition and has a better idea of what execution path is actually taken at a given time. All recent compilers will remove the "else" and the comment, so you are not slowing software execution.
Unless I am reading the other responses incorrectly, it looks like most folks are objecting to the time it takes to declare their thoughts in the code and would rather just do it.
SQL Server 2000, 2005 at least.
IF 1 = 1
BEGIN
PRINT 'doing something productive'
END
ELSE
BEGIN
--Just sitting here
END
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'END'.
You have to have a meaningful statement, which means a dummy assign or return data to client. I suppose I could use WAITFOR DELAY...
Haskell's if is always ternary. So else is mandatory.
if (thereIsSomeThingToDoInTheElse)
{
putAnElseClause();
}
else
{
// intentionally left blank
}
If your code is complex enough that this becomes an issue, you should probably be rethinking your approach to the problem. Break what you're doing down into smaller simpler functions where it should be unbelievably obvious what the if statements are doing.
If you can't break it down into smaller functions, or you find yourself nesting more than one if statement inside another, Using if statements for your conditional logic are probably not a good fit. Consider switches, lookup tables (if the only difference between your conditions is the value of some constant), or decision tables instead.
If you've already done all this, then you are quibbling over something so unbelievably trivial it's hardly worth your time to argue it.
One of the few possible situations where this might be a good idea is where you have several nested if statements, but fewer else clauses. The language will specify which if the else matches, but this may not always be clear to the reader. Of course, where you put content in curly brackets, nesting will be obvious, so there's no ambiguity. This make this a bit of an artificial case, but still possibly worth mentioning. Also, if your code is this complicated, there's probably a clearer way of writing it.
There are situations where using an optional syntax element when not required can improve readability or prevent future errors. A typical case are the brackets around one-sentence conditionals:
Doing
if(foo){
bar
}
instead of
if(foo)
bar
could eventually prevent
if(foo)
bar
dot
I can't really think of any language I know where omitting an unnecessary else can lead to potential errors :-?
there are a lot of "words" telling you the way to programming such as DRY
in this case i'd use YAGNI.. you aint gonna need it..
so following this you shouldn't write the else.
anyhow in my opinion it makes it harder to read and understand the code.. the more you write the harder to understand the code is
edit:
here are the links you requested:
http://en.wikipedia.org/wiki/YAGNI
http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

Resources