I know python doesn't allow assignments statements to be used in expressions,
but does it apply for recursive functions.
C code:
if (ret = recursive_function("asdf")) return ret;
Python3
ret = recursive_function("asdf")
if ret:
return ret
Are those 2 codes equivalent? If not how to rewrite it to Python3
Another example. Will it work in Python3?
if recursive_function("asdf"):
#sth
Thanks
In a sufficiently-typed application, yes, these are equivalent.
However, it appears that you're using this in the looser, C-based sense: you test whether the return value happens to evaluate to True or False. These do not align perfectly between C++ and Python. There are many similarities (for similar reasons), but you need to check before you depend on the value.
Better yet, make a specific check on the return value. What is the "false" response you anticipate from the function? For instance, you might want to use
ret = recursive_function("asdf")
if ret is not null:
return ret
Does that get you moving forward?
Related
The following code has to check for an 'e' value such that the gcd(h,e)=1. Where 1
module great(p,q,e,d);
input p,q;
output e,d;
reg e,d;
h=((p-1)*(q-1));
always
begin
for(e=2;e<h;e=e+1)
begin
g1=gcd(h,e);
if(g1==1)
return e;
If, by "return a value", you mean spit out a value you can use in another module, you would use the output of this module as your "return" value. But even ignoring the return e, I don't think your code will work if you tried to run it, because it is too much like a programming language. There's several major things wrong:
You already declared output e,d so you can't declare two reg with the same name. You probably want output reg e,d instead.
You didn't declare a type for h or g1.
You have a for loop for e but e can never be anything other than 0 or 1 because you didn't set a size for it, so by default it is only 1-bit long. Even if it was big enough that you could increment it past 1, it's a wire type by default, and you can't make those kind of increments to a wire directly.
I assume gcd is some module you made somewhere else, but this isn't how you interconnect modules together. You can't call it like it's a function. You have to use wire and reg to connect the inputs and outputs of two modules together, almost like you're plugging components in.
Those are what stick out the most to me, anyway. I think you are coding your Verilog as if it were Python and that's what's causing these misunderstandings. Verilog is very, very different.
Is it possible to construct a python if-then statement where the equality depends on both a variable and a string?
For example, the possible values might be "4","4A", or "4B". But I am running over a loop from 4-12 (so I might have 5A, 6, 7B, etc.; always an integer 4-12, and there may or may not be a string afterward).
I attempted:
B_steps=np.zeros(8)
A_steps=np.zeros(8)
No_steps=np.zeros(8)
for i in range(0,9,1):
if data[i]=="i+4""A":
A_steps[i]=A_steps[i]+1
elif data[i]=="i+4B":
B_steps[i]=B_steps[i]+1
else:
No_Steps[i]=No_steps[i]+1
But this does not work; my syntax is improper to identify both a variable (i+4) and a possible letter. Can someone advise what the proper syntax is to have both a variable and a string in an if/then statement?
For this scenario (and why your syntax is improper), variable i is of type int,
while you put it in a string as part of a string literal.
Try if data[i] == "%sA" % (i + 4) instead.
Also the code you posted here is not indented correctly, albeit it could be caused by copy-pasting.
Apart from that, if you're not similar with the language itself and conventions in python, or some basic programming concepts, help yourself with the Python Documentation. I would recommend Chapters of "Tutorial", "Library Reference" and "Python HOWTOS".
For more complex scenarios, you might try using regular expressions with re from python standard library like:
for i in range(0, 9, 1):
if re.match(pattern_A, data[i]):
...
...
I'm hoping to perform the following steps in a single IF statement to save on code writing:
If ret is TRUE, set ret to the result of function lookup(). If ret is now FALSE, print error message.
The code I've written to do this is as follows:
BOOLEAN ret = TRUE;
// ... functions assigning to `ret`
if ( ret && !(ret = lookup()) )
{
fprintf(stderr, "Error in lookup()\n");
}
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement. As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time, failing immediately when evaluating an operand to false rather than evaluating them all. If so, then I expect the code to follow the steps I wrote above.
I've used assignments in IF statements a lot and I know they work, but not with another read beforehand.
Is there any reason why this isn't good code? Personally, I think it's easy to read and the meaning is clear, I'm just concerned about the compiler maybe not producing the equivalent logic for whatever reason. Perhaps compiler vendor disparities, optimisations or platform dependencies could be an issue, though I doubt this.
...to save on code writing This is almost never a valid argument. Don't do this. Particularly, don't obfuscate your code into a buggy, unreadable mess to "save typing". That is very bad programming.
I've got a feeling that this isn't as simple as it looks. Reading from, assigning to and reading again from the same variable in an IF statement.
Correct. It has little to do with the if statement in itself though, and everything to do with the operators involved.
As far as I'm aware, the compiler will always split statements like this up into their constituent operations according to precedence and evaluates conjuncts one at a time
Well, yes... but there is operator precedence and there is order of evaluation of subexpressions, they are different things. To make things even more complicated, there are sequence points.
If you don't know the difference between operator precedence and order of evaluation, or if you don't know what sequence points are, you need to instantly stop stuffing as many operators as you can into a single line, because in that case, you are going to write horrible bugs all over the place.
In your specific case, you get away with the bad programming just because as a special case, there happens to be a sequence point between the left and right evaluation of the && operator. Had you written some similar mess with a different operator, for example ret + !(ret = lookup(), your code would have undefined behavior. A bug which will take hours, days or weeks to find. Well, at least you saved 10 seconds of typing!
Also, in both C and C++ use the standard bool type and not some home-brewed version.
You need to correct your code into something more readable and safe:
bool ret = true;
if(ret)
{
ret = lookup();
}
if(!ret)
{
fprintf(stderr, "Error in lookup()\n");
}
Is there any reason why this isn't good code?
Yes, there are a lot issues whith such dirty code fragments!
1)
Nobody can read it and it is not maintainable. A lot of coding guidlines contain a rule which tells you: "One statement per line".
2) If you combine multiple expressions in one if statement, only the first statements will be executed until the expression is defined! This means: if you have multiple expressions which combined with AND the first expression which generates false will be the last one which will be executed. Same with OR combinations: The first one which evaluates to true is the last one which is executed.You already wrote this and you! know this, but this is a bit of tricky programming. If all your colleges write code that way, it is maybe ok, but as I know, my colleagues will not understand what you are doing in the first step!
3) You should never compare and assign in one statement. It is simply ugly!
4) if YOU! already think about " I'm just concerned about the compiler maybe not producing the equivalent logic" you should think again why you are not sure what you are doing! I believe that everybody who must work with such a dirty code will think again on such combinations.
Hint: Don't do that! Never!
I'm trying to figure out if there is a macro similar to delay in clojure to get a lazy expression/ variable that can be evaluated later.
The use case is a default value for Map.get/3, since the default value comes from a database call, I'd prefer it to be called only when it's needed.
Elixir's macro could be used for writing simple wrapper function for conditional evaluation. I've put one gist in the following, though it may be better/smarter way.
https://gist.github.com/parroty/98a68f2e8a735434bd60
"Generic" laziness is a bit of a tough nut to crack because it's a fairly broad question. Streams allow laziness for enumerables but I'm not sure what laziness for an expression would mean. For example what would a lazy form of x = 1 + 2 be? When would it be evaluated?
The thought that comes to mind for a lazy form of an expression is a procedure expression:
def x, do: 1 + 2
Because the value of x wouldn't be calculated until the expression is actually invoked (as far as I know). I'm sure others will correct me if I'm wrong on that point. But I don't think that's what you want.
Maybe you want to rephrase your question--leaving out streams and lazy evaluation of enumerated values.
One way to do this would be using processes. For example the map could be wrapped in a process like a GenServer or an Agent where the default value will be evaluated lazy.
The default value can be a function which makes the expensive call. If Map.get/3 isn't being used to return functions you can check if the value is a function and invoke it if it is returned. Like so:
def default_value()
expensive_db_call()
end
def get_something(dict, key) do
case Map.get(dict, key, default_value) do
value when is_fun(value) ->
value.() # invoke the default function and return the result of the call
value ->
value # key must have existed, return value
end
end
Of course if the map contains functions this type of solution probably won't work.
Also check Elixir's Stream module. While I don't know that it would help solve your particular problem it does allow for lazy evaluation. From the documentation:
Streams are composable, lazy enumerables. Any enumerable that generates items one by one during enumeration is called a stream. For example, Elixir’s Range is a stream:
More information is available in the Stream documentation.
Map.get_lazy and Keyword.get_lazy hold off on generating the default until needed, links the documentation below
https://hexdocs.pm/elixir/Map.html#get_lazy/3
https://hexdocs.pm/elixir/Keyword.html#get_lazy/3
You can wrap it in an anonymous function, then it will be evaluated when the function is called:
iex()> lazy = fn -> :os.list_env_vars() end
#Function<45.79398840/0 in :erl_eval.expr/5>
iex()> lazy.()
With respect to coding standards, speed, and efficiency, which of the following is a better programming practice for this situation?
function foo() {
if(bar) { return 0; }
if(baz) { return 0; }
if(qux) { return 0; }
}
or
function foo() {
if(bar || baz || qux) { return 0; }
}
I'd lean toward the first, since only one condition has to be evaluated and therefore would be faster, but having the multiple returns is not good...?
//EDIT
The languages I'd be applying this to are mainly PHP and Javascript, possibly C++ and Ruby.
Almost every single programming language today uses short-circuit evaluation for ||, which means the two examples will be equivalent in terms of control flow and thus performance.
Having multiple returns should indeed be avoided if they are spread all over the function and they return different things, because this decreases readability. On the other hand, it's fairly standard to have early-out conditions that detect inacceptable conditions and stop the execution flow:
function getFriendList()
{
if (! has_internet_connection() ) return null;
if (! is_logged_in() ) return null;
return server.getFriendList();
}
Regarding your second example the || is short-circuiting in most languages so only the necessary conditions will be evaluated. For example if bar evaluates to true, neither baz nor qux will be evaluated.
Knowing this, I would probably choose the second example.
The latter but as:
function foo()
{
var result = 1;
if(bar || baz || quz)
{
result = 0;
}
return result;
}
Exiting your code willy-nilly with "return" is bad practice and makes debugging a nightmare - especially if it is someone elses code you are trying to debug! Flow of control should always exit at the bottom of the function!
In C# you can use the second version because is the same regarding performance but looks nicer. If bar is true then the other flags are no longer checked.
In the second case since you are using logical-OR the second conditions are checked only if it is necessary,so wrt better coding standards I would like to go with second one.
The latter example is better in my opinion in terms of coding. In an OR statement, atmost one condition is true the statement is true. So if the first condition is true, no further conditions will be looked at. There is no loss in speed or efficiency.
It depends entirely upon the language. Many languages will short-circuit evaluations so that, if bar is true, the other two are not evaluated, and any half-decent compiler will optimise those to the same thing in that case. Of the four languages you mentioned (C++, Ruby, PHP and Javascript), they all do short circuit evaluations.
And, despite what the "avoid multiple returns" crowd will tell you, that's not a rule you should follow like a sheep. It's meant to avoid situations where it's hard to see where returns (or loop breaks) are happening. Your first solution does not suffer from that problem any more than your second.
Blind following of dogma without understanding the reasons behind it should be an offence punishable by painful torture.