This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I am working of Project Euler problem 2. I need to find the sum of all even Fibonacci numbers up to four million. I have a function that generates all possible Fibonacci numbers up to upperBound which is input by the user. I am passing this list of fibs to another function in order to eliminate the odd values. I am trying to iterate through the list and delete the element if it is odd. It is returning an error saying :
in evenFibs
del list_of_fibs[value]
IndexError: list assignment index out of range
Here is my code for evenFibs() :
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
for value in list_of_fibs:
if value % 2 != 0:
del list_of_fibs[value]
return list_of_fibs
I am not sure why this error is occuring.
Take a note that you shouldn't change array while iterating it, also to delete element from array you should use index of element, not value. You can get index of first element with specific value using index method of list. As for your task, it would be better to use list comprehension:
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
return [value for value in list_of_fibs if value % 2 == 0]
Related
This question already has answers here:
Finding median of list in Python
(28 answers)
Closed 3 years ago.
I have a problem that one of the things i need to include is a subscript of median, but i have no clue what that means
I have tried most things but again i have no clue what subscript of median means.
def median(a):
a=a.sort()
a=len(a)/2
return a
def main():
print(median([3,1,2]))
print(median([4,3,2,1]))
print(median([1,5,3,2,4]))
print(median([6,5,1,2,3,4]))
main()
I expect it to print out the median of the numbers if it gets two i need the lesser... We cant use average.
You're returning the middle index, not the value of the element at that index.
Also, a.sort() modifies the list in place, it doesn't return the sorted list; a = a.sort() sorts the list and then sets a to None.
def median(a):
s = sorted(a)
middle = int(len(s)/2)
return s[middle]
This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 4 years ago.
I'm supposed to find the largest number in a list, and then change all the elements of the list to that number. But when I print the output after the iteration, it still hasn't changed. What am I doing wrong please ?
Ar =[5,4,11]
ArMax = max(Ar)
for i in Ar:
i = ArMax
print(Ar)
The list doesn't change because you've done nothing to change the list. Your list is Ar -- where have you assigned a new value to anything in that list? Nowhere. All you did was to create a local variable to take on the values in Ar, and then change the value of that variable. You never touched the original list. Instead, you have to change the list elements themselves, not their copies. Keeping close to your present code:
for i in range(len(Ar)):
Ar[i] = ArMax
Another way would be to create a new list with those items in it, and simply replace the original list all at once:
Ar = [ArMax] * len(Ar)
This looks to see how long the current list is with len(Ar). Then it takes a one-element list with the max value and replicates it that many times. That new list becomes the new value of Ar.
i = ArMax does not actually assign values to the list because the values of i are copies of the elements in the list. If you want to fix this, try:
for i in xrange(len(Ar)):
Ar[i] = ArMax
This question already has an answer here:
Recursive code returns None [duplicate]
(1 answer)
Closed 6 years ago.
I want to search a Specific Value (an Integer) in a List in Python where the List could possibly have a Hierarchical Structure, So there could be a List on a Specific index (e.g [1,2,[[3,4],[5,6]] here the index 2 is a list it self and there could be a list in that again), and So on, or the index of Original List could have Integer values itself (e.g [1,2,3,[4,5]] in this case index 0 is an integer..
Eventually, I want the index of the searched value w.r.t original List , otherwise if searched value is not in the list, it should give me -1...I'm using recursion for that, but i'm not having the desired results...
Here's My Code
def search_in_list(L,c1):
index=-1
for i in range(len(L)):
if type(L[i])==list:
search_in_list(L[i],c1)
elif type(L[i])!=list:
if c1==L[i]:
index=i
return index
and here's an example List [1,2,[[3,4],[5,6]] So let's say i want to search 6, then it should give me 2 because that's the index of original list on which 6 is present, but i'm having -1 instead...
Can someone dig into my code and tell me the problem and solution...
Thanks in Advance
You can make some modifications to work correctly:
def search_in_list(l, needle):
for i, item in enumerate(l):
if type(item) == list:
# We found it, return current index
if search_in_list(item, needle) >= 0:
return i
else:
if needle == item:
return i
return -1
The main reason it didn't work was in the recursive call. When it returned that the item was found (by returning a non negative index) you didn't return the current index.
This question already has answers here:
Find the index of the second occurrence of a string inside a list
(3 answers)
Find the index of the n'th item in a list
(11 answers)
Closed 7 years ago.
If I'm working with a list containing duplicates and I want to know the index of a given occurrence of an element but I don't know how many occurrences of that element are in the list, how do I avoid calling the wrong occurrence?
Thanks
I don't know that a single builtin does this thing alone, but you could fairly easily write it, for instance:
def index_second_occurence(alist, athing):
if alist.count(athing) > 1:
first = alist.index(athing)
second = alist[first + 1::].index(athing)
return second + first + 1
else:
return - 1
This question already has answers here:
How to find the last occurrence of an item in a Python list
(15 answers)
Closed 8 years ago.
For example, I have a list
[0,2,2,3,2,1]
I want to find the index of the last '2' that appears in this list.
Is there an easy way to do this?
You can try the following approach. First reverse the list, get the index using L.index().
Since you reversed the list, you are getting an index that corresponds to the reversed, so to "convert" it to the respective index in the original list, you will have to substract 1 and the index from the length of the list.
n = ...
print len(L) - L[::-1].index(n) - 1