Python: for-loop wrong output [duplicate] - python

This question already has answers here:
Removing elements from a List in Python
(3 answers)
Closed 6 years ago.
Can't understand why it missing some indexes in loop?
Index number 3 for example.
I just want to delete the unique elements this way. I know another one but I don't know what's wrong with this one (or me).
lst = [2, 7, 1, 9, 3, 5, 2, 1]
def check(lst):
result = lst
print(lst) #checking
for num in lst:
print("index:", num) #checking
print("num:", num) #checking
if lst.count(num) < 2:
print("count:", lst.count(num)) #checking
result.remove(num)
return(result)
print(check(lst))
Output
[2, 7, 1, 9, 3, 5, 2, 1]
index: 2
num: 2
index: 7
num: 7
count: 1
index: 9
num: 9
count: 1
index: 5
num: 5
count: 1
index: 1
num: 1
[2, 1, 3, 2, 1]

You're removing items from a list as you're iterating over it, which you shouldn't do.
(result = lst does NOT make a copy of lst; it creates a new name which refers to the same object.)
If you just want to remove duplicate elements, you can use a set (although you may lose your ordering):
lst = list(set(lst))

Related

Negative number in python list [duplicate]

This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 1 year ago.
items = [10, 5, -2, 23, 5, 6,7]
For i in items:
if i <= 5:
items.remove(i)
print(items)
Does anybody know why -2 is not taken into account in for loop? It works if the condition is i < 5 but -2 is passed over when the condition is <=
The answer is quite simple. If you change the object you are working with, it will restructure automatically. What is happening is the following:
Your starting list -> [10, 5, -2, 23, 5, 6, 7]
Step 0. First iteration of the loop (checks the first element of the list) -> 10 <= 5 False
Step 1. Second iteration of the loop (checks the second item in the list) -> 5 <= 5 True
Your current list -> [10, -2, 23, 5, 6, 7]
Step 2. Third iteration of the loop (checks the third item in the list) -> 23 <= 5 False
As you can see, when you removed the number 5, the -2 became the second item in the list. However, the for loop does not know this, and it will continue to search with the next values ​​thinking that it has already checked for -2, since it is now the second value in the list.
This is why it is not recommended to change objects while iterating with them.
Try to filter the list and create a new one.
numbers= [10, 5, -2, 23, 5, 6,7]
positive_numbers = [x for x in numbers if x > 0]

How to ignore numbers after specific number in the list/array in Python?

I'm stuck on this problem:
I was trying to return sum of list of numbers in the array ignoring sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.
Here are my test cases:
number_69([1, 3, 5]) --> 9
number_69([4, 5, 6, 7, 8, 9]) --> 24
number_69([2, 1, 6, 9, 11]) --> 14
I came up with something like:
def number_69(arr):
for num in arr:
if 6 not in arr and 9 not in arr:
return sum(arr)
return 0
i guess we stop adding when we see 6 and we start again when we see 9
def number_69(arr):
sum = 0
stop = False
for num in arr:
if num == 6:
stop = True
elif num == 9:
stop = False
elif stop is False:
sum = sum + num
return sum
print(number_69([2, 1, 6, 9, 11]))
Great name for a function BTW
def summer_69(arr):
toSum = True
sum = 0
for x in arr:
if toSum :
if(x == 6):
toSum = False
else :
sum += x
else :
if(x == 9):
toSum = True
return sum
Hope it is useful
Another attempt, using list.pop:
lst = [4, 5, 6, 7, 8, 9]
def summer_69(lst):
s = 0
while lst:
i = lst.pop()
if i == 9:
while i!=6:
i = lst.pop()
else:
s += i
return s
print(summer_69(lst))
Prints:
9
You can iteratively slice out the parts between the 6 and the 9 until there are no more pairs, then call sum on the remainder.
For 'slicing' we use the Python's index slicing, which works by giving a start index and an end index (which will not be included).
>>> [0, 1, 2, 3][1:3] == [1, 2]
True
>>> [0, 1, 2, 3][1:]
[1, 2, 3]
>>> [0, 1, 2, 3][:2]
[0, 1]
We find the locations of the first 6 and the first following 9 with list.index. We do have to make sure to only start looking for a 9 after the 6. This gives
def number_69(arr):
while 6 in arr:
index = arr.index(6)
arr = arr[:index] + arr[index + arr[index:].index(9) + 1:]
# +index because we are removing it from arr[index:]
# +1 because we don't want to include the 9 in the new list
return sum(arr)
Since we know that every 6 will be followed by a 9, there is no need to check whether there is a 9 in the list. Thus, this function will remove all 6-9 blocks and only then return the sum of the entire list.
If there is a 6 without an accompanying 9 this function will raise a ValueError. This can be solved by checking for a 9 anyways, but this has to be done after the index of the first 6. If no 9 is found, we also have to break out of the loop, since the 6 will not be removed.
def number_69(arr):
while 6 in arr:
index = arr.index(6)
if 9 in arr[index:]:
arr = arr[:index] + arr[index + arr[index:].index(9) + 1:]
# +index because we are removing it from arr[index:]
# +1 because we don't want to include the 9 in the new list
else:
break
return sum(arr)
def summer_69(arr):
pop = []
for i in arr:
if i <=9 and i>=6:
continue
else:
pop.append(i)
return pop

How to find the index of two similar numbers in an array? [duplicate]

This question already has answers here:
How to find the largest number(s) in a list of elements, possibly non-unique?
(9 answers)
Closed 3 years ago.
Here is my program,
item_no = []
max_no = 0
for i in range(5):
input_no = int(input("Enter an item number: "))
item_no.append(input_no)
for i in item_no:
if no > max_no:
max_no = no
high = item_no.index(max_no)
print (item_no[high])
Example input: 5, 6, 7, 8, 8
Example output: 8
How can I change my program to output the same highest numbers in an array and how do I find the index of the result in (item_no)?
Expected output: 8, 8
Expected index for the result in item_no: 3, 4
I would use max() to find the maximum values.
item_no = []
for i in range(5):
input_no = int(input("Enter an item number: "))
item_no.append(input_no)
m = max(item_no)
max_values = [i for i in item_no if i == m]
max_values_indexes = [i for i, j in enumerate(item_no) if j == m]
print(max_values)
print(max_values_indexes)
Output using 5, 6, 7, 8, 8 as input:
[8, 8]
[3, 4]
Just use a filter function to find all max elements and than a new list for the index.
items = []
for i in range(5):
no = int(input("Enter an item number: "))
items.append(no)
max_item = max(items)
highest = list(filter(lambda x: x==max_item, items))
index = [pos for pos, no in enumerate(items) if no == highest[0]]
print (highest)
print (index)
With the input of 5, 6, 7, 8, 8, you'll get
[8, 8]
[3, 4]

how to identify duplicate integers within a list, than minus each integer following the duplicate by one?

I am trying to solve an issue that I am currently running into. I want to have to have a list that is made up of only random integers. Then if i find a duplicate integer within this list i want to minus the rest of the list by one, after the second time the duplicate number appeared. Furthermore if a second pair of duplicate numbers are encountered, it should then minus the rest of the list by two, than if a third by three and etc.
But it should not affect the same duplicate number or any other duplicated number (that differs from the first) that is in the sequence.
For example
mylist = [0 1 2 3 4 5 6 2 8 5 10 11 12 1 14 15 16 17]
I want the end result to look like;
mylist = [0 1 2 3 4 5 6 2 7 5 9 10 11 1 12 13 14 15]
I have some rough code that I created to attempt this, but it will always minus the whole list including duplicated integers (the first pairs and any further pairs).
If someone can shed some light on how to deal with this problem i will be highly grateful!
Sorry forgot to add my code
a = [49, 51, 53, 56, 49, 54, 53, 48]
dupes = list()
number = 1
print (dupes)
while True:
#move integers from a to dupes (one by one)
for i in a[:]:
if i >= 2:
dupes.append(i)
a.remove(i)
if dupes in a:
a = [x - number for x in a]
print (dupes)
print(dupes)
if dupes in a:
a = [x - number for x in a]
number = number+1
break
Forgot to mention earlier, me and friend are currently working on this problem and the code i supplied is our rough outline of what is should look like and now the end result, I know that it does now work so i decided to ask for help for the issue
You need to iterate through your list and when you encounter a duplicate(can use list slicing) then decrement the next item!
List slicing - example,
>>> L=[2,4,6,8,10]
>>> L[1:5] # all elements from index 1 to 5
[4, 6, 8, 10]
>>> L[3:] # all elements from index 3 till the end of list
[8, 10]
>>> L[:2] # all elements from index beginning of list to second element
[2, 4]
>>> L[:-2] # all elements from index beginning of list to last second element
[2, 4, 6]
>>> L[::-1] # reverse the list
[10, 8, 6, 4, 2]
And enumerate
returns a tuple containing a count (from start which defaults to 0)
and the values obtained from iterating over sequence
Therefore,
mylist=[0, 1, 2, 3, 4, 5, 6, 2, 8, 5, 10, 11, 12, 1, 14, 15, 16, 17]
dup=0
for index,i in enumerate(mylist):
if i in mylist[:index]:
dup+=1
else:
mylist[index]-=dup
print mylist
Output:
[0, 1, 2, 3, 4, 5, 6, 2, 7, 5, 8, 9, 10, 1, 11, 12, 13, 14]

python - How to move back an iteration in a for loop list [duplicate]

This question already has answers here:
Making a python iterator go backwards?
(14 answers)
Closed 6 years ago.
Given the list: a = [1, 2, 3, 4 5] in a for loop, suppose that the current item is 2, and next item is 3. If some condition is true, how can I make the next item be 2 again, which means the iteration should continue from 2 again instead of 3?
a = [1, 2, 3, 4, 5]
for item in a:
print item
if condition:
do something, and go back to previous iterator
The output would be:
1
2
2
3
4
5
Beware of an infinite loop, and it's not very Pythonic.
i = 0
a = [1, 2, 3, 4, 5]
hasBeenReset = False
while i < len(a):
if a[i] == 3 and not hasBeenReset:
i = 1
hasBeenReset = True
print(a[i])
i += 1

Categories