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.
Related
This question already has an answer here:
How to get combinations of elements from a list?
(1 answer)
Closed 4 years ago.
Let's say I have a list of four values. I want to find all combinations of two of the values. For example, I would like to get an output like:
((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3))
As you can see, I do not want repetitions, for example (0, 1) and (1, 0)
This needs to be able to be used with larger numbers, not just 4, and I will have to iterate through all of the combos
I am using Python 3 and Windows, and this would ideally be an inbuilt function, a simple bit of list comprehension code, or something I can import. I have tried making this with range, but I do not know how to exclude the numbers that I have already done from it.
It is very easy
from itertools import combinations
list(combinations([0,1,2,3],2))
Take just the lower triangular matrix if you only need a distinct set
a = [1,2,10,20]
[(a[i], a[j+i+1]) for i in range(len(a)) for j in range(len(a[i+1:]))]
[(1, 2), (1, 10), (1, 20), (2, 10), (2, 20), (10, 20)]
This question already has answers here:
Get all pairwise combinations from a list
(2 answers)
Closed 2 years ago.
I would like to get all the possible couples of elements from a list like the following :
L = [1, 2, 4, 5]
--> couples = [(1, 2), (1, 4), (1, 5), (2, 4), (2, 5), (4, 5)]
I do not want symetric couples like (1, 2), (2, 1) and I do not want couples with same numbers either like (1, 1)
If you guys could tell me the best way to do it I would be super glad !
A simple way of getting combinations
def getPairs(inList):
outList = []
for i in range(len(inList)):
item = inList[0]
inList = inList[1:]
for j in inList:
outList.append((item, j))
return outList
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) ), ... }
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 5 years ago.
Improve this question
I really want to know how to extract all the element from two lists and multiply each other. For example, if there are two lists
A=[1,3,5,7,9]
B=[2,4,6,8]
I want to do 1X2, 1X4, 1X6, 1x8, 3x2... etc.
One element from A X one element from B.
I tried to use zip but because of length difference, I couldn't get right answers.
SInce your question seems to want the cartesian product between two lists, you can use itertools.product to bind every element from A with every element from B:
>>> from itertools import product
>>> A = [1,3,5,7,9]
>>> B = [2,4,6,8]
>>> list(product(A, B))
[(1, 2), (1, 4), (1, 6), (1, 8), (3, 2), (3, 4), (3, 6), (3, 8), (5, 2), (5, 4), (5, 6), (5, 8), (7, 2), (7, 4), (7, 6), (7, 8), (9, 2), (9, 4), (9, 6), (9, 8)]
Then if you want to multiply the the two elements in each tuple, you can do this:
>>> [x * y for x, y in product(A, B)]
[2, 4, 6, 8, 6, 12, 18, 24, 10, 20, 30, 40, 14, 28, 42, 56, 18, 36, 54, 72]
To get a random value from a list, you can do something similar to the following:
import random
lst = [10,20,30]
x = random.choice(lst)
Importing the random library gives you access to a ton of random generation tools. Per the random library documentation (https://docs.python.org/3/library/random.html), random.choice(seq) returns a random element from a non-empty sequence, such as a list. Thus, the code above randomly selects an element from lst and assigns that value to the variable x.
I don't want to give the solution away until you've tried using the random library, so I'll let you figure out how to use the information above.
You can use for loops:
Operation for each item in A with each item in B:
A=[1,3,5,7,9]
B=[2,4,6,8]
C = [] #Create an empty list
for i in A: #iter each element in A
for j in B: #iter each element in B
mult = i * j
C.append(mult) #Append the result in the list C
print(C)
Operation with a random item in A with each item in B:
import numpy as np
A=[1,3,5,7,9]
B=[2,4,6,8]
C = [] #Create an empty list
for i in A: #iter each element in A
i = np.random.randint(len(A)) #Chose a random number from A
for j in B: #iter each element in B
mult = A[i] * j #Multiply a random number from A with each element in B
C.append(mult) #Append the result in the list C
print(C)
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.