for i in nli: if i not in fli: f=True as comprehension - for-comprehension

How to convert this piece of code in python3 to comprehension?
Im trying to access each element of list1 compare it with list2,if not in it then flag is set.
Please help:
for i in list1:
if i not in list2:
flag=True

You can use the any function. This functions takes an iterable over booleans (or expressions convertible into booleans) and returns True if and only if any of the elements in the iterable are true.
flag = any(i not in list2 for i in list1)
That is: Go through list1 and check for each element i whether it is not in list2. If this is True for any i, the any function will return True.
There is also the closely related function all. As you may suspect this returns True if all elements of the input iterable are True. You could also write the above as
flag = not all(i in list2 for i in list1)

Related

Take every item in list that starts with x and put it in a new list - Rego

list := ["a:aqsdf", "a:asdf", "b:gfs", "b:sdf", "a:adfd", "b:asdfd"]
I want the new list to only include items that start with 'a': ["a:aqsdf", "a:asdf", "a:adfd"]
I've tried working with sets with no success. This would be a breeze in python but can't seem to wrap my head around rego. I can turn it into a set but not sure how to squeeze in an if statement(startswith(list[_], "a") == true)
One way to do this is with an array comprehension and the startswith builtin function:
[ x | x := list[_]; startswith(x, "a")]
Playground example: https://play.openpolicyagent.org/p/8mQYYvUL2h
This is essentially saying to define a new array containing the value of x if the rule body is true. The rule body for the comprehension is in turn iterating over all indicies of list for values of x, and will be true when the value of x starts with "a".
References:
https://www.openpolicyagent.org/docs/latest/policy-reference/#strings
https://www.openpolicyagent.org/docs/latest/policy-language/#comprehensions

This expression was expected to have type bool but here has type unit error

getting an error when I try to run this line of code and I can't figure out why
let validCol column value : bool =
for i in 0..8 do
if sudokuBoard.[i,column] = value then
false
else true
As Tyler Hartwig says a for loop cannot return a value except unit.
On the other hand, inside a list comprehension or a seq Computation Expression you can use for to yield the values and then test if the one you are looking for exists:
let validCol column value : bool =
seq { for i in 0..8 do yield sudokuBoard.[i,column] }
|> Seq.exists value
|> not
In F#, the last call made is what is returned, you have explicitly declared you are returning a bool.
The for loop is unable to return or aggregate multiple values, bun instead, returns unit.
let validCol column value : bool =
for i in 0..8 do
if sudokuBoard.[i,column] = value then
false
else
true
Here, you'll need to figure out how to aggregate all the bool to get your final result. I'm not quite sure what this is supposed to return, or I'd give an example.
It looks like you are looking for a short-cut out of the loop like in C# you can use continue, break or return to exit a loop.
In F# the way to accomplish that with performance is to use tail-recursion. You could achieve it with while loops but that requires mutable variables which tail-recursion doesn't need (although we sometimes uses it).
A tail-recursive function is one that calls itself at the very end and doesn't look at the result:
So this is tail-recursive
let rec loop acc i = if i > 0 then loop (acc + i) (i - 1) else acc
Where this isn't
let rec loop fib i = if i < 1 then 1 else fib (i - 1) + fib (i - 2)
If F# compiler determines a function is tail-recursive the compiler applies tail-recursion optimization (TCO) on the function, basically it unrolls it into an efficient for loop that looks a lot like the loop would like in C#.
So here is one way to write validCol using tail-recursion:
let validCol column value : bool =
// loops is tail-recursive
let rec loop column value i =
if i < 9 then
if sudokuBoard.[i,column] = value then
false // The value already exists in the column, not valid
else
loop column value (i + 1) // Check next row.
else
true // Reach the end, the value is valid
loop column value 0
Unfortunately; F# compiler doesn't have an attribute to force TCO (like Scala or kotlin does) and therefore if you make a slight mistake you might end up with a function that isn't TCO. I think I saw GitHub issue about adding such an attribute.
PS. seq comprehensions are nice in many cases but for a sudoku solver I assume you are looking for something that is as fast as possible. seq comprehensions (and LINQ) I think adds too much overhead for a sudoku solver whereas tail-recursion is about as quick as you can get in F#.
PS. In .NET 2D arrays are slower than 1D arrays, just FYI. Unsure if it has improved with dotnet core.

In Z3: how if then else based conditions be formulated (based on evaluations of variables)?

I'm new to Z3 and still couldn't find how I can express conditional new assignments based on the different possible evaluations. In If-then-else example in
https://github.com/Z3Prover/z3/blob/master/examples/c/test_capi.c#L1846
I still need to make the assignment to true or false, and when I want to make it true or false based on possible evaluations of another variable. How can I do this?
In the evaluation example I want the value calculated to be used to affect the still not evaluated values that are going to be checked by assertion later. So if this is the way how I can return back the model UN-evaluated with the new (evaluation based) conditions to the context again? i.e. I want to do composite conditions without final evaluations. Is that possible?
The following line from ite_example():
ite = Z3_mk_ite(ctx, f, one, zero)
creates an expression that will evaluate to whatever the (symbolic) term one evaluates to, if f evaluates to true, or alternatively to whatever zero evaluates to, if f evalautes to false. In ite_example, f always evaluates to false, but it may be any other (symbolic) term of Boolean sort.
For example,
x = mk_int_var(ctx, "x");
y = mk_int_var(ctx, "y");
x_eq_y = Z3_mk_eq(ctx, x, y);
will create a term called x_eq_y, representing "x = y", which is of Boolean sort.

is_proplist in erlang?

How can get the type of a list. I want to execute the code if the list is proplist.
Let us say L = [a,1,b,2,c,3, ...]. Is the list L, I'm converting it to proplist like
L = [{a,1}, {b,2}, {c,3}, ...].
How can I determine whether the list is a proplist? erlang:is_list/1 is not useful for me.
You can use something like:
is_proplist([]) -> true;
is_proplist([{K,_}|L]) when is_atom(K) -> is_proplist(L);
is_proplist(_) -> false.
but necessary to consider that this function cannot be used in guards.
You'd need to check whether every element of the list is a tuple of two elements. That can be done with lists:all/2:
is_proplist(List) ->
is_list(List) andalso
lists:all(fun({_, _}) -> true;
(_) -> false
end,
List).
This depends on which definition of "proplist" you use, of course. The above is what is usually meant by "proplist", but the documentation for the proplists module says:
Property lists are ordinary lists containing entries in the form of either tuples, whose first elements are keys used for lookup and insertion, or atoms, which work as shorthand for tuples {Atom, true}.

What does this Erlang statement do?

I have this Erlang code:
not lists:any(fun(Condition) ->Condition(Message) end, Conditions).
Can anyone please explain the entire statement in layman's terms? For your information Condition is a function, Conditions is an array. What does fun(Condition) ->Condition(Message) end mean? As well as meaning of not lists:any.
fun(Condition) ->Condition(Message) end
is a lambda function that applies the function Condition to the value of Message (taken as a closure on the surrounding code).
lists:any
is a function that takes a predicate and a list of values, and calls the predicate on each value in turn, and returns the atom true if any of the predicate calls do.
Overall, the result is the atom true if none of the Condition functions in the list Conditions return true for the Message value.
EDIT -- add documentation for lists:any
any(Pred, List) -> bool()
Types:
Pred = fun(Elem) -> bool()
Elem = term()
List = [term()]
Returns true if Pred(Elem) returns true for at least one element Elem in List.
Condition is something that takes a message and returns a boolean if it meets some criteria.
The code goes through the list of conditions and if any of them say true then it returns false, and if all of them say false it says true.
Roughly translated to verbose pseudo-Python:
def not_lists_any(Message,Conditions):
for Condition in Conditions:
if Condition(Message):
return False
return True
One step behind syntax and stdlib description which you have in other answers:
This code looks very much like an Erlang implementation of chain-of-responsibility design pattern. The message (in OOP sense of the word) "traverses" all possible handlers (functions from Conditions array) until someone can handle it. By the author's convention, the one which handles the message returns true (otherwise false), so if nobody could handle the message the result of your expression as a whole is true:
% this is your code wrapped in a function
dispatch(Message, Handlers) ->
not lists:any(fun(Condition) ->Condition(Message) end, Handlers).
It may be used like this:
CantHandle = dispatch(Event, Handlers),
if CantHandle->throw(cannot_handle); true->ok end.

Resources