I am having an issue with last part of a code im creating. I am trying to, for example, make the list iterate to item 3 normally, but then check if the item is 3 and other condition (which doesn't matter right now), then change the index to iterate from example 10.
I made a lot of attempts but it doesn't seem to work.
li = [3, 8, 1, 2, 6, 2, 2, 3, 3, 5, 4, 5, 5, 4, 2, 1, 5, 5, 3, 5, 4, 6]
'''
HERE COMES OTHER CODE WHICH WORKS BASED ON THE ITERATION
'''
for i in range(0,len(li)):
print(i)
if i == 3: #along with other condition
def g(li):
global i
i = li[9]
g()
print(i)
Maybe if it wasn´t clear here, what i am looking for is when 3 and the other condition reach the condition, then it skip to the index 9 to keep iterating the rest of the script from 9 which would be the new value.
I am sure I have not got your question right. But while loop should be preferred here
i=0
while i<len(li):
if i == 3: #along with other condition
i = li[9]
print(i)
continue
i += 1
A simple way to do what you want is to set a flag if that condition is met and continue thru the skipped indices if that flag is true
li = [3, 8, 1, 2, 6, 2, 2, 3, 3, 5, 4, 5, 5, 4, 2, 1, 5, 5, 3, 5, 4, 6]
'''
HERE COMES OTHER CODE WHICH WORKS BASED ON THE ITERATION
'''
do_skip = False
for i in range(len(li)):
if i == 3: #along with other condition
do_skip = True
# don't skip past a certain point
if do_skip and i < 9:
continue
print(i)
Alternatively, you can use a while loop:
li = [3, 8, 1, 2, 6, 2, 2, 3, 3, 5, 4, 5, 5, 4, 2, 1, 5, 5, 3, 5, 4, 6]
'''
HERE COMES OTHER CODE WHICH WORKS BASED ON THE ITERATION
'''
i = 0
while i < len(li):
if i == 3: #along with other condition
i = 9
print(i)
# other loop operations go here
i += 1
Yet another way to do it:
li = [3, 8, 1, 2, 6, 2, 2, 3, 3, 5, 4, 5, 5, 4, 2, 1, 5, 5, 3, 5, 4, 6]
flag = True # Conditional Flag
for x, i in enumerate(li):
if x > 2 and not flag: break
if 3 > x or x > 8: print(x, "has a value of", i)
Related
Assume an unordered list of numbers, with duplicates being allowed. I want to patch all gaps or sudden jumps in it. Some examples:
def renum(arr):
# magic happens here
pass
renum(np.array([1, 1, 1, 2, 2, 2])) # already in correct shape
> [1, 1, 1, 2, 2, 2]
renum(np.array([1, 1, 2, 2, 4, 4, 5, 5, 5])) # A jump between 2 and 4
> [1,1, 2, 2, 3, 3, 4, 4, 4]
renum(np.array([1, 1, 2, 2, 5, 2, 2])) # A forward and backward jump
> [1,1, 2, 2, 3, 4, 4]
Finding gaps is easy, but I have a hard time when trying to renumber gaps followed by the same number multiple times when processing the sequence elementwise. I.e the attempt below fails because numbers can occur many times:
def renum(arr):
new_arr = np.zeros(len(arr))
prev_num = new_arr[0]
for idx, num in enumerate(arr):
diff = num - prev_num
if diff == 0 or diff == 1:
new_arr[idx] = num
else:
new_arr[idx] = prev_num + 1
prev_num = new_arr[idx]
return new_arr
renum(np.array([1, 1, 2, 2, 4, 4, 5, 5, 5]))
> [1, 1, 2, 2, 3, 4, 5, 5, 5] # should actually be [1, 1, 2, 2, 3, 3, 4, 4, 4]
Also I think this implementation is not very efficient..
Any ideas?
This seems to do the trick:
def renum(input_array):
diff = np.diff(input_array)
diff[diff != 0] = 1
return np.hstack((input_array[0], diff)).cumsum()
If I understood correctly, you want the differences between your values to be 0 if they are 0 in the original array. If they are non-zero, you want them to be 1. This happens in the first two lines. Now, you can use the first original element and the newly created differences to create a new array as described here.
So I’m trying to take a list like this:
[1, 2, 3, 8, 15, 4, 12, 8]
And whenever a number is larger than 9 or has two digits, that number has 10 subtracted from it, and 1 is added to the previous number in the list.
So the list would result into this:
[1, 2, 3, 9, 5, 5, 2, 8]
For now, i have something like:
for i in list:
If i in list>= 10
list[i] = list[i] - 10
list[i-1] = list[i-1] + 1
But I’m getting an error from this
Does anyone know how to do this?
We are enumerating the list and as your logic says, if we encounter a number that is bigger than 9, we substract it from 10 and we add 1 to the previous element.
my_list = [1, 2, 3, 8, 15, 4, 12, 8]
for index,item in enumerate(my_list):
if item > 9:
my_list[index] -= 10
if index > 0:
my_list[index-1] += 1
print(my_list) # [1, 2, 3, 9, 5, 5, 2, 8]
data = [1, 2, 3, 8, 15, 4, 12, 8]
count = 0
for item in data:
if item >= 10 :
data[count-1] += 1
data[count] -= 10
count += 1
Output:
[1, 2, 3, 9, 5, 5, 2, 8]
Here it is man, but this only handles if the first item is less than 10 because I did not make the logic for it to check if its the first item, it will crash if the first item in the list is greater than or equal to 10.
x = [1,2,3,8,15,4,12,8]
for i in range(0, len(x)):
if x[i] >= 10:
x[i] = x[i]-10
x[i-1] = x[i-1]+1
print(x)
the output will be
[1, 2, 3, 9, 5, 5, 2, 8]
I am trying modify a list. Currently, there is a list with random number and I would like to change the list which creates maximum number of increase between numbers. Maybe I worded badly. For example, if list is [2,3,1,2,1], I would modify into [1,2,3,1,2] since 1->2, 2->3 and 1->2 in an increase which gives total of 3 increasing sequence. Any suggestions?
I would approach your problem with this recursive algorithm. What I am doing is sorting my list, putting all duplicates at the end, and repeating the same excluding the sorted, duplicate-free list.
def sortAndAppendDuplicates(l):
l.sort()
ll = list(dict.fromkeys(l)) # this is 'l' without duplicates
i = 0
while i < (len(ll)-1):
if list[i] == list[i+1]:
a = list.pop(i)
list.append(a)
i = i - 1
i = i + 1
if hasNoDuplicates(l):
return l
return ll + sortAndAppendDuplicates(l[len(ll):])
def hasNoDuplicates(l):
return( len(l) == len( list(dict.fromkeys(l)) ) )
print(sortAndAppendDuplicates([2,3,6,3,4,5,5,8,7,3,2,1,3,4,5,6,7,7,0,1,2,3,4,4,5,5,6,5,4,3,3,5,1,2,1]))
# this would print [0, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 3, 4, 5, 3, 5, 3, 5]
I need to remove the duplicate occurrence of the 1st element in the list which is duplicate (present more than once) while preserving the order of the input list. For eg: for the input of
in = [2, 3, 4, 5, 3, 6, 4, 1]
output should be
out = [2, 3, 4, 5, 6, 4, 1]
I have tried below and is giving correct result , I just wanted to check with the community if there is a better or more pythonic solution to this
input = [2, 3, 4, 5, 3, 6, 4, 1]
first_dupe = None
for elem in input:
if input.count(elem) > 1:
first_dupe = elem
break
flg = True
new_list = []
for x in input:
if x != first_dupe or flg is True:
new_list.append(x)
if x == first_dupe:
flg = False
print(new_list)
If you just want to remove the first duplicate, you can create set, append elements to a new list if they are in the set while removing each element from the set as well. When an element is not seen, append the rest of the list.
This is fairly efficient if the duplicate is seen early, but has O(1) if the element is seen late.
x = [2, 3, 4, 5, 3, 6, 4, 1]
s = set(x)
out = []
for i,z in enumerate(x):
if z in s:
out.append(z)
s.remove(z)
else:
break
out += x[i+1:]
out
# returns:
[2, 3, 4, 5, 6, 4, 1]
You could keep track of what you have already used and check if the value is in there.
lst = [2, 3, 4, 5, 3, 6, 4, 1]
used = set([])
for i, x in enumerate(lst):
if x in used:
lst.pop(i)
break
used.add(x)
print(lst)
Also, don't give variables, or anything else, the same name as a keyword in python. input is already a built-in function.
This is my version of Chiheb Nexus' answer.
def find_dup(lst):
seen = set()
it = iter(lst)
for item in it:
if item not in seen:
seen.add(item)
yield item
else:
yield from it
lst = [2, 3, 4, 5, 3, 6, 4, 1]
list(find_dup(lst))
[2, 3, 4, 5, 6, 4, 1]
For the sorted list l = [1,1,1,1,1,2,2,2,3]
A 75% "threshold" is defined as pct_value = 0.75*sum(l)
I want to find the value at which the threshold is reached. In this given list, since cumsum(l) = array([ 1, 2, 3, 4, 5, 7, 9, 11, 14]), the threshond pct_value is crossed at the value l[-2]. I want to write a program that finds this value at which the threshold is reached.
My if-else condition isn't correct:
pct_value = 10.5
[i+i if i+i < pct_value else i for i in L]
Any suggestion would be appreciative to fix the condition.
So is this what you want?
def find_element(L):
pct = 0.75 * sum(L)
s = 0
for i, element in enumerate(L):
if s > pct:
break
else:
s += element
return L[i]
You can use a while loop to remove the trailing elements from a copy until you hit your target. This returns a copy of the list elements that satisfy the stated condition:
li=[ 1, 2, 3, 4, 5, 7, 9, 11, 14]
li_c=li[:]
while sum(li_c)>=sum(li)*.75:
li_c.pop()
print li_c
# [1, 2, 3, 4, 5, 7, 9]
To make that more efficient, you would use a deque:
from collections import deque
li_c=deque(li)
tgt=sum(li)*.75
while sum(li_c)>=tgt:
li_c.pop()
print li_c
# deque([1, 2, 3, 4, 5, 7, 9])
If you are just looking for the index, not a copy of the elements, you can also use a while loop to do that:
i=1
while i<len(li):
if sum(li[0:i+1])>=tgt:
break
else:
i+=1
print i, li[0:i], i-len(li)
# 7 [1, 2, 3, 4, 5, 7, 9] -2