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.
Related
This question already has answers here:
Searching a sorted list? [closed]
(3 answers)
Closed 4 years ago.
I need to find the position of an index based on the existence of an value in a numerical array. I understand that I can use the .index(value) method for list but the thing is I don't want the code to exit or given None or any other type of exception if the value is not present in the array. Instead I would like to know the adjacent array indices values if the exact value is not present in the list. Hope the below example makes the problem statement clear.
arr = [10,20,30,40,50]
Input: 25
Output: 1,2
Input: 20
Output: 1
Basically the code returns the indices of the adjacent values in the array within which the search input is looked for.
For a non-numpy method, you can append your input variable to your list, sort it, and find the index where your input is found in the new list, and return that as well as the previous index:
arr = [10,20,30,40,50]
i = 25
i_index = sorted(arr+[i]).index(i)
>>> [i_index-1, i_index]
[1, 2]
Edit Based on your comment: if the value is already present in the array then I need just the exact index position of that value else I need the adjacent index values within which the value is falling into
You can wrap it in an if statement to check if your input is in your array already:
if i in arr:
idx = sorted(arr).index(i)
else:
i_index = sorted(arr+[i]).index(i)
idx = [i_index-1, i_index]
>>> idx
[1, 2]
This question already has answers here:
Python -Intersection of multiple lists?
(6 answers)
Closed 5 years ago.
say that I have a nested list like this for example:
List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]
and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.
here is what I have done so far:
def related(List):
for item in List[0]:
for i in range(1, len(List)):
if item in List[i]:
return item
the problem I am having is that when I do:
related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.
My function basically just stops running once it finds the same object in just 1 of the lists.
Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!
What you're looking for here is the intersection of these lists. Python lists don't have an intersection functionality built-in, but sets do. We can do
def in_common(l):
if not l:
return set()
return set(l[0]).intersection(*l[1:])
This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.
in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
returns
{'d'}
the set containing 'd'
This question already has answers here:
Removing Item From List - during iteration - what's wrong with this idiom? [duplicate]
(9 answers)
Closed 6 years ago.
I'm new to python and this may be a simple one line or one character answer but I can't seem to wrap my head around it. I have a list I want to iterate through and check if the element in the index after the current index is the same and delete it if it is.
while i < len(list):
if list[i] == list[i+1]:
del list[i];
i+=1;
I know the problem is coming from "if list[i] == list[i+1]:" when I get to end of the list "list[i+1]" will be out of range of the index. The problem is that I don't know how to stop the code when it gets to that point where it goes out of range
Firstly, list is the built-in function of python, so you should never use it for the name of your variables.
And to your problems itself. The fix for your error is simple:
while i < (len(_list) - 1):
if _list[i] == _list[i+1]:
del _list[i]
i+=1;
The reason for the IndexError is that at the last iteration i is already the last index and you are trying to get the element at the i+1 position.
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]
This question already has answers here:
Finding the index of an item in a list
(43 answers)
Closed 9 years ago.
I am trying to figure out how to determine if a tuple has an exact match in a list of tuples, and if so, return the index of the matching tuple. For instance if I have:
TupList = [('ABC D','235'),('EFG H','462')]
I would like to be able to take any tuple ('XXXX','YYYY') and see if it has an exact match in TupList and if so, what its index is. So for example, if the tuple ('XXXX','YYYY') = (u'EFG H',u'462') exactly, then the code will return 1.
I also don't want to allow tuples like ('EFG', '462') (basically any substring of either tuple element) to match.
Use list.index:
>>> TupList = [('ABC D','235'),('EFG H','462')]
>>> TupList.index((u'EFG H',u'462'))
1
I think you can do it by this
TupList = [('ABC D','235'),('EFG H','462')]
if ('ABC D','235') in TupList:
print TupList.index(i)