Finding unique combinations of tuples - python-3.x

Input: 1 2 3 4
Output: (1,2)(3,4)
(1,3)(2,4)
(1,4)(2,3)
I have been able to come up with a solution for the problem but it is efficient. It needs to be optimized.
comb = combinations(Arr,int(n/2))
l = []
for i in comb:
l.append(i)
final_comb = combinations(l,int(n/2))
for i in final_comb:
if is_unique(n,i):
print(i)
def is_unique(n,tup):
k = []
for i in tup:
for j in i:
k.append(j)
if len(set(k)) == n:
return True
return False
The output must be combinations of tuples such that they all have the numbers given as input

Use itertools
from itertools import combinations
list(combinations([1, 2, 3, 4], 2))
>>> [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Related

Making a list of tuples from prime factorization output for any value?

How do I turn the resulting tuple into a list of tuples containing the prime numbers and how many times it appers. I've tried tuples = tuple(2, factors.count(2)) and then doing the same for other numbers and then do list(zip(list1,list2) but that would just hard code the output:
E,g
In: 288
Out: [(2, 5), (3, 2)]
def prime_factors(n):
i = 2
factors = []
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
tuple1 = tuple(factors)
return tuple1
n = int(input())
print(prime_factors(n))
You need collections.Counter.
import collections
list(collections.Counter((2,2,2,3,4)).items())
gives
[(2, 3), (3, 1), (4, 1)]

Get different sets of numbers with repetition

I have a list of numbers:
lst = [1, 2, 3, 1,4]
def permutation(lst):
# If lst is empty then there are no permutations
if len(lst) == 0:
return []
# If there is only one element in lst then, only
# one permuatation is possible
if len(lst) == 1:
return [lst]
# Find the permutations for lst if there are
# more than 1 characters
l = [] # empty list that will store current permutation
# Iterate the input(lst) and calculate the permutation
for i in range(len(lst)):
m = lst[i]
# Extract lst[i] or m from the list. remLst is
# remaining list
remLst = lst[:i] + lst[i + 1:]
# Generating all permutations where m is first
# element
for p in permutation(remLst):
l.append([m] + p)
return l
if __name__ == "__main__":
lst = [1, 2, 3, 1,4]
v_out = permutation(lst)
print(v_out)
I am only getting permutations of 4 length, I want permutatins of all lengths, and only distinct permutations. But within each permutation, repetition is allowed.
This should work... Using the permutations function from itertools and making a set out of everything to prevent duplicates from being added to the overall result
In [20]: from itertools import permutations
In [21]: a = [1, 1, 2, 3]
In [22]: all_results = set()
In [23]: for i in range(1, len(a)):
...: all_results.update(set(permutations(a, i)))
...:
In [24]: all_results
Out[24]:
{(1,),
(1, 1),
(1, 1, 2),
(1, 1, 3),
(1, 2),
(1, 2, 1),
(1, 2, 3),
(1, 3),
(1, 3, 1),
(1, 3, 2),
(2,),
(2, 1),
(2, 1, 1),
(2, 1, 3),
(2, 3),
(2, 3, 1),
(3,),
(3, 1),
(3, 1, 1),
(3, 1, 2),
(3, 2),
(3, 2, 1)}
In [25]:

How to add the values according to subject

strong textLet's we have a list :
testList1 = [("Sita_English", 1), ("Sita_Maths", 2), ("Ram_English", 3), ("Ram_Maths", 4), ("Shyam_English", 5)]
I have added the values by name:
out2 = list(map(lambda v:(v[0], sum(map(lambda s: s[1], v[1]))), groupby(testList1, key=lambda x: x[0].split('_')[0])))
And i got this as a output:
[('Sita', 3), ('Ram', 7), ('Shyam', 5)]
Now i want to have a Output Like:
[('English', 9), ('Maths', 6)]
Using collections.defaultdict
Ex:
from collections import defaultdict
testList1 = [("Sita_English", 1), ("Sita_Maths", 2), ("Ram_English", 3), ("Ram_Maths", 4), ("Shyam_English", 5)]
out = defaultdict(int)
out2 = defaultdict(int)
for i, v in testList1:
name, lang = i.split("_")
out2[name] += v
out[lang] += v
print(out2) #out2.items() for list of tuples
print(out) #out.items() for list of tuples
Output:
defaultdict(<type 'int'>, {'Sita': 3, 'Ram': 7, 'Shyam': 5})
defaultdict(<type 'int'>, {'Maths': 6, 'English': 9})
As requested by OP
out2 = list(map(lambda v:(v[0], sum(map(lambda s: s[1], v[1]))), groupby(sorted(testList1, key=lambda x: x[0].split("_")[1]), key=lambda x: x[0].split('_')[1])))
#-->[('English', 9), ('Maths', 6)]

How to make 3 pairs of sub-lists from a Python list

In Python is there a way to get all 3 pairs or n pairs of a list from a list?
For example list = [1,2,3,4]
result : [[1,2,3],[2,3,4],[1,2,4]]
I want to find all possible n pairs of lists from a Python list. I do not want to import any other functions like itertools.
You can use the module itertools. It comes inside Python by default (you don't need to install it throught third party modules):
>>> import itertools
>>> print(itertools.permutations([1,2,3,4], 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]
This itertools.permutations(iterable, r=None) produces all the possible permutations of a given iterable element (like a list). If r is not specified or is None, then r defaults to the length of the iterable and all possible full-length permutations are generated.
If you are looking only for n pair of permutations instead of all the possible permutations just delete the rest of them:
>>> print(list(itertools.permutations([1,2,3,4], 3))[:3])
[(1, 2, 3), (1, 2, 4), (1, 3, 2)]
As you asked in comments you can do that without importing any module. itertools.permutations is just a function, which you can make by yourself:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
But I strongly advise your importing it. If you don't want to import the whole module, just this function simply do from itertools import permutations.

counting the number of each word in a dictionary

I am trying to fix this code:
def word_counter (input_str):
input_str1 = input_str.lower()
word = 0
input_str2 = dict(enumerate(input_str1.split(), start=1))
if word in input_str2:
input_str2[word] += 1
else:
input_str2[word] = 1
return (input_str2)
word_count_dict = word_counter("This is a sentence")
print(sorted(word_count_dict.items()))
so that instead of the output just being:
[(0, 1), (1, 'this'), (2, 'is'), (3, 'a'), (4, 'sentence')]
it will instead return a count of HOW MANY OF EACH word in input_str as so:
[('a', 1), ('is', 1), ('sentence', 1), ('this', 1)]
any help would be appreciated
You can just use collections.Counter:
>>> from collections import Counter
>>> c = Counter('This is a a a sentence'.split())
>>> c
Counter({'a': 3, 'This': 1, 'is': 1, 'sentence': 1})
>>> c['a']
3
>>> c['This']
1
>>> c.items()
[('This', 1), ('a', 3), ('is', 1), ('sentence', 1)]

Resources