How to get a specific element from the set - PlusCal - tla+

Given the set, for example, {1, 2, 4, 10, 6} how can I get the element 4 to a variable var.
What I want is to get element "4" from the set to a variable var: var = 4
And remove the element 4 from the set: set = {1, 2, 10, 6}

Based on the comments, it sounds like you want this:
with x \in set do
var := x;
set := set \ {x};
end with;

Related

how to concatenate a string and a variable and assign a value in it in python

Is there anyway to assign value in concatenated variable?
I want to concatenate and assign a value in it.
for i in range (5):
'serial_' + str(i) = i+5
that showing SyntaxError: can't assign to operator
If I understand correctly,
d = {}
In [898]: for i in range (5):
...: d[ ('{}' + str(i)).format('serial_')] = i+5
In [899]: d
Out[899]: {'serial_0': 5, 'serial_1': 6, 'serial_2': 7, 'serial_3': 8, 'serial_4': 9}
Let me know if this is what you want.
It is possible to add variables with concatenated names in the global/local symbol table using the globals and locals built-in functions:
>>> for i in range (5):
... global()['serial_' + str(i)] = i+5
...
>>> serial_0
5
>>> serial_3
8
However according to the documentation, changing the dictionary returned by locals may have no effect to the values of local variables used by the interpreter.
Furthermore since modifying the global symbol table is not considered a good practice, I recommend you to use a dictionary to store your values as suggested by Mayank Porwal as this will result in cleaner code:
>>> d = {f'serial_{i}' : i + 5 for i in range(5)}
>>> d
{'serial_0': 5, 'serial_1': 6, 'serial_2': 7, 'serial_3': 8, 'serial_4': 9}

How to find how many items are in the same position in two lists?python

I need to be able to check if any items in one list are also in another list but in the same position. I have seen others but they return true or false. I need to know how many are in the same position.
So compare them directly!
This of course is assuming both lists are the same length:
a = [1, 1, 2, 3, 4, 5, 7, 8, 9]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
matches = 0
for index in range(len(a)):
if a[index] == b[index]:
matches += 1
print mat
Try it here!
overlap = set(enumerate(listA)).intersection(set(enumerate(listB))
print(len(overlap))
enumerate pairs up elements with their index, so you can check how many common element/ index pairs exist between the two lists.
One advantage of this approach (as opposed to iterating through either list yourself) is that it automatically takes care of the case where the lists have different lengths.
demo

Join two strings to get variable name and its contents

I have:
AB_xy = [4, 3, 5, 9, 10]
And I want to access AB_xy elements by combining its name from two separate strings something like this:
['AB' '_xy'](1)
I would like this to return 4 as it would be done by AB_xy(1)but this doesnt work. Suggestions ?
Here, eval would work, if you also include the index
AB_xy = [4, 3, 5, 9, 10];
eval(['AB', '_xy(1)'])
ans =
4
But in general eval should be avoided as there are other alternatives.
Perhaps you could consider making AB a struct with xy as a field.
AB.xy = [4, 3, 5, 9, 10];
and use dynamic field reference
str = 'xy';
AB.(str)(1)
ans =
4
It sounds lika an eval problem.
s = strcat('AB', '_xy', '(', '1', ')')
eval(s)
Of course, just substitute the strings in strcat to variables holding the string(s) you would like to concatenate.
And I agree fully with #BillBokeey. eval is usually a code smell.

Python convert string to variable name

Im aware that this may come up as a duplicate but so far I haven't found (or should that be understood) an answer to what Im looking for.
I have a list of strings and want to convert each one into a variable name which I then assign something to. I understand that I may need a dict for this but I am unfamiliar with them as I am relatively new to python and all the examples I have seen so far deal with values whilst I'm trying something different.
Im after something like:
list = ['spam', 'eggs', 'ham']
for i in range(len(list)):
list[i] = rat.readColumn(ratDataset, list[i])
where the first list[i] is a variable name and not a string. The second list[i] is a string (and for context is the name of a column Im reading from a raster attribute table (rat))
Essentially I want each string within the list to be set as a variable name.
The idea behind this is that I can create a loop without having to write out the line for each variable I want, with matching rat column name (the string). Maybe there is a beer way of doing this than I am suggesting?
Try the following:
lst = ['spam', 'eggs', 'ham']
d = {} # empty dictionary
for name in lst:
d[name] = rat.readColumn(ratDataset, name)
Do not use list for your identifiers as it is a type identifier and you would mask its existence. The for loop can iterate directly for the elements inside -- no need to construct index and use it aganist the list. The d['spam'] will be one of your variables.
Although, it is also possible to create the real variable names like spam, eggs, ham, you would not probably do that as the effect would be useless.
Here comes a simple dictionary use :
variables = ['spam', 'eggs', 'ham']
data = {}
datum = 0
for variable in variables:
data[variable] = datum
datum+=1
print(data)
print("value : ",data[variables[2]])
It gives as result :
{'eggs': 1, 'ham': 2, 'spam': 0}
value : 2
NB : don't use list as a variable name, list is a type identifier that you can use to transform an object into a list if possible (list("abc")==['a', 'b', 'c']) and you are overriding it with your value list right now.
one way is setting the variable name as a string and changing a part or all of it via format() method and then using the string as a varibale via vars()[STRING]
import numpy as np
X1= np.arange(1,10)
y1=[i**2 for i in X1]
X2= np.arange(-5,5)
y2=[i**2 for i in X2]
for i in range(1,3):
X = 'X{}'.format(i)
y = 'y{}'.format(i)
print('X_{}'.format(i) , vars()[X])
print('y_{}'.format(i) , vars()[y])
Output:
X_1 [1 2 3 4 5 6 7 8 9]
y_1 [1, 4, 9, 16, 25, 36, 49, 64, 81]
X_2 [-5 -4 -3 -2 -1 0 1 2 3 4]
y_2 [25, 16, 9, 4, 1, 0, 1, 4, 9, 16]

finding onsets (and offsets) of number sequence

given the following cell array:
strings = {'str1', 'str2', 'str2', 'str1', 'str2', 'str2', 'str1', 'str1', 'str2'};
I want to find the onsets and offsets (first occurrence and last occurrence) of a particular value. For example, the following are the onsets and offsets for 'str1':
onset_str1 = [1, 4, 7, ];
offset_str1 = [1, 4, 8, ];
And here are the on- and offsets for 'str2':
onset_str2 = [2, 5, 9];
offset_str2 = [3, 6, 9];
Currently I do something like this:
[blub, ia, ic] = unique(strings, 'first');
all_str1 = find(ic == 1); % 1 4 7 8
all_str2 = find(ic == 2); % 2 3 5 6 9
Using all_str1 and all_str2 I would then look for consecutive values (using diff for example) and determine that way the on and offsets. However this kind of implementation feels 'hackish' to me.
What other ways are there to extract the on and offsets in my sequence efficiently?
[blub, ia, ic] = unique(strings, 'first');
ok, but next up, just use logicals and find to find the rising/falling edges:
N = numel(blub); % number of unique strings found
str_onsets=cell(N,1);
str_offsets=cell(N,1);
for ii=1:N
x=ic==ii;
str_onsets{ii} = find([true ~x(1:end-1)] & x);
str_offsets{ii}= find(x & [~x(2:end) true]);
end
or strfind if that's more clear to understand to you:
N = numel(blub); % number of unique strings found
str_onsets=cell(N,1);
str_offsets=cell(N,1);
for ii=1:N
x=ic==ii;
str_onsets{ii} = strfind([0 x],[0 1]);
str_offsets{ii}= strfind([x 0],[1 0]);
end

Resources