Join two strings to get variable name and its contents - string

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.

Related

Trouble with removing list elements that are present in another list

I am attempting to add items to a new list from a primary list, then remove those moved items from the primary list. Essentially use and discard.
I have already attempted to use list comprehensions (Remove all the elements that occur in one list from another).
Then I attempted to use a for loop as well as an if statement to check for the elements and remove them, though when I printed the original list once again, nothing changed.
Not sure what I am doing wrong but it is extremely frustrating:
your_hand_list = []
computer_hand_list = []
computer_hand_list.append (random.sample(card_list, 5))
your_hand_list.append (random.sample(card_list, 5))
print (your_hand_list, computer_hand_list)
for card in your_hand_list and computer_hand_list:
if card in card_list:
card_list.remove(card)
Edit: Adding your code made it much easier to understand your issue. Specifically, the problem is this statement:
for card in your_hand_list and computer_hand_list:
The Python and operator does not work the way you were expecting it to in this context. Instead, the Python standard itertools library has a function called chain that will solve your problem. Here is a (greatly) simplified version of your code for illustration purposes.
Example:
from itertools import chain
card_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
your_hand_list = [1, 4, 7]
computer_hand_list = [3, 9, 10]
for card in chain(your_hand_list, computer_hand_list):
if card in card_list:
card_list.remove(card)
print(card_list)
Output:
[2, 5, 6, 8]

Is there a way to sort an unsorted list with some repeated elements?

I am trying to sort an unsorted list [4, 5, 9, 9, 0, 1, 8]
The list has two repeated elements. I have tried to approach the question by having a loop that goes through each element comparing each element with the next in the list and then placing the smaller element at the start of the list.
def sort(ls:
ls[x]
x = [4, 5, 9, 9, 0, 1, 8]
while len(x) > 0:
for i in the range(0, len(x)):
lowest = x[i]
ls.append(lowest)
Please, could someone explain where I am going wrong and how the code should work?
It may be that I have incorrectly thought about the problem and my reasoning for how the code should work is not right
I do not know, if this is exactly what you are looking for but try: sorted(ListObject).
sorted() returns the elements of the list from the smallest to the biggest. If one element is repeated, the repeated element is right after the original element. Hope that helped.
Yes, you can try x.sort() or sorted(x). Check this out https://www.programiz.com/python-programming/methods/built-in/sorted. Also, in your program I don't see you making any comparisons, for example, if x[i] <= x[i+1] then ...
This block of code is just gonna append all the elements in the same order, till n*n times.
Also check this https://en.wikipedia.org/wiki/Insertion_sort
For a built-in Python function to sort, let y be your original list, you can use either sorted(y) or y.sort().Keep in mind that sorted(y) will return a new list so you would need to assign it to a variable such as x=sorted(y); whereas if you use x.sort() it will mutate the original list in-place, so you would just call it as is.
If you're looking to actually implement a sorting function, you can try Merge Sort or Quick Sort which run in O (n log n) in which will handle elements with the same value. You can check this out if you want -> https://www.geeksforgeeks.org/python-program-for-merge-sort/ . For an easier to understand sorting algorithm, Insertion or Bubble sort also handle duplicate as well but have a longer runtime O (n^2) -> https://www.geeksforgeeks.org/python-program-for-bubble-sort/ .
But yea, I agree with Nameet, what you've currently posted looks like it would just append in the same order.
Try one of the above suggestions and hopefully this helps point you in the right direction to if you're looking for a built-in function or to implement a sort, which can be done in multiple ways with different adv and disadv to each one. Hope this helps and good luck!
There are several popular ways for sorting. take bubble sort as an example,
def bubbleSort(array):
x = len(array)
while(x > 1): # the code below make sense only there are at least 2 elements in the list
for i in range(x-1): # maximum of i is x-2, the last element in arr is arr[x-1]
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
x -= 1
return array
x = [4, 5, 9, 9, 0, 1, 8]
bubbleSort(x)
your code has the same logic as below
def sorts(x):
ls = []
while len(x) > 0:
lowest = min(x)
ls.append(lowest)
x.remove(lowest)
return ls
x = [4, 5, 9, 9, 0, 1, 8]
sorts(x)
#output is [0, 1, 4, 5, 8, 9, 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

Explaining the behavior of sprintf in MATLAB

I have recently been perplexed by some of the behavior of sprintf. It appears to be inconsistent in my view and I haven't been able to exactly determine the logic behind some of its behavior. Here is one case that baffles me
C = [1 + 2i, 3+ 4i, 5+6i, 7+8i, 9+10i];
>> sprintf('%+d%+di\n',real(C(1:2)),imag(C(1:2)))
ans =
+1+3i
+2+4i
>> sprintf('%+d%+di\n',real(C(1:3)),imag(C(1:3)))
ans =
+1+3i
+5+2i
+4+6i
I would've expected it to print my complex numbers as in C. Do I need to explicitly create a new vector of interleaved inputs? I feel this is problematic when different types are involved.
EDIT: What I feel the expected output should be
>> sprintf('%+d%+di\n',real(C(1:2)),imag(C(1:2)))
ans =
+1+2i
+3+4i
>> sprintf('%+d%+di\n',real(C(1:3)),imag(C(1:3)))
ans =
+1+2i
+3+4i
+5+6i
The sprintf command you have provided behaves as sprintf('%+d%+di\n', [1, 3], [2, 4]) since real(C(1:2)) returns [1, 3] and imag(C(1:2)) returns [2, 4] which behaves as you've observed.
What you want to do is: sprintf('%+d%+di\n', [1, 3; 2, 4])
It should be accomplished by either looping over elements of C or with the following sprinf('%+d%+di\n', [real(C(1:2)); imag(C(1:2))]).

Underscore GroupBy Sort

I have a question regarding programming in function style.
I use underscore.js library.
Let's consider some use-case. I have an array of some labels with repetitions I need to count how many occurrences of each label is in array and sort it according to the number of occurrences.
For counting, how many labels I can use countBy
_.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
=> {odd: 3, even: 2}
But here, as result I have a hash, which doesn't have meaning for order, so there is no sort. So here, I need to convert the hash to array then to sort it and convert backward to hash.
I am pretty sure there is an elegant way to do so, however I am not aware of it.
I would appreciate any help.
sort it and convert backward to hash.
No, that would loose the order again.
You could use
var occurences = _.countBy([1, 2, 3, 4, 5], function(num) {
return num % 2 == 0 ? 'even': 'odd';
});
// {odd: 3, even: 2}
var order = _.sortBy(_.keys(occurences), function(k){return occurences[k];})
// ["even", "odd"]
or maybe just
_.sortBy(_.pairs(occurences), 1)
// [["even", 2], ["odd", 3]]

Resources