Python 2D Array Issue - python-3.2

I am trying to set a specific value of a 2D array to True. Here is the snippet of code:
b [ [False] * 3] * 3
b[2][1] = True
Unfortunately, this is setting the entire row to True (so b[0][1] would then be changed to True). Any ideas on what is going on?
EDIT:
Just tried this code and it worked:
b = []
for i in range(3):
b.append([False, False, False])
b[1][2] = True
Why would it work in that case and not the former?

[[False]*3]*3 creates three references to the same [False,False,False] object, thus when you change one item, your other rows/cols change as well.
Your second version avoids this by createing a new [False, False, False] object for every row/col.

Related

Check if a list contains any element of another list in Dart

I have an array:
const list1 = [0, 1, 2];
How do I check if other arrays contain any of the target array elements?
For example:
[2, 3] //returns true;
[2, 3, 4] //returns true;
[3, 4] //returns false;
Using list1.indexWhere(list2.contains) should be fine for small lists, but for large lists, the asymptotic runtime complexity would be O(m * n) where m and n are the sizes of the lists.
A different way to pose the problem of checking if a list contains any element of another list is to check if the set-intersection of two lists is non-empty. The direct way to implement that would be:
var contains = list1.toSet().intersection(list2.toSet()).isNotEmpty;
Since the default Set implementation is a LinkedHashSet, lookups would be O(1), and computing the intersection would be linear with respect to one of the Sets. However, converting each List to a Set would take linear time, making the whole operation take O(m + n).
That's asymptotically efficient, but it computes the entire intersection just to determine whether it's empty or not, which is wasteful. You can do a bit better by using .any to stop earlier and noting that .any doesn't benefit from the receiving object being a Set:
var set2 = list2.toSet();
var contains = list1.any(set2.contains);
Note that if you can use Sets in the first place instead of Lists, then the conversion cost would disappear and make the operation O(m).
final contains = list1.indexWhere((e) => list2.contains(e)) > -1
Explanation
indexWhere returns an index of an element where the test function returned true.
contains returns true if the given element is presented in the array.

Lua - Find value between 1 - 4 , but only return others

I’m not quite sure how to explain this, but I’m trying to find a way to return all the values between 1 to 4 , that are not the value provided.
For example, let say I provide value ‘2’, I want the process to return 1,3,4 for me to process individually.
To give you a more specific explanation, I’m putting together a script to retrieve the input in use against each output of a 4x4 HDMI matrix. I can retrieve the input in use e.g 2, and enable that button on a UI, but I can’t work out to get the other 3 values, to request that those buttons are turned off on the UI too.
Discover what’s on..(value returned 2)
luup.variable_set("urn:upnp-net:serviceId:Matrix1", "input2", ‘true’,
Turn off the others..
luup.variable_set("urn:upnp-net:serviceId:Matrix1", "input1", ‘false’,
luup.variable_set("urn:upnp-net:serviceId:Matrix1", "input3", ‘false’,
luup.variable_set("urn:upnp-net:serviceId:Matrix1", "input4", ‘false’,
Hope that helps someone to help me ?
function foo(n)
tbl = {1, 2, 3, 4}
table.remove(tbl, n)
return tbl
end
or to also call those functions
function foo(n)
tbl = {1, 2, 3, 4}
luup.variable_set("urn:upnp-net:serviceId:Matrix1", "input"..table.remove(tbl, n), ‘true’)
for num, _ in ipairs(tbl) do
luup.variable_set("urn:upnp-net:serviceId:Matrix1", "input"..num, ‘false’)
end
end

Shorter way to convert an empty string to an int, and then clamp

I'm looking for a way to simplify the code for the following logic:
Take a value that is either a nil or an empty string
Convert that value to an integer
Set zero values to the maximum value (empty string/nil are converted to 0 when cast as an int)
.clamp the value between a minimum and a maximum
Here's the long form that works:
minimum = 1
maximum = 10_000
value = value.to_i
value = maximum if value.zero?
value = value.clamp(minimum, maximum)
So for example, if value is "", I should get 10,000. If value is "15", I should get 15. If value is "45000", I should get 10000.
Is there a way to shorten this logic, assuming that minimum and maximum are defined and that the default value is the maximum?
The biggest problem I've had in shortening it is that null-coalescing doesn't work on the zero, since Ruby considers zero a truthy value. Otherwise, it could be a one-liner.
you could still do a one-liner with your current logic
minimum, maximum = 1, 10_000
value = ( value.to_i.zero? ? maximum: value.to_i ).clamp(minimum, maximum)
but not sure if your issue is that if you enter '0' you want 1 and not 10_000 if so then try this
minimum, maximum = 1, 10_000
value = (value.to_i if Float(value) rescue maximum).clamp(minimum, maximum)
Consider Fixing the Input Object or Method
If you're messing with String objects when you expect an Integer, you're probably dealing with user input. If that's the case, the problem should really be solved through input validation and/or looping over an input prompt elsewhere in your program rather than trying to perform input transformations inline.
Duck-typing is great, but I suspect you have a broken contract between methods or objects. As a general rule, it's better to fix the source of the mismatch unless you're deliberately wrapping some piece of code that shouldn't be modified. There are a number of possible refactorings and patterns if that's the case.
One such solution is to use a collaborator object or method for information hiding. This enables you to perform your input transformations without complicating your inline logic, and allowing you to access the transformed value as a simple method call such as user_input.value.
Turning a Value into a Collaborator Object
If you are just trying to tighten up your current method you can aim for shorter code, but I'd personally recommend aiming for maintainability instead. Pragmatically, that means sending your value to the constructor of a specialized object, and then asking that object for a result. As a bonus, this allows you to use a default variable assignment to handle nil. Consider the following:
class MaximizeUnsetInputValue
MIN = 1
MAX = 10_000
def initialize value=MAX
#value = value
set_empty_to_max
end
def set_empty_to_max
#value = MAX if #value.to_i.zero?
end
def value
#value.clamp MIN, MAX
end
end
You can easily validate that this handles your various use cases while hiding the implementation details inside the collaborator object's methods. For example:
inputs_and_expected_outputs = [
[0, 10000],
[1, 1],
[10, 10],
[10001, 10000],
[nil, 10000],
['', 10000]
]
inputs_and_expected_outputs.map do |input, expected|
MaximizeUnsetInputValue.new(input).value == expected
end
#=> [true, true, true, true, true, true]
There are certainly other approaches, but this is the one I'd recommend based on your posted code. It isn't shorter, but I think it's readable, maintainable, adaptable, and reusable. Your mileage may vary.

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.

How to check include? at least one element in array, ruby on rails

Can I check include? at least one element in array with ruby on rails?? Here my example:
a = 1234
b = [1,5,6,7,8....]
if a.include?b[0] == true
app => return true
if a.include?b[0] == true and a.include?b[1] == false and a.include?b[2] == false and ......
app still return true
In the real app, I can't call b[0],b[1],b[2]... like that,So, how can I do to check include? at least one element in array, in rails app? Please help me :)
In cases like these, basic set algebra comes in handy. In your case, you want to check if the intersection of both sets (here implemented as arrays) is not empty, i.e. if they have any elements in common.
In Ruby, you can use the set operations for this:
a = "12345".chars.map(&:to_i)
b = [1,5,6,7,8]
intersection = a & b
has_common_elements = intersection.any?
You can read more about the intersection operator at the Ruby documentation. And while you are at that, you should also read about the union operator too, which complements the the intersection operator.
a1 = a.to_s.chars.map(&:to_i)
# => [1, 2, 3, 4]
b.any? {|i| a1.include?(i) }
# => true
UPDATE:
Ruby 2.4 has an Integer#digits. So you can do
a1 = a.digits
b.any? {|i| a1.include?(i) }
digits = a.to_s.chars.map(&:to_i)
(digits - b).empty?

Resources