print the longest sequence of number in number list (python) - python-3.x

I have a list of number:
a=[2,3,4,5,1,3,2,4,5,6,2,6,7,5,2,7,5,6,2]
I want the longest sequence that not contain 2, so the answer is:
[3,4,5,1,3]
How can I do this in python?
Thanks for helping me,

You can use itertools.groupby():
from itertools import groupby
a = [2, 3, 4, 5, 1, 3, 2, 4, 5, 6, 2, 6, 7, 5, 2, 7, 5, 6, 2]
# get the subsequences not containing 2
subsequences = (list(it)
for contains_two, it in groupby(a, lambda x: x == 2)
if not contains_two)
# find the longest one among them
print(max(subsequences, key=len))
prints
[3, 4, 5, 1, 3]

Related

How to append item to match the length of two list in Python

I am working on a Python script which is connected to a server. Every x min, server returns two list but the length of these list is not same. For ex:
a = [8, 10, 1, 34]
b = [4, 6, 8]
As you can see above that a is of length 4 and b is of length 3. Similarly, sometimes it returns
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
I have to write a logic where I have to check if length of these two list is not same, then add the 0 at the end of the list which is smaller than other list. So for ex, if input is:
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
then output will be:
a = [3, 6, 4, 5, 0, 0]
b = [8, 3, 5, 2, 9, 3]
What can I try to achieve this?
def pad(list1, list2):
# make copies of the existing lists so that original lists remain intact
list1_copy = list1.copy()
list2_copy = list2.copy()
len_list1 = len(list1_copy)
len_list2 = len(list2_copy)
# find the difference in the element count between the two lists
diff = abs(len_list1 - len_list2)
# add `diff` number of elements to the end of the list
if len_list1 < len_list2:
list1_copy += [0] * diff
elif len_list1 > len_list2:
list2_copy += [0] * diff
return list1_copy, list2_copy
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
# prints: ([3, 6, 4, 5, 0, 0], [8, 3, 5, 2, 9, 3])
print(pad(a, b))
a = [8, 10, 1, 34]
b = [4, 6, 8]
# prints: ([8, 10, 1, 34], [4, 6, 8, 0])
print(pad(a, b))
For now, I can suggest this solution:
a = [3, 6, 4, 5]
b = [8, 3, 5, 2, 9, 3]
# Gets the size of a and b.
sizeA, sizeB = len(a), len(b)
# Constructs the zeros...
zeros = [0 for _ in range(abs(sizeA-sizeB))]
# Determines whether a or b needs to be appended with 0,0,0,0...
if sizeA < sizeB:
a += zeros
else:
b += zeros
print(a,b)
You should use extend instead of append. This is the way to add a list to another list in Python. The list here is the list of zeros.
a = [3, 6, 4, 5, 9, 3]
b = [8, 3, 5, 2]
lenA, lenB = len(a), len(b)
diff=abs(len(a)-len(b))
if lenA < lenB:
a.extend([0]*diff)
else:
b.extend([0]*diff)
print(a)
print(b)
You could also try to use more_itertools padded() method:
It's prob. more elegant and adaptable for future Use cases.
Notes: just need to do pip install more_itertools first.
# simple example to demo it:
from more_itertools import padded
print(list(padded([1, 2, 3], 0, 5))) # last num: 5 is the numbers of 0 to be padded to make the total length to be 5. (needs 2 zeros)
# [1, 2, 3, 0, 0]
# more examples:
>>> L = [1, 2, 3]
>>> K = [3, 4, 5, 6, 8, 9]
>>> gap = len(K) - len(L)
# 3
# shorter list is L
>>>list(padded(L, 0, len(L) + gap))
[1, 2, 3, 0, 0, 0]

How to find missing numbers from list in Python?

lst = [1, 4, 5, 9, 6]
How to write a code to get some missing values which must return [2, 3, 7, 8]?
Here is my code
new_list = []
for i in range(1, len(lst1)):
if i not in lst1:
new_list.append(i)
print(new_list)
You can convert them to sets and use "-" to calculate the difference. Note that the order is important.
You need to define what you want to compare your list to if you want to find the missing elements. You can automatically do this if it is simple like "the numbers from 1 to 10" using the code:
list(range(1, 10))
The comparison code is:
lst1 = [1, 4, 5, 9, 6]
lst2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
out = list(set(lst2) - set(lst1))
print(out)
which returns
[8, 2, 3, 7]
It isn't clear exactly what you want from your question, if you give a more detail it will be easier to help.

Python code to print elements from list that meet certain criteria [duplicate]

This question already has answers here:
Print an element in a list based on a condition
(3 answers)
Select value from list of tuples where condition
(4 answers)
How to return a subset of a list that matches a condition [duplicate]
(1 answer)
Closed 3 years ago.
I have a list with 22 integers (ranging from 1 through 9) and want to create/ print a new list containing only those integers that are above 5.
This is what I have tried so far - the result (obviously) is that 'the_list' gets printed multiple times - i.e. the number of times = the number of instances above 5.
the_list = [1, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7]
print(the_list)
k=5
tl2=[]
for i in the_list:
if i > k :
tl2.append(the_list)
Try this code:
>>> the_list = [1, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7]
>>> print(the_list)
[1, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7]
>>> the_filtered_list = list(filter(lambda x: x > 5, the_list))
>>> print(the_filtered_list)
[7, 6, 6, 7, 6, 6, 7]
See
filter
lambda
EDIT:
Another option is to use a generator expression:
>>> the_filtered_list = list(i for i in the_list if i > 5)
>>> print(the_filtered_list)
[7, 6, 6, 7, 6, 6, 7]
See
generator expressions and list comprehensions
EDIT:
My initial answer was indeed slow and memory inefficient. Here is the comparison of several possibilities. Which one to choose depends on how big the list is and what it is used for later.
>>> import random
>>> import timeit
>>> import sys
>>>
>>> the_list = [random.randrange(1, 10) for _ in range(100)]
>>>
>>> timeit.timeit('filter(lambda x: x > 5, the_list)', setup=f'the_list = {the_list}')
0.15890196000000856
>>> timeit.timeit('[i for i in the_list if i > 5]', setup=f'the_list = {the_list}')
2.633208761999981
>>> timeit.timeit('(i for i in the_list if i > 5)', setup=f'the_list = {the_list}')
0.227755295999998
>>>
>>> timeit.timeit('list(filter(lambda x: x > 5, the_list))', setup=f'the_list = {the_list}')
7.5565902380000125
>>> timeit.timeit('list(i for i in the_list if i > 5)', setup=f'the_list = {the_list}')
3.599053368
>>>
>>> sys.getsizeof(filter(lambda x: x > 5, the_list))
64
>>> sys.getsizeof([i for i in the_list if i > 5])
440
>>> sys.getsizeof((i for i in the_list if i > 5))
128
>>>
>>> sys.getsizeof(list(filter(lambda x: x > 5, the_list)))
480
>>> sys.getsizeof(list(i for i in the_list if i > 5))
480
The problem is you are appending the list, not the number 'i'
the_list = [1, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7]
print(the_list)
k=5
tl2=[]
# the_list refers to the entire list
# i is an element in the list
for i in the_list:
if i > k :
# append the number 'i' if it is greater than k
tl2.append(i)
print (t12)
the_list = [1, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 3, 4, 5, 6, 7]
print(the_list)
k=5
new_ls = [x for x in the_list if x >k]
print(new_ls)
try this solution

Finding elements in specific index between two lists using a function or other

How do I define a function where for a and b it would return 7 and 5
or a[0] and b[0] and a[4] and b[4]. The problem is the length of both lists could change at any time...
I've tried:
if a[0]== b[0]:
print(a[0])
but if the length of lists changes then it would eventually return a list Index out of range error.
Any help is much appreciated.
a = [7, 5, 9, 3, 5, 3, 6, 7, 8, 4, 3, 3, 4, 5]
b = [7, 3, 3, 5, 5, 2, 1, 5, 2, 5, 2, 9, 8, 6]
Zip two lizts with zip and iterate over it:
a = [7, 5, 9, 3, 5, 3, 6, 7, 8, 4, 3, 3, 4, 5]
b = [7, 3, 3, 5, 5, 2, 1, 5, 2, 5, 2, 9, 8, 6]
for a_i, b_i in zip(a, b):
if a_i == b_i:
print(a_i, b_i)
Out:
7, 7
5, 5
or define it as a fiunction:
def extract_matches(a, b):
result = []
for a_i, b_i in zip(a, b):
if a_i == b_i:
result.append((a_i, b_i))
return result
matches = extract_matches(a, b)
matches
Out:
[(7, 7), (5, 5)]
How the zip works. zip function always zips lists by shorter. It returns a generator, so you should iterate it:
list(zip([1,2,3], [1,2]))
Out:
[(1, 2), (1, 2)] # list of pairs
list(zip([], [1,2,3]))
Out:
[] # length of shorter is 0, so you get zero length list

How to sum an output in Python

The program below will create a list of 100 numbers chosen randomly between 1-10. I need help to then sum the list, then average the list created.
I have no idea how to begin and since I'm watching videos online I have no person to turn to. I'm very fresh in this world so I may just be missing entire ideas. I would doubt that I don't actually know enough though because the videos I paid for are step by step know nothing to know something.
Edit: I was informed that what the program does is overwrite a variable, not make a list. So how do I sum my output like this example?
This is all I have to go on:
Code:
import random
x=0
while x < 100:
mylist = (random.randrange(1,10))
print(mylist)
x = x+1
I think the shortest and pythonic way to do this is:
import random
x = [random.randrange(1,10) for i in range(100)] #list comprehension
summed = sum(x) #Sum of all integers from x
avg = summed / len(x) #Average of the numbers from x
In this case this shouldn't have a big impact, but you should never use while and code manual counter when you know how many times you want to go; in other words, always use for when it's possible. It's more efficient and clearer to see what the code does.
def sum(list):
sm = 0
for i in list:
sm+=i
return sm
Just run sum(list) to get sum of all elements
Or you can use
import random
x=0
mylist = []
sm = 0
while x < 100:
mylist.append(random.randrange(1,10))
sm += mylist[x]
x += 1
Then sm will be sum of list
The code is not correct. It will not create a list but generate a number everytime. Use the below code to get your desired result.
import random
mylist = []
for x in range(100):
mylist.append(random.randrange(1,10))
print(mylist)
print(sum(mylist))
OR
import random
mylist = [random.randrange(1,10) for value in range(100)]
print(mylist)
print(sum(mylist))
Output:
[3, 9, 3, 1, 3, 5, 8, 8, 3, 3, 1, 2, 5, 1, 2, 1, 4, 8, 9, 1, 2, 2, 4,
6, 9, 7, 9, 5, 4, 5, 7, 7, 9, 2, 5, 8, 2, 4, 3, 8, 2, 1, 3, 4, 2, 2,
2, 1, 6, 8, 3, 2, 1, 9, 6, 5, 8, 7, 7, 9, 9, 9, 8, 5, 7, 9, 4, 9, 8,
7, 5, 9, 2, 6, 8, 8, 3, 4, 8, 4, 7, 9, 9, 4, 2, 9, 9, 6, 3, 4, 9, 5,
3, 8, 4, 1, 1, 3, 2, 6]
512

Resources