A sequence is said to be progressive if it doesn't decrease in time
E.g. 1 1 2 2 is a progressive sequence but 1 2 1 is not
Let S be the sequence and represented by L spaced integer Ki(where i =1,2,3.. L)now the task is to find the longest progressive sequence in S
a= int(input()) #length of the sequence
b=input() # sequence S
if(int(b[-1])>=int(b[-3])):
print(b)
else:
for i in range(a+2):
print(b[i],end='')
Output 1:
4
1 1 2 1
1 1 2
Output 2:
4
1 3 2 1
1 3 2(But correct answer is 1 3)
I think your code is too short to check for progressive sequences and works only for the one example you provided.
I'll give it a try:
# get some sequence here
seq = [1, 2, 4, 3, 5, 6, 7]
# store the first value
_v = seq[0]
# construct a list of lists
cnts = list()
# and store the first value into this list
cnt = [_v]
# iterate over the values starting from 2nd value
for v in seq[1:]:
if v < _v:
# if the new value is smaller, we have to append our current list and restart
cnts.append(cnt)
cnt = [v]
else:
# else we append to the current list
cnt.append(v)
# store the current value as last value
_v = v
else:
# append the last list to the results
cnts.append(cnt)
# get the longest subsequence
print(max(cnts, key=lambda x: len(x)))
Output:
[3, 5, 6, 7]
Related
So, I have data like this
Index c1
sls1 6
sls2 4
sls3 7
sls4 5
sls5 5
I want to find a collection of indexes provided that the value of column c2 on some indexes amounts to less than equal to 10 with looping. Then I save the index set as a list on a new data frame, which is output.
output = []
output
[sls1, sls2]
[sls3]
[sls4, sls5]
The first row is sls1, sls2 because the number of values from both indices is equal to 10, while the second row of sls3 only because the value of column c1 in index sls3 is 7 where if added up with the next index values will amount to more than 10. And so on
Thank You
There is no vectorized way to compute a cumulated sum with restart on a threshold, you'll have to use a loop.
Then combine this with groupby.agg:
def group(s, thresh=10):
out = []
g = 0
curr_sum = 0
for v in s:
curr_sum += v
if curr_sum > thresh:
g += 1
curr_sum = v
out.append(g)
return pd.Series(out, index=s.index)
out = df.groupby(group(df['c1']))['Index'].agg(list)
Output:
0 [sls1, sls2]
1 [sls3]
2 [sls4, sls5]
Name: Index, dtype: object
How to count number of values repeated in list at first position and do sum based on that
My input :
[[2, 1], [2, 1], [2, 1], [1, 2]]
Note : my list will contain 2 OR 1 in first index[0]
In above the 2 is repeated the maximum number of times so my sum should be like get its second value of all and do sum and display
2 , 1 -> 1 +
2 , 1 -> 1 +
2 , 1 -> 1
----------------------
2 , 3
So output would be : 2 , 3
How to achieve above output from given Input
In my code not able to implement such logic
cnt=0
m[0]=0
for m in my_list:
if m[0] == 2
cnt+=1
v=m[1]
print(m[0],v[1])
Try:
#create a list with just the 0th elements
keys = [i[0] for i in l]
#get the key that has the maximum count
max_key = max(keys, key=keys.count)
#sum the 1st element for all sublists where the 0th element is the same as the max_key
>>> max_key, sum(i[1] for i in l if i[0]==max_key)
(2, 3)
In one line (not recommended as it's not very readable):
>>> max([i[0] for i in l], key=[i[0] for i in l].count), sum(i[1] for i in l if i[0]==max([i[0] for i in l], key=[i[0] for i in l].count))
(2, 3)
Suppose we know 2 is the most common 1st item, here's a one liner list comprehension to make the sum:
[2, sum(x[1] for x in l if x[0]==2)]
# ^ ^ ^
# | | \-- if 1st item is 2
# | \-- extract 2nd item
# \-- sum all the 2nd items
To find the most common 1st item, we can use collections.Counter:
from collections import Counter
Counter(x[0] for x in l).most_common(1) # [(2, 3)]
Put everything together:
n = Counter(x[0] for x in l).most_common(1)[0][0]
[n, sum(x[1] for x in l if x[0]==n)] # [2, 3]
I am trying to reverse arrays in groups. I have wasted more than half an hour finding the problem but not able to figure out how is index is out of range.
Here is my code:
def rev(A,S,N):
start=S
end=N
while start<end:
A[start],A[end]=A[end],A[start] #error here
start+=1
end-=1
return A
def reverseInGroups(A,N,K):
#Your code here
rev(A,0,K)
rev(A,K,N) #error here
return A
Here is the error I am getting
Sample Input 1 : N=5 K=3 A= [1,2,3,4,5]
Sample Output 1 : 3 2 1 5 4
Sample Output 2 N= 8 K=3 A=[1,2,3,4,5,6,7,8]
Sample Output 2 : 3 2 1 6 5 4 8 7
For more information please visit this link
How about
def rev(a,start,end, middle):
assert 0 <= start <= middle <= end < len(a)
a[start:middle] = reversed(a[start:middle])
a[middle:end] = reversed(a[middle:end])
return a
There is no need to use / iterate positions at all - this avoids your error because slicing can handle oversized slices: [1,2,3,4][2:99] works w/o error.
def rev(data, start, end):
"""Reverses the range start:end (end exclusive) of the given list.
No safeguards whatsoever so only use with correct data. Out of bounds
is irrelevant due to slices used to reverse."""
data[start:end] = data[start:end][::-1] # you need end+1 if you want inclusive
return data
def reverseInGroups(A,N,K):
rev(A,0,K)
rev(A,K,N)
return A
l = list(range(11))
print ( reverseInGroups(l , 8, 3)) # why N (the bigger number) first?
to get
[2, 1, 0, 7, 6, 5, 4, 3, 8, 9, 10]
#0 1 2 3 4 5 6 7 8 9 10 # 0-3(exclusive) and 3-8(exclusive) reversed
To revere all K sized groups do
def reverseInGroups(A,K):
pos_at = 0
while pos_at < len(A):
rev(A, pos_at, pos_at+K)
pos_at += K
return A
I have:
hi
0 1
1 2
2 4
3 8
4 3
5 3
6 2
7 8
8 3
9 5
10 4
I have a list of lists and single integers like this:
[[2,8,3], 2, [2,8]]
For each item in the main list, I want to find out the index of when it appears in the column for the first time.
So for the single integers (i.e 2) I want to know the first time this appears in the hi column (index 1, but I am not interested when it appears again i.e index 6)
For the lists within the list, I want to know the last index of when the list appears in order in that column.
So for [2,8,3] that appears in order at indexes 6, 7 and 8, so I want 8 to be returned. Note that it appears before this too, but is interjected by a 4, so I am not interested in it.
I have so far used:
for c in chunks:
# different method if single note chunk vs. multi
if type(c) is int:
# give first occurence of correct single notes
single_notes = df1[df1['user_entry_note'] == c]
single_notes_list.append(single_notes)
# for multi chunks
else:
multi_chunk = df1['user_entry_note'].isin(c)
multi_chunk_list.append(multi_chunk)
You can do it with np.logical_and.reduce + shift. But there are a lot of edge cases to deal with:
import numpy as np
def find_idx(seq, df, col):
if type(seq) != list: # if not list
s = df[col].eq(seq)
if s.sum() >= 1: # if something matched
idx = s.idxmax().item()
else:
idx = np.NaN
elif seq: # if a list that isn't empty
seq = seq[::-1] # to get last index
m = np.logical_and.reduce([df[col].shift(i).eq(seq[i]) for i in range(len(seq))])
s = df.loc[m]
if not s.empty: # if something matched
idx = s.index[0]
else:
idx = np.NaN
else: # empty list
idx = np.NaN
return idx
l = [[2,8,3], 2, [2,8]]
[find_idx(seq, df, col='hi') for seq in l]
#[8, 1, 7]
l = [[2,8,3], 2, [2,8], [], ['foo'], 'foo', [1,2,4,8,3,3]]
[find_idx(seq, df, col='hi') for seq in l]
#[8, 1, 7, nan, nan, nan, 5]
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3
I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?
'a' is the list in my code
a = [1, 3, 2, 4, 3]
for i in a:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
Try:
for i in range(len(a)):
print(max(a[:i+1]))
print(max(a[i:]))
You are not iterating over the indices in your original code; and thus the partition does not make sense.
The only mistake in your code is the for i in a loop, which loops throgh i = 1,3,2,4,3 and not i=0,1,2,3,4
The following piece of code works
a=[1,3,2,4,3]
for i in range(len(a)) :
print max(i,max(a[:i+1]))
print max(i,max(a[i:]))
this may work... not fully tested but it looks correct
a = [1, 3, 2, 4, 3]
for i in a[:-1]:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
num = a[-1]
west = a[0:-1]
if max(west) > num:
print(max(west))
else:
print(str(a[-1]))
print(str(a[-1]))
Output: 1 4 3 4 4 4 4 3