So, I have this code,How to find the specific index of zero element?
arr =[1,0,2,0]
for i in arr:
if i <=0:
print(list(arr).index(i))
else:
print("greater")
prints:
greater
1
greater
1
target:
greater
1
greater
3
Use enumerate(), You will get both index and value at the same time. Compare value is greater than 0 or not.
arr = [1, 0, 2, 0]
for i, val in enumerate(arr):
if val > 0:
print('Greater!')
else:
print(i)
Output
Greater!
1
Greater!
3
in python 3 you can get all the index with the following line.
list(map(lambda x: x[0], filter(lambda enum_val: enum_val[1] > 0, enumerate(arr))))
Related
Need help counting the occurrence that values in two columns are greater than a value in the same row. For example, if I want to count the number of times each row is greater than 4 and I have columns X & Y such that:
X Y
2 1
5 5
6 3
5 5
The output variable will be 2 since both numbers are greater than 4 in two rows, row 2 and 4.
Thank you
In [134]: df.gt(4).all(axis="columns").sum()
Out[134]: 2
check if values are greater than 4; gives True/False's (frame)
check if we have all True's per row; gives True/False's again (series)
sum to get the count as True -> 1, False -> 0
What about a comparison like this, in case you're not looking to use any additional packages.
x = [2, 5, 6, 5]
y = [1, 5, 3, 5]
counter = 0 # initialize counter variable
min_value = 4 # initialize min_value to compare
for x, y in zip(x, y):
# print(x, y)
if x > min_value and y > min_value:
counter += 1
print("Row Count: " + str(counter))
If you are using pandas, then you can use something like this:
import pandas as pd
x = [2, 5, 6, 5]
y = [1, 5, 3, 5]
df = pd.DataFrame(list(zip(x, y)), columns=["x", "y"])
min_value = 4 # initialize min_value to compare
counter = df.gt(min_value).all(axis="columns").sum()
print("Row Count: " + str(counter))
For example, if I had a 1x100 array, and it contained 90 0's, I'd like to somehow exclude 80 of those 0's chosen at random. I've been struggling with this problem for a while and I've made very little progress unfortunately.
Since you have a numpy tag:
import numpy as np
def solution(arr, value, size):
return np.delete(arr, np.random.choice(np.flatnonzero(arr==value), size, False))
arr = np.array([0]*90 + [1]*10)
np.random.shuffle(arr)
print(solution(arr, 0, 80)) # [1 0 1 0 0 1 0 0 1 0 1 1 1 0 0 0 0 1 1 1]
print(solution(arr, 0, 90)) # [1 1 1 1 1 1 1 1 1 1]
print(solution(arr, 0, 100)) # Raises error (expected behavior)
Vanilla Python approach.
Determine indices of the elements meeting the criteria:
candidate_indices = [i for i, x in enumerate(data) if data == 0]
Choose indices to remove:
removed_indices = random.sample(candidate_indices, 80)
Remove them, by building a list without the corresponding elements:
result = [x for i, x in enumerate(data) if i not in removed_indices]
This is one approach, it is not very efficient, but it should be robust.
def progressivelyExcludeItem(item, arr, maxExclusions):
"""
#param item the item value that will be progressively excluded
#param arr the list from which we will exclude
#param maxExclusions the maximum number of excluded items
"""
excludeIndices = [i for i, x in enumerate(arr) if x == item]
excludeIndices = random.shuffle(excludeIndices)[:maxExclusions]
for i in excludeIndices.sort().reversed():
arr.pop(i)
Time complexity is O(n^2).
A = [['a'],['a'],['b'],['c'],['b'],['a']]
B = [['k'],['k'],['a'],['b'],['k']]
I have two list, A and B.I have to print those elements index number(index number + 1) separated by space of list A,which elements also exist in list B.For every element of list B,i want to print the indices of the values in list A sequentially in one line.If there is any element of list B,that missing in list A, then i want to print -1 for this element.How can i fix this?
my code:
dict_B = dict([(b[0],[]) for b in B])
for i,a in enumerate(A):
if a[0] in dict_B:
dict_B[a[0]].append(i+1)
for key in dict_B:
if dict_B[key] == []:
c = 0
for i,x in enumerate(B):
if x == list(key):
c += 1
for x in range(c):
if x == c-1:
print(-1,end=" ")
else:
print(-1)
else:
for elem in dict_B[key]:
print(elem,end=' ')
print()
Output of my code:
-1
-1
-1
1 2 6
3 5
Expected Output:
-1
-1
1 2 6
3 5
-1
You're over complicating the problem, I'm not sure why you need to use a dict.
for item_b in B:
found = []
for i, item_a in enumerate(A):
if item_a == item_b:
found.append(str(i + 1))
print(" ".join(found) or -1)
Output:
-1
-1
1 2 6
3 5
-1
You can use collections.defaultdict here.
from collections import defaultdict
idx_dict=defaultdict(list)
for idx,[val] in enumerate(A,1):
idx_dict[val].append(idx)
for [key] in B:
if key in idx_dict:
print(' '.join(map(str,idx_dict[key])))
else:
print(-1)
Output:
-1
-1
1 2 6
3 5
-1
Using non-library python code, how can i return the index and count of the longest sequence of even numbers?
a = [1, 3, 2, 6, 4, 1, 2, 2, 2, 8, 1]
should return 6 and 4, 6 being the index and 4 being the count.
I tried without luck..
def evenSeq(list):
count=0
for i in list:
if list[i]%2 and list[i+1]%2==0:
count+=1
return count
Here's a possible solution:
def even_seq(l):
best = (-1, -1)
start_i = 0
count = 0
for i, n in enumerate(l):
if n % 2 == 0:
count += 1
if count > best[1]:
best = (start_i, count)
else:
start_i = i + 1
count = 0
return best
a=[1,3,2,6,4,2,2,2,2,2,1,2,2,2,8,1]
def evenSeq(a):
largest = 0
temp_largest = 0
location = 0
for count, value in enumerate(a):
if value % 2 == 0:
temp_largest += 1
else:
temp_largest = 0
if temp_largest >= largest:
largest = temp_largest
location = count + 1 - temp_largest #plus one cause enumerate returns the index and we are subbing from the current streak which needs to be offset by one
return location, largest
print(evenSeq(a)) #returns 2 8
Not the prettiest solution but it helps teaches you what's going on and the basic logic of the solution. Basically it checks if the number is even, and keeps a count on the current streak stored in temp_largest. Checks if the temp_largest is the biggest known streak at that moment, and updates the index from enumerate.
Edited based on comment:
for count, value in enumerate(a):
This line basically goes through the list, putting the value in value and the current index in count. enumerate() basically will go through what ever you pass it and returns a count starting from 0 along wit the item. see below for example.
a=[1,3,2,6,4,2,2,2,2,2,1,2,2,2,8,1]
for index, value in enumerate(a):
print('{} index and value is {}'.format(index,value))
Prints out:
0 index and value is 1
1 index and value is 3
2 index and value is 2
3 index and value is 6
4 index and value is 4
5 index and value is 2
6 index and value is 2
7 index and value is 2
8 index and value is 2
9 index and value is 2
10 index and value is 1
11 index and value is 2
12 index and value is 2
13 index and value is 2
14 index and value is 8
15 index and value is 1
I would try it this way:
def evenSeq(seq):
i = startindex = maxindex = maxcount = 0
while i < len(seq):
if seq[i]%2==0:
startindex = i
while i < len(seq) and seq[i]%2==0:
i+=1
if maxcount < i - startindex:
maxcount = i - startindex
maxindex = startindex
i+=1
return (maxindex, maxcount)
Say I have an array with integers 1 through 10 and have to replace all integers less than 6 with 0 and all integers equal to or greater than 6 with 1. Currently, I am doing this:
arry[arry < 6] = 0
arry[arry >= 6] = 1
I was wondering what would be a way to combine these two statements into one line of code, or any other solution for that matter.
I assume that arry is a numpy array (the smart indexing that you are using seems to indicate this). In that case you can simply do:
arry = (arry >= 6).astype(int)
where astype(int) will convert the array of booleans arry >= 6 to an array of integers.
You can use a simple list comprehension:
array = [0 if num < 6 else 1 for num in arry]
Which is equivalent to the following loops:
temp = []
for num in arry:
if num < 6:
temp.append(0)
else:
temp.append(1)
arry = temp
[1 if e >= 6 else 0 for e in arry]
for numpy array, (arry >= 6) gives an array of True/False which you can multiply by 1
(arry >= 6) * 1
or add 0
(arry >= 6) + 0
or cast to int
(a >= 6).astype(int)
[int(e >= 6) for e in arry]
This works because True is defined to be the same value as 1 and False is defined to be the same value as 0.
list(map(lambda i: 0 if i<6 else 1, a))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function (n) {return n >= 6 ? 1 : 0})