cycle through a list while skipping elements (python) - python

I'm trying to find a way of going through a loop of a single list skipping the first element each time.
so for example, if I have a list:
lst = [0,1,2,3,4,5,6]
and wish to use a for loop to cycle through all but the first element and stop at an arbitrary point. So if I wish to start at index 1 of lst and advance through a cycle of each element (excluding the first) I can use the following:
scd = [1,2,3,4,5,6]
out = []
for i in range (1,14+1):
if (i%len(lst)) not in scd:
continue
else:
out.append(lst[i%len(lst)])
print(out)
it returns a list with only 12 elements:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
The output that I'm trying to get is:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]
I know the issue is in using the continue in the for loop, but I'm struggling with a workaround that gets me the desired output.
Any help would be greatly appreciated. also if there's a more pythonic way of going about this problem, I'm all ears.
Thanks so much.

IIUC, you simply want to repeat the same list, right? How about this where you could concatenate lists using divmod:
num = 14
i,j = divmod(num, len(lst)-1)
out = lst[1:] * i + lst[1:1+j]
Output:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]

Related

Finding the indexes of a list

I have the following series and I am supposed to pinpoint with a loop the indices that contain exactly the value 6:
x=[1, 3, 2, 1, 1, 6, 4, 2]
results=[]
Upon making my code, however, I am getting the output none. What could be going wrong?
def throwing_6(x):
for index,throw in enumerate(x):
if throw==6:
results.append(index)
results
indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6])
print(indexes)
You forgot to return the results array at the end of the function.
def throwing_6(x):
for index,throw in enumerate(x):
if throw==6:
results.append(index)
return results;
indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6])
print(indexes)
You could also use a simple list comprehension with condition as follows:
def throwing_6(x):
return [i for i, v in enumerate(x) if v == 6]
Upon reading user feedback I found the solution see the code between two stars.
def throwing_6(x):
for index,throw in enumerate(x):
if throw==6:
results.append(index)
**return results**
indexes = throwing_6([1, 2, 6, 3, 6, 1, 2, 6])
print(indexes)

Python - How to find the longest sequence in a integer list of neighbor numbers

How I find the longest sub-list in list of number pairs that has the difference of 1.
So "number neighbors" could be element 1 and 2 or element 7 and 6.
If the list is [7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0],
Then the desired output should be 4. The sub-list would be then [7, 6, 5, 6].
This is what I have for now. The for loop formula is really broken and I don't know how to solve this.
list = [7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0]
sublist = []
for i in list:
if list[i] - list[i+1] == 1 or list[i] - list[i+1] == -1:
sublist.append(i)
print(sublist)
print(len(sublist))
more-itertools makes it simple:
from more_itertools import split_when
lst = [7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0]
print(max(split_when(lst, lambda x, y: abs(x - y) != 1), key=len))
Its best to break these types of problems up into their parts
the main problem here is to get all sequential sequences
def get_sequences_iter(an_array):
# start a new sequence with first value (or empty)
sequence = an_array[:1]
# check each index with the value that comes before
for idx in range(1,len(an_array)):
if an_array[idx] - an_array[idx-1] in {1,-1}:
# this is part of a run append it
sequence.append(an_array[idx])
else:
# run is broken
yield sequence
# start a new run
sequence = [an_array[idx]]
#capture final sequence
yield sequence
once you have this you can get all the runs in a list in O(n) time
sequences = get_sequences_iter([7, 1, 2, 5, 7, 6, 5, 6, 3, 4, 2, 1, 0])
for sequence in sequences:
print(sequence)
hopefully with this information you can figure out how to solve your actual question
but just in case
print(max(sequences,key=len))

Sum of every element in a list

So i have a list:
list1 = [[1, 3, 6, 8, 9, 9, 12], [1, 2, 3, 2, 1, 0, 3, 3]]
but you can also split it into two lists, if it make it any easier. All i have to do is sum every digit with every other digit. Like you know
first row:
1+1, 1+2, 1+3, 1+2, 1+1...
second:
3+1... etc.
first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]
w = [x + y for x, y in zip(first, second)]
I was trying to do it in this way. But it doesn't work*, any ideas?
*i mean its summing in a wrong way, instead of every possible digits with every possible, just the first one in 1st list with 1st in second list.
zip is getting only pairs that sit at the same index. You should instead have a double loop:
[x + y for x in first for y in second]
You can do it using itertools to get all possible pair then make a pair of sum list
import itertools
first = [1, 3, 6, 8, 9, 9, 12]
second = [1, 2, 3, 2, 1, 0, 3, 3]
res = itertools.product(first, second)
ress = [sum(pair) for pair in res]
print(ress)

For each element in array return whole array without this element

I want my code to return, for every element in array, this array but without this one element.
Example: for array numbers=[1,2,3] I want output "[2,3]","[1,3]","[1,2]"
I've used this code:
examp = [1, 2, 3, 4, 5]
for number in examp:
print(str(number) + " MAIN")
subExp = examp
subExp.remove(number)
print(subExp)
but this one outputs (word "MAIN" is used as information which element is right now "subtracted" from array):
1 MAIN
[2, 3, 4, 5]
3 MAIN
[2, 4, 5]
5 MAIN
[2, 4]
For this code above I would expect this:
1 MAIN
[2, 3, 4, 5]
2 MAIN
[1, 3, 4, 5]
3 MAIN
[1, 2, 4, 5]
4 MAIN
[1, 2, 3, 5]
5 MAIN
[1, 2, 3, 4]
It's probably some stupid mistake from my side, but as a beginner in this topic, I coudn't find answer anywhere, so if there's any better way to do it, please help
The issue is this line:
subExp = examp
Here subExp isn't a copy of examp, but rather just another pointer just like examp to the list [1, 2, 3, 4, 5]. So in each iteration of your for loop you remove one entry of the list.
You can replace that line with:
subExp = examp.copy()
which will make a shallow copy of examp. Although this works for flat lists, you'd get in trouble for nested lists. In general you want to use copy package's
subExp = copy.deepcopy(examp)
EDIT: If you don't need to do the print line, then itertools.combinations() is the way to go. See https://docs.python.org/2/library/itertools.html#itertools.combinations for more info
For these you can use itertools:
import itertools
list(itertools.combinations([1, 2, 3,4,5],4))
# [(1, 2, 3, 4), (1, 2, 3, 5), (1, 2, 4, 5), (1, 3, 4, 5), (2, 3, 4, 5)]
Iterate through the list, slicing out the current element:
examp = [7, False, "OOpS", 3.14159]
for i in range(len(examp)):
print(examp[:i] + examp[i+1:])
Output:
[False, 'OOpS', 3.14159]
[7, 'OOpS', 3.14159]
[7, False, 3.14159]
[7, False, 'OOpS']
You can create a range, then output arrays filtered by index
examp = [1, 2, 3, 4, 5]
for x in range(0, len(examp)):
print(f'iteration {x + 1} ->')
print([el for i, el in enumerate(examp) if i != x])
or using itertools
print(list(itertools.combinations(examp, len(examp) - 1)))

Python - How to add a single bracket to the beginning and end of a list

So I'm to return [[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]] using L = [1,2,3,4,5] as the starting list
Everytime I try using
a = [1
L.insert(0,a)
to get the first bracket or use
L.append(]}
to get the last bracket, I just get ... in the command prompt like it's an if/else statement.
I know I can use just L.extend(L) to get the 1,2,3,4,5 added at the end, but I'm not quite sure how to get the brackets in without adding a '' marks around them.
You are currently inserting L at an index in itself, hence the [...] syntax. Instead, use * to expand the list:
L = [1,2,3,4,5]
new_l = [L*2]
Output:
[[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]]
From the look of what you are asking I think you are confused on what the [] are. They denote the use of a list. So to get two of them, put the list in a list.
L=[1,2,3,4,5]
new_L=[L*2]
print(new_L)
Not sure why you are trying to alter the actual display, but:
L = [1, 2, 3, 4, 5]
L2 = L + L
L = [L2]
You can just nest L into a new list and then multiply L by the number of times you want to repeat it:
L = [ 1, 2, 3, 4, 5 ]
A = [ L * 2 ]
Should print
[[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]]

Categories