How to retrieve the array elements in a tuple in numpy - python-3.x

when I used numpy.nonzero(), e.g. numpy.nonzero(bool_row), where bool_row is a series containing boolean values. It returns a tuple, which contains only one array. I want to retrieve the elements in the array and put them in a list. How to do that?

When indexing, a tuple is the same as actual values, e.g.
x[1,2]
x[(1,2)]
idx = (1,2); x[idx]
So in you case, the result of nonzero can be used directly as the indexing tuple.
In [566]: x=np.arange(10,20)
In [567]: idx = np.nonzero(x%2)
In [568]: idx
Out[568]: (array([1, 3, 5, 7, 9], dtype=int32),)
In [569]: x[idx]
Out[569]: array([11, 13, 15, 17, 19])
From the nonzero docs
The corresponding non-zero
values can be obtained with::
a[nonzero(a)]
If you need a list instead of an array, you'll have add the .tolist() method.

Related

WHY sort function works such in both conditions?

l = [1, 2, 3]
print(l.sort(reverse = True))
Here output=None
l = [1,2,3]
l.sort(reverse = True)
print(l)
Here =[3,2,1]
#ggorlen answered your question - .sort() performs an in-place sort of your list and returns None when it is done. So, in your first example you are printing the None that .sort() returned. If want to print a sorted version of your list without actually sorting the list iself you could used a similar function, sorted.
Example:
l = [1, 2, 3]
print(sorted(l, reverse = True))
Output:
[3, 2, 1]
in 1st snippet you are printing the return value of sort() i.e. None
sort() returns None instead it just sorts the list
your approach in 2nd snippet is correct because you first sorted the list and then printed it.
The primary difference between the list sort() function and the sorted() function is that the sort() function will modify the list it is called on. The sorted() function will create a new list containing a sorted version of the list it is given. The sorted() function will not modify the list passed as a parameter. If you want to sort a list but still have the original unsorted version, then you would use the sorted() function. If maintaining the original order of the list is unimportant, then you can call the sort() function on the list.
A second important difference is that the sorted() function will return a list so you must assign the returned data to a new variable. The sort() function modifies the list in-place and has no return value.
The example below shows the difference in behavior between sort() and sorted(). After being passed to sorted(), the l list remains unchanged. Once the sort() function is called on it, the list is updated. exaple:
l = [3, 1, 2]
new_list = sorted(l)
print(new_list) # output --> [1, 2, 3]
print(l) # output --> [3, 1, 2]
l.sort() # finction sort()
print(l) # output --> [1, 2, 3]

Godot - How do I create a subarray of a list in Gdscript?

I know it's possible to slice an array in python by array[2:4]. The way I get around this is to just loop through the indexes I want and append them to the new_list. This way requires more work is there just a simple way to do it like in python?
You can use the Array.slice() method added in Godot 3.2 for this purpose:
Array slice ( int begin, int end, int step=1, bool deep=False )
Duplicates the subset described in the function and returns it in an array, deeply copying the array if deep is true. Lower and upper index are inclusive, with the step describing the change between indices while slicing.
Example:
var array = [2, 4, 6, 8]
var subset = array.slice(1, 2)
print(subset) # Should print [4, 6]

In the case of a tie, how do I return the largest and most frequent number in python?

I have a list of numbers. I created this frequency dictionary d:
from collections import Counter
mylist = [10, 8, 12, 7, 8, 8, 6, 4, 10, 12, 10, 12]
d = Counter(mylist)
print(d)
The output is like this:
Counter({10: 3, 8: 3, 12: 3, 7: 1, 6: 1, 4: 1})
I know I can use max(d, key=d.get) to get value if there is no tie in frequency. If multiple items are maximal, the function usually returns the first one encountered. How can I return the largest number, in this case, 12, instead of 10? Thank you for your help!
Define a lambda function that returns a tuple. Tuples are sorted by their first value, and then tie-broken by subsequent values. Like this:
max(d, key=lambda x:(d.get(x), x))
So for the two example values, the lambda will return (3, 10) and (3, 12). And of course, the second will be considered the max.
Further explanation:
When the max function is given a collection to find the max of, and a key, it will go over the values in the collection, passing each value into the key function. Whatever element from the collection results in the maximal output from the key function is considered the maximal value.
In this case, we're giving it a lambda function. Lambdas are just functions. Literally no difference in their usage, just a different syntax for defining them. The above example could have been written as:
def maxKey(x):return (d.get(x), x)
max(d, key=maxKey)
and it would behave the same way.
Using that function, we can see the return values that it would give for your sample data.
maxKey(10) #(3, 10)
maxKey(12) #(3, 12)
The main difference between the anonymous lambda above and using d.get is that the lambda returns a tuple with two values in it.
When max encounters a tie, it returns the first one it saw. But because we're now returning tuples, and because we know that the second value in each tuple is unique (because it comes from a dictionary), we can be sure that there won't be any duplicates. When max encounters a tuple it first compares the first value in the tuple against whatever it has already found to be the maximal value. If there's a tie there, it compares the next value. If there's a tie there, the next value, etc. So when max compares (3, 10) with (3, 12) it will see that (3, 12) is the maximal value. Since that is the value that resulted from 12 going into the key function, max will see 12 as the maximal value.
You can get the max count (using d.most_common), and then get the max of all keys that have the max count:
max_cnt = d.most_common(1)[0][1]
grt_max = max(n for n, cnt in d.items() if cnt == max_cnt)
print(grt_max)
Output:
12

create list from list where values only increase by 1

I have the code below that gets the maximum value from a list. It then compares it to the maximum value of the remaining values in the list, and if it is more than 1 higher than the next greatest value, it replaces the original list maximum with 1 higher than the next greatest value. I would like the code to search the entire list and make sure that any value in the list is at most 1 larger than any other value in the list. I know this ins’t the best worded explanation, I hope the example lists below make what I’m trying to accomplish clearer.
for example I don’t want to get a final list like:
[0,2,0,3]
I would want the final list to be
[0,1,0,2]
input:
empt=[0,2,0,0]
Code:
nwEmpt=[i for i in empt if i !=max(empt)]
nwEmpt2=[]
for i in range(0,len(empt)):
if (empt[i]==max(empt))&(max(empt)>(max(nwEmpt)+1)):
nwEmpt2.append((max(nwEmpt)+1))
elif (empt[i]==max(empt))&(max(empt)==(max(nwEmpt)+1)):
nwEmpt2.append(max(empt))
else:
nwEmpt2.append(empt[i])
output:
nwEmpt2
[0,1,0,0]
min_value = min(empt)
empt_set = set(empt)
for i in empt:
nwEmpt.append(min_value + len(list(filter(lambda x: x < i, empt_set))))
This gives e.g. for input empt = [8, 10, 6, 4, 4] output nwEmpt = [6, 7, 5, 4, 4].
It works by mapping each element to (the minimum value) + (the number of distinct values smaller than element).

What is the empty dictionary used for in the code?

I'm doing practice problems in python on Leetcode (still learning). This is the problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
my code is
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for counter, i in enumerate(nums):
a = target- i
if a in dict:
return (dict[a], counter)
dict[i] = counter
It runs fine and passes all the tests however I found a common reason this works is for the dict = {}
What is the reason for this dictionary and how does this code recognize cases for (3,3) target = 6 where there are duplicates and index matters. A basic run down of why the code works would be great!
The dictionary stores as keys the numbers in the list with their index as a value.
For example:
[2, 7, 11, 15] -> {'2':0, '7':1, '11':2, '15':3}
There is never a duplicate inserted, if the same number appears twice, the index will be replaced with the new index where it appears.
In the case of duplicate, it is important to test all value on the first list, and to store index on a separated dict in order to be sur that you will never test in dictionnary the actually tested value.
By using a dictionnary in order to find the index of the right number, you can't store duplicate.
Since in dictionnary you can't have 2 values with the same key, if duplicate, you just change the old index with the new one.
For example, if dict == {'3': 0, '2':1} and the tested value is 2, the dict == {'3': 0, '2':2}.
And if the target is reach by duplicate number (2+2 for target 4 for example), nothing is stored cause of the return in the if a in dict: return (dict[a], counter)

Resources