Related
I am a beginner coder, and have been struggling with defining a function that would return all the permutations of a given array. My current code is:
def Permutations(array):
result = []
idx = 0
for element in array:
for number in range(len(array)):
if number != idx:
array[array.index(element)] = array[number]
result.append(array)
idx += 1
return result
For some reason, I get a value error when I run the code. What is the issue with the code, as it seems to be logical to me?
Thank you!
You can do something like this:
def Permutations(array):
result = []
for id1, el1 in enumerate(array):
a = [el1]
for id2, el2 in enumerate(array):
if id1 != id2:
a.append(el2)
result.append(a)
return result
In [1]: Permutations([1, 2, 3])
Out[1]: [[1, 2, 3], [2, 1, 3], [3, 1, 2]]
So what I changed here was:
use enumerate instead of keeping a variable to track index
keep separate list to construct a permutation then add it to the final set of permutations
I am newbie to Python programming language. And I am looking for How to get the indexes (line and column ) of specific element in matrix.
In other I way I want to do the same as this source code using lists.
myList=[1,10,54,85]
myList.index(54)
Best Regards
Here's a simple function which returns the coordinates as a tuple (or None if no index is found). Note that this is for 2D matrices, and returns the first instance of the element in the matrix.
(Edit: see hiro protagonist's answer for an alternative Pythonic version)
def find(element, matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == element:
return (i, j)
Or, if you want to find all indexes rather than just the first:
def findall(element, matrix):
result = []
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == element:
result.append((i, j))
return result
You can use it like so:
A = [[5, 10],
[15, 20],
[25, 5]]
find(25, A) # Will return (2, 0)
find(50, A) # Will return None
findall(5, A) # Will return [(0, 0), (2, 1)]
findall(4, A) # Will return []
a (in my opinion) more pythonic version of FlipTack's algorithm:
def find(element, matrix):
for i, matrix_i in enumerate(matrix):
for j, value in enumerate(matrix_i):
if value == element:
return (i, j)
in python it is often more natural to iterate over elements of lists instead of just the indices; if indices are needed as well, enumerate helps. this is also more efficient.
note: just as list.index (without a second argument) this will only find the first occurrence.
Since you say that you're a beginner, pardon me if you already know some of the below. Just in case I'll describe the basic logic you can use to write your own function or understand the other answers posted here better:
To access an element in a specific row of a list, for example, if you wanted to get the first element and save it in a variable:
myList=[1,10,54,85]
myvar = myList[0] # note that you access the first element with index 0
myvar now stores 1. Why index 0? Think of the index as an indicator of "how far away from the beginning of the list an element is." In other words, the first element is a distance of 0 from the start.
What if you have a multi-dimensional list like so?
multi = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
Now you think in terms of row and column (and of course you could have n-dimensional lists and keep going).
How to retrieve the 5? That is a distance of 1 row from the start of the list of rows and 2 columns away from the start of the sub-list.
Then:
myvar = multi[1][2]
retrieves the 5.
FlipTack's and hiro protagonist's functions wrap this logic in the nice compact procedures, which search the entire 2-dimensional list, comparing elements until the desired one is found, then returning a tuple of the indices or continuing to search for duplicate elements. Note that if your lists are guaranteed to sorted you can then use a binary search algorithm across rows and columns and get the answer faster, but no need to worry about that for now.
Hopefully this helps.
You can also add a tag to your function to search the occurrences of your input matrix/list.
For example:
If you input is 1D vector:
def get_index_1d(a = [], val = 0, occurrence_pos = False):
if not occurrence_pos:
for k in range(len(a)):
if a[k] == val:
return k
else:
return [k for k in range(len(a)) if a[k] == val]
Output:
a = [1,10,54,85, 10]
index = get_index_1d(a, 10, False)
print("Without occurrence: ", index)
index = get_index_1d(a, 10, True)
print("With occurrence: ", index)
>>> Without occurrence: 1
>>> With occurrence: [1, 4]
For 2D vector:
def get_index_2d(a = [], val = 0, occurrence_pos = False):
if not occurrence_pos:
for k in range(len(a)):
for j in range(len(a[k])):
if a[k][j] == val:
return (k, j)
else:
return [(k, j) for k in range(len(a)) for j in range(len(a[k])) if a[k][j] == val]
Output:
b = [[1,2],[3,4],[5,6], [3,7]]
index = get_index_2d(b, 3, False)
print("Without occurrence: ", index)
index = get_index_2d(b, 3, True)
print("With occurrence: ", index)
>>> Without occurrence: (1, 0)
>>> With occurrence: [(1, 0), (3, 0)]
Just wanted to throw another solution since I didn't see it above:
def find(matrix, value):
value_indexs = [ ( matrix.index(row), row.index(value) ) for row in matrix if value in row]
return value_indexs
Example:
matrix = [
[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9, 0]
]
find(matrix, 0)
Returns: [(0,0), (2,3)]
Write a function that takes a two-dimensional list (list of lists) of
numbers as argument and returns a list which includes the sum of each
column. Assume that the number of columns in each row is the same.
I know how to traverse a row in a multidimensional list but have been facing problem on how to traverse the column elements of a multidimensional list. I'm just a beginner with python. There's no logic I can come up with using for loop or any of the list manipulation methods. I haven't come across the advance topics of lambda or anything of that sort. Any help would be appreciated.
Transpose and sum each column:
In [1]: arr = [[1,2,3],
[4,5,6]]
In [2]: list(map(sum, zip(*arr)))
Out[2]: [5, 7, 9]
zip(*arr) gives you the columns:
In [3]: list(zip(*arr))
Out[3]: [(1, 4), (2, 5), (3, 6)]
Then mapping sum on each column gives you the sum for each.
If you prefer a list comp:
In [5]: [sum(col) for col in zip(*arr)]
Out[5]: [5, 7, 9]
def _sum_of_columns_sample_(sample_list):
cols = len(sample_list[0])
mylist = []
for c in range(cols):
column_sum = 0
for row in sample_list:
column_sum += row[c]
mylist.append(column_sum)
return mylist
That's not the most beautiful piece of code I've ever come up with, but it should do the trick. If you would use packages such as numpy, things get significantly easier.
a = [1,2,3]
b = [4,5,6]
res = []
for i in range(len(a)):
res.append(a[i] + b[i])
A 2 dimensional list can be expressed a list of lists. That is
>>> mylist = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
>>>len(mylist)
You can now create a sum using nested for loops. Note that this assumes that there are the same number of elements in each column.
mysum = [0, 0, 0, 0]
for i in range(len(mylist)):
for j in range(len(mylist[0])):
mysum[i] += mylist[i][j]
print mysum
If you want to make it more general (and allow for different sized columns) without having to create an explicit mysum list you can use the following code.
mysum = []
for i in range(len(mylist)):
total = 0
for j in range(len(mylist[i])):
total += mylist[i][j]
mysum.append(total)
print mysum
For a one dimensional list, the index of an item is found as follows:
a_list = ['a', 'b', 'new', 'mpilgrim', 'new']
a_list.index('mpilgrim')
What is the equivalent for a 2 or n dimensional list?
Edit: I have added an example to clarify:
If I have a 3 dimensional list as follows
b_list = [
[1,2],
[3,4],
[5,6],
[7,8]
],
[
[5,2],
[3,7],
[6,6],
[7,9]
]
Now lets say I want to identify a certain value in this list. If I know the index of the 1st and 2nd dimesion but don't know the zero-th index for the value I want, how do I go about finding the zero-th index?
Would it be something like:
target_value = 7
b_list[0].index(target_value)
With the output being an integer:
0
I don't know of an automatic way to do it, but if
a = [[1,2],[3,4],[5,6]]
and you want to find the location of 3, you can do:
x = [x for x in a if 3 in x][0]
print 'The index is (%d,%d)'%(a.index(x),x.index(3))
The output is:
The index is (1,0)
For two dimensional list; you can iterate over rows and using .index function for looking for item:
def find(l, elem):
for row, i in enumerate(l):
try:
column = i.index(elem)
except ValueError:
continue
return row, column
return -1
tl = [[1,2,3],[4,5,6],[7,8,9]]
print(find(tl, 6)) # (1,2)
print(find(tl, 1)) # (0,0)
print(find(tl, 9)) # (2,2)
print(find(tl, 12)) # -1
A multidimensional list is simply a list with more lists inside of it.
So its indices would be lists themselves.
a = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
print a.index([2, 3, 4])
# prints 1
list_2d = [[1,2],[3,4],[5,6]]
element = 1
index_row = [list_2d.index(row) for row in list_2d if element in row]
index_column = [row.index(element) for row in list_2d if element in row]
For multidimensional arrays:
def find(needle,haystack):
if needle == haystack: return []
# Strings are iterable, too
if isinstance(haystack,str) and len(haystack)<=1: return None
try:
for i,e in enumerate(haystack):
r = find(needle,e)
if r is not None:
r.insert(0,i)
return r
except TypeError:
pass
return None
ml = [[1,2,3],[4,5,6],[7,8,9]]
print find(2,ml)
ml = [3,[[1,2,3],[4,5,6],[7,8,9]]]
print find(2,ml)
ml = [[["ab", "bc", "cde"]]]
print find("d",ml)
There should be a better way to avoid the try/except block, but I could not find one:
In Python, how do I determine if an object is iterable?
You can use the following sample method too:
data = [[1, 1,2],[12,4],[6]]
def m_array_index(arr, searchItem):
for i,x in enumerate(a):
for j,y in enumerate(x):
if y == searchItem:
return i,j
return -1,-1#not found
print m_array_index(data, 6)
Or with all occurrences(sure code could be optimized - modified to work with generators and so on - but here is just a sample):
occurrences = lambda arr, val: tuple((i,j) for i,x in enumerate(arr) for j,y in enumerate(x) if y == val) or ((-1,-1))
print occurrences(data, 1) # ((0, 0), (0, 1))
print occurrences(data, 12) # ((1, 0),)
print occurrences(data, 11) # (-1, -1)
For n-dimensional recursive search, you can try something like this:
from copy import copy
def scope(word, list, indexes = None):
result = []
if not indexes:
indexes = []
for index, item in enumerate(list):
try:
current_index = indexes + [index]
result.append(current_index + [item.index(word)])
except ValueError:
pass
if type(item[0]) == type([]):
indexes.append(index)
result.extend(scope(word, item, copy(indexes)))
return result
And the result is:
>>> d_list = [['a', 'b', 'new', 'mpilgrim', 'new'], [['a', 'b', 'new', 'mpilgrim', 'new'], ['b', 'd', 'new', 'mpilgrim', 'new']]]
>>> word = 'mpilgrim'
>>> result = scope(word, d_list)
[[0, 3], [1, 0, 3], [1, 1, 3]]
Probably there are better ways to do it, but that is the one I figured out without getting any library.
EDIT:
Actually, it was not perfect and one library must be added. It's copy. Now it's ok.
If you want to find the list that has an item, the simplest way to do it is:
i = 4
index = b_list[0].index( filter(lambda 1D_list: i in index , b_list[0]) )
Or if you know there are more than one matches for the item, then you can do:
i = 4
indexes = []
for match in filter(lambda 1D_list: i in list, b_list[0]):
indexes.append(b_list[0].index(match))
None of this will raise any errors but they'll only work if there is no subarray. Go here for information about the functionality of filter.
list1 = [10, 20, [300, 400, [5000, 6000, [1, 6000, 2]], 6000, 500], 30, 40]
print(f'Your list is {list1}')
print('---------------------------------------------------------')
index = []
index_result=['6000 index is list1']
def try_this(list1, index):
for x, element in enumerate(list1):
if element == 6000:
index.append(x)
index_result.append(index[:])
index.pop()
elif type(element) == list:
index.append(x)
try_this(element, index)
index.pop()
print(try_this(list1, index))
print(index_result)
Does a direct way to do this exists?
if element in aList:
#get the element from the list
I'm thinking something like this:
aList = [ ([1,2,3],4) , ([5,6,7],8) ]
element = [5,6,7]
if element in aList
#print the 8
L = [([1, 2, 3], 4), ([5, 6, 7], 8)]
element = [5, 6, 7]
for a, b in L:
if a == element:
print b
break
else:
print "not found"
But it sounds like you want to use a dictionary:
L = [([1, 2, 3], 4), ([5, 6, 7], 8)]
element = [5, 6, 7]
D = dict((tuple(a), b) for a, b in L)
# keys must be hashable: list is not, but tuple is
# or you could just build the dict directly:
#D = {(1,2,3): 4, (5,6,7): 8}
v = D.get(tuple(element))
if v is not None:
print v
else:
print "not found"
Note that while there are more compact forms using next below, I imagined the reality of your code (rather than the contrived example) to be doing something at least slightly more complicated, so that using an block for the if and else becomes more readable with multiple statements.
(Note: this answer refers to the question text, not the example given in the code, which doesn't quite match.)
Printing the element itself doesn't make any sense, because you already have it in the test:
if element in lst:
print element
If you want the index, there's an index method:
if element in lst:
print lst.index(element)
And, on the off chance that you're asking this because you want to loop through a list and do things with both the value and the index, be sure to use the enumerate idiom:
for i, val in enumerate(lst):
print "list index": i
print "corresponding value": val
>>> aList = [ ([1,2,3],4) , ([5,6,7],8) ]
>>> element = [5,6,7]
if you only wish to check if the first element is present
>>> any(element==x[0] for x in aList)
True
to find the corresponding value
>>> next(x[1] for x in aList if element==x[0])
8
>>> aList = [ ([1,2,3],4) , ([5,6,7],8) ]
>>> for i in aList:
... if [5,6,7] in i:
... print i[-1]
...
8
[5, 6, 7] is not an item of the aList you show, so the if will fail, and your question as posed just doesn't pertain. More generally, the loop implied in such an if tosses away the index anyway. A way to make your code snippet work would be, instead of the if, to have something like (Python 2.6 or better -- honk if you need to work on different versions):
where = next((x for x in aList if x[0] == element), None)
if where:
print(x[1])
More generally, the expressions in the next and in the print must depend on the exact "fine grained" structure of aList -- in your example, x[0] and x[1] work just fine, but in a slightly different example you may need different expressions. There is no "generic" way that totally ignores how your data is actually structured and "magically works anyway"!-)
The code in your question is sort of weird. But, assuming you're learning the basics:
Getting the index of an element:
it's actually simple: list.index(element). Assuming of course, the element only appears once. If it appears more than once, you can use the extra parameters:
list.index(element, start_index): here it will start searching from start_index. There's also:
list.index(element, start_index, end_index): I think it's self explanitory.
Getting the index in a for loop
If you're looping on a list and you want to loop on both the index and the element, the pythonic way is to enumerate the list:
for index, element in enumerate(some_list):
# here, element is some_list[index]
Here, enumerate is a function that takes a list and returns a list of tuples. Say your list is ['a', 'b', 'c'], then enumerate would return: [ (1, 'a'), (2, 'b'), (3, 'c') ]
When you iterate over that, each item is a tuple, and you can unpack that tuple.
tuple unpacking is basically like this:
>>> t = (1, 'a')
>>> x, y = t
>>> t
(1, 'a')
>>> x
1
>>> y
'a'
>>>
One possible solution.
aList = [ ([1,2,3],4) , ([5,6,7],8) ]
element = [5,6,7]
>>> print(*[y for x,y in aList if element == x])
8