In one of the review questions, we discussed creating nested for-loops in order to list out all possible combinations of (x, y) values for a given range of numbers. Somebody pointed out that this would indeed generate some duplicates--e.g., (0, 9) and (9, 0) could be considered exactly the same.
In this question, you'll replicate the double-for loop for a range of numbers, but you'll only generate a range of unique pairwise combinations. This is exactly what itertools.combinations(list, 2) does, but you'll implement it yourself. For example, the list [1, 2, 3] should return [ (1, 2), (1, 3), (2, 3) ] (the ordering of the internal tuple pairs doesn't matter).
Put your answer in the list_of_pairs variable.
In [ ]:
def my_pairs(x):
list_of_pairs = []
### BEGIN SOLUTION
### END SOLUTION
return list_of_pairs
In [ ]:
try:
combinations
itertools.combinations
except:
assert True
else:
assert False
In [ ]:
from itertools import combinations as c
i1 = [1, 2, 3]
a1 = set(list(c(i1, 2)))
assert a1 == set(my_pairs(i1))
i2 = [8934, 123, 23, 1, 6, 8, 553, 8, 98.345, 354, 876796.5, 34]
a2 = set(list(c(i2, 2)))
assert a2 == set(my_pairs(i2))
This question is a straight-up rip-off from one of the lecture review questions. In the code below, you'll be given a matrix in list-of-lists format. You'll need to iterate through the matrix and replace each row list with a tuple, where the first element of the tuple is the row index, and the second element is the original row list.
For example, if the input matrix list-of-lists is
x = [ [1, 2, 3], [4, 5, 6] ]
then the output should be
y = [ (0, [1, 2, 3]), (1, [4, 5, 6]) ]
In other words, y[0] would give the tuple (0, [1, 2, 3]), and y[1] would give (1, [4, 5, 6]).
Put your answer in the tuple_matrix variable.
In [ ]:
def add_row_ids(matrix):
tuple_matrix = []
### BEGIN SOLUTION
### END SOLUTION
return tuple_matrix
In [ ]:
i1 = [ [1, 2, 3], [4, 5, 6] ]
a1 = set((1, (4, 5, 6)))
i, t = add_row_ids(i1)[1]
assert a1 == set((i, tuple(t)))
i2 = [ [1, 2], [2, 3], [4, 5], [6, 7], [8, 9] ]
a2 = set((4, (8, 9)))
i, t = add_row_ids(i2)[4]
assert a2 == set((i, tuple(t)))
You could solve Part B in one of several different ways--some combination of range, zip, and enumerate, either just one, or two, or even all three. Regardless of how you solved Part B, describe in words (and pseudocode if you'd like) how you could condense the entirety of Part B into a list comprehension statement, using one or more of the aforementioned iterating tools.