Longest sequence of even numbers in python - python

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)

Related

look for indices for the smallest number and the smallest number adjacent to that number

It needs to find the index of the smallest number and the index of the smallest neighboring number.
If there are more such pairs, it chooses the number with the smallest indices.
for examlple:
lista = [0,4,3,2,0,5,4,0,3,4,2,0]
My first smallest value in that list is 0 so there are 6 possibilities for different pairs
0,4 with indices 0 and 1
0,2 with indices 3 and 4
0,5 with indices 4 and 5
4,0 with indices 6 and 7
2,0 with indices 10 and 11
My second smallest value in this 6 possibilities is 2 so I have two options
0,2 with indices 3 and 4
2,0 with indices 10 and 11
Indexes 3 and 4 are less than 10 and 11 so the correct answer is
[3, 4]
The program I tried to write but it doesn't work as expected vvv
def indices(lst, element):
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset)
def search_min2(lista, max_value):
for i in lista:
if(i==0):
if(lista[i+1]<max_value):
max_value = lista[i+1]
elif(i==len(lista)-1):
if(lista[i-1]<max_value):
max_value = lista[i-1]
else:
if(lista[i-1]<max_value):
max_value = lista[i-1]
if(lista[i+1]<max_value):
max_value = lista[i+1]
second_min = max_value
return second_min
lista = [0,4,3,2,0,5,4,0,3,4,2,0]
min_value = 0
min_list = indices(lista, min_value)
# min2 = search_min2(min_list, max(lista))
# print(min2)
Thank you for help in advance
You could find the first index in the range with the minimum sorted pair at that index:
i = min(range(len(lista) - 1),
key=lambda i: sorted(lista[i : i+2]))
print(i, i+1)
Prints 3 4.

Index position of an element

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))))

Print the indices of elements in one list according to the values of another list in seperate lines and print -1 for missing elements in python

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

Compare current column value to different column value by row slices

Assuming a dataframe like this
In [5]: data = pd.DataFrame([[9,4],[5,4],[1,3],[26,7]])
In [6]: data
Out[6]:
0 1
0 9 4
1 5 4
2 1 3
3 26 7
I want to count how many times the values in a rolling window/slice of 2 on column 0 are greater or equal to the value in col 1 (4).
On the first number 4 at col 1, a slice of 2 on column 0 yields 5 and 1, so the output would be 2 since both numbers are greater than 4, then on the second 4 the next slice values on col 0 would be 1 and 26, so the output would be 1 because only 26 is greater than 4 but not 1. I can't use rolling window since iterating through rolling window values is not implemented.
I need something like a slice of the previous n rows and then I can iterate, compare and count how many times any of the values in that slice are above the current row.
I have done this using list instead of doing it in data frame. Check the code below:
list1, list2 = df['0'].values.tolist(), df['1'].values.tolist()
outList = []
for ix in range(len(list1)):
if ix < len(list1) - 2:
if list2[ix] < list1[ix + 1] and list2[ix] < list1[ix + 2]:
outList.append(2)
elif list2[ix] < list1[ix + 1] or list2[ix] < list1[ix + 2]:
outList.append(1)
else:
outList.append(0)
else:
outList.append(0)
df['2_rows_forward_moving_tag'] = pd.Series(outList)
Output:
0 1 2_rows_forward_moving_tag
0 9 4 1
1 5 4 1
2 1 3 0
3 26 7 0

A loop for adding list element without high memory performance?

Everybody,
a =[0, 0, 2, 4, 6]
x=5
This a list (a) and a fix value (x).
I need a loop codes which must add with x every element of list and add this value with previous list elements in every loop ( loop must continue as x value). Other words result should like below:
0
0
2
4
6
0
0
7
9
11
0
0
12
14
16
0
0
15
19
21
0
0
21
24
26
I prepared codes as below but it doesn’t work. Other words produce something as below (incorrect)
i=0
counter=0
while counter < x:
for i in a:
if i >0:
i=i+x
elif i ==0:
i=0
print i
counter=counter+1
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
0
0
7
9
11
So, I need to help for this…
Thank you.
I think this does mostly what you want (at least, as I understand the question)...
def make_it_so(a, x):
i = 0
counter=0
while counter < x:
for i in a:
if i == 0:
yield 0
else:
yield i + counter * x
counter = counter + 1
# Demo
for item in make_it_so([0, 0, 2, 4, 6], 5):
print item
Note that I've made it a generator function. You could easily turn it into a regular function that returns a list if you created an output list at the top of the function and swapped yield ... for output_list.append(...) and then return output_list at the end of the function...
The key here is to understand that in the first loop, you are adding 0 to all of the (non-zero) items. In the second loop, you are adding x. In the third loop, you're adding the x + x (since the first loop added x and now you're adding x more). In general, for the Nth loop, you'll be adding (N-1) * x to all of the non-zero items. So, you just need to keep track of N, (or N-1). In fact, your original code was already doing this (with counter), so we just re-purpose that and it's all good.
You need to change the values in a, not just add to the numbers you get out of a (because you'll keep getting the same ones out). Also, you need to print out the original values.
def process(x, memo):
return [n+x if n else n for n in memo]
res = a
memo = a
for _ in range(x - 1):
memo = process(x, memo)
res.extend(memo)

Categories