how to pair values from python list [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
list = [1,2,3,4]
I would like to get a result of below and store them in csv file. ( 6 rows total )
1,2
1,3
1,4
2,3
2,4
3,4
Is there a function to this or how can I accomplish and store this in csv file ?

itertools is your friend...
http://docs.python.org/2/library/itertools.html
>>> import itertools
>>> x = [1, 2, 3, 4]
>>> list(itertools.combinations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Use itertools.combinations. It's builtin in Python 2.6+.
import itertools
pairs = itertools.combinations(list, 2)

One option is to use itertools.permutations and a list comprehension:
>>> [(x, y) for x, y in itertools.permutations(mylist, 2) if x < y]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
The condition x < y ensures you only get the permutations where x is lower than y.
The better option is to use itertools.combinations(mylist, 2).

This is simple enough to do it yourself:
l=[1,2,3,4]
for i in range(0,len(l)):
for j in range (i+1,len(l)):
print l[i],l[j]
But solutions using itertools can be generalized much easier.

Related

Efficiently check if elements lie between closed intervals [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
I have a tuple x with elements as x = (2, 3, 4, 5). I also have another data structure that holds closed intervals with the number of elements equal to the number of elements in the tuple x, as y = ((2,3), (3.5, 4.5), (6, 9), (4, 7)).
Now, I can set up a nested loop and check if each element of x lies within the respective intervals in y. But the issue is that it takes too long for a tuple with 10000 elements. Although efficiency might not matter, I do want the code to run fast.
Note: By efficient I do mean time wise, where the code runs faster than any other 'obvious' solutions.
I was wondering if there was a more efficient way to do this using Python instead of the obvious nested loop? This seems to be only possible with the nested loops solution.
I don't have any code as I can not figure the question out. If I could have hints as to how to make it efficient then please provide them.
What about something like this
>>> x = (2, 3, 4, 5)
>>> y = ((2,3), (3.5, 4.5), (6, 9), (4, 7))
>>> def f(e):
... p, (q, r) = e
... return q <= p <= r
>>> list(map(f, zip(x,y)))
[True, False, False, True]
You can achieve this in linear time using one loop.
You only have to iterate once on both of the tuples, something like this:
x = (2, 3, 4, 5)
y = ((2,3), (3.5, 4.5), (6, 9), (4, 7))
for index, number in enumerate(x):
if number > y[index][1] or number < y[index][0]:
print(f'{number} is NOT in {y[index}')
else:
print(f'{number} is in {y[index]}')
the output is:
2 is in the interval (2, 3)
3 is NOT in the interval (3.5, 4.5)
4 is NOT in the interval (6, 9)
5 is in the interval (4, 7)
As i said, this solution will take O(n), instead of O(n^2)
Welcome to SO.
Although this is definitely not efficient for a small tuple, for a large one this will speed up the process greatly (from an O(n^2) solution to an O(n)). I hope this helps.
x = (2, 3, 4, 5)
y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7))
for a, b in enumerate(y):
if b[0] <= x[a] <= b[1]:
print(f'{x[a]} is in between {b}.')
else:
print(f'{x[a]} is not in between {b}')
For boolean values:
interval = lambda t, i: [b[0] <= t[a] <= b[1] for a, b in enumerate(i)]
x = (2, 3, 4, 5)
y = ((2, 3), (3.5, 4.5), (6, 9), (4, 7))
print(interval(x, y))
All within linear (O(n)) time! Thanks for reading and have a great day.

How to make a matrix from two arrays

I have two arrays:
import numpy as np
MC=np.array([1, 2, 3])
oo=np.array([4,5,6])
for i in range(0, len(MC)):
for j in range(0, len(oo)):
H[i,j]=(MC[i],oo[j])
print(oo)
print(H)
I want an output matrix like this and I get an error (list indices must be integers or slices, not tuple):
H=[[(1,4),(1,5),(1,6)],[(2,4),(2,5),(2,6)],[(3,4),(3,5),(3,6)]]
"I get an error" is quite unspecific. So you should provide more details. But I assume that you get a NameError since H is not defined anywhere before using it. But looking at you implementation I can't see how you would get the desired result anyway. If you generally don't know the length of the given arrays in advance you could try
H = []
for i in range(0, len(MC)):
H.append([])
for j in range(0, len(oo)):
H[-1].append((MC[i], oo[j]))
That should give you the desired output. Or in my opinion even better, particulary in terms of readability:
H = []
for mc_el in MC:
H.append([])
for oo_el in oo:
H[-1].append((mc_el, oo_el))
Or (inspired by nikoros' answer):
H = [[(MC_el, oo_el) for oo_el in oo] for MC_el in MC]
Instead of manually iterating the arrays, you can combine groupby and product from itertools, you can create the required list of list of tuples in List-Comprehension
>>> from itertools import groupby, product
>>> [list(product([k], oo)) for k,v in groupby(MC)]
[[(1, 4), (1, 5), (1, 6)], [(2, 4), (2, 5), (2, 6)], [(3, 4), (3, 5), (3, 6)]]

generating all permutations with all orderings and replacements in Python [duplicate]

This question already has an answer here:
Having problems with python permutations
(1 answer)
Closed 2 years ago.
How to generate all possible ordering of a set of elements in a list which:
generates all ordering (not only those with sorted order)
allows repetition
I know that using itertools.permutations(iterable[, r]) I can do the following:
import itertools
a = itertools.permutations([1,2])
list(a)
output:
[(1, 2), (2, 1)]
and also using the itertools.combinations_with_replacement(iterable, r):
import itertools
a = itertools.combinations_with_replacement([1,2],2)
list(a)
output:
[(1, 1), (1, 2), (2, 2)]
but what I want is a function which does the following:
a = function([1,2],2)
output:
[(1, 1), (1, 2), (2, 1), (2, 2)]
In other words, for a list of size n with distinct elements and a given input of r it could generate all possible n**r possible combinations
itertools.product([1,2],repeat=2)
I think...

Is there a way to get combinations for a set of tuples? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a set of tuples:
(1, 3, 6)
(5, 2, 4)
...
(8, 1, 9)
I can get combinations of middle (or first or last) values whose sum is below a certain value:
def func(tuples, maxVal):
values = [i[1] for i in tuples]
result = [seq for s in range(len(values), 0, -1) for seq in itertools.combinations(values, s) if sum(seq) <= maxVal]
print(result)
but i'd like to be able to keep track of which tuples the values came from, so instead of just returning sets of values with appropriate sum, i want to return whole tuples which those values came from. Not sure how to do that.
How about
from itertools import combinations
def func(tuples, maxVal):
return [seq for s in range(len(tuples), 0, -1)
for seq in combinations(tuples, s)
if sum(t[1] for t in seq) <= maxVal]
tuplesset = {(1, 3, 6), (5, 2, 4), (8, 1, 9)}
print(func(tuplesset, 4))
The printout from that is
[((1, 3, 6), (8, 1, 9)), ((5, 2, 4), (8, 1, 9)), ((1, 3, 6),), ((5, 2, 4),), ((8, 1, 9),)]
which seems to be correct.
The main differences between my routine and yours is that I leave out the values variable (the middle values in your tuples) and have the expression sum(t[1] for t in seq) rather than sum(seq) for summing the middle values of the tuples. I also broke your one long line into multiple shorter lines for legibility and to follow PEP8 better.
You could use a dictionary mapped to pairs if you really want to save the tuples instead of just saving the indices:
{(x, x, x) : ( (z,z,z), (y,y,y) ), ... }

Tuples - Python 2.7 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have been given a whole stack of data (900 tuples to be exact) within each of these tuples there are 12 elements stored.
I need to load the second element in the tuple.
How would I extract the second element from every all of the 900 tuples? Any help or suggestions how to do this would be appreciated.
t1 = (something here)
t2 = (something here)
.
.
.
t900= (something here)
l = [t1, t2 ,... ,t900]
a = [i[1] for i in l]
print a
Is this what you want? Tell me if it works.
...
yourTuples = [(....), (.....)]
result = []
for item in yourTuples:
result.append(item[1])
print result
Map over the list:
list_of_tuples = [(..., ...), (..., ...), ...]
second_elements = map(lambda x: x[1], list_of_tuples)
You can easily do that using a python package numpy
see the sample code below,
import numpy
initial_list = [(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), ]
array = numpy.array(initial_list)
print array[:,1]
If you have stack of data in list form, you can simply do this using zip:
lt=[(1,2,3),(4,5,6),(7,8,9)]
print zip(*lt)[1]
output:
(2, 5, 8)

Categories

Resources