I need your help about a list - python

For example, I have a list like ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
In this list, I want to take elements that form () with 'A' elements.
This means, I want to take elements ('A', 'B') and ('A', 'C')
Not 'A', 'B' or ('C', 'D')
How can I get this?

l = ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
[x for x in l if type(x) == tuple and 'A' in x]

I would use a conditional list comprehension. I check if 'A' is in the list and if it is and the content isn't only A (hence the len check), then add it to the list.
temp = ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
results = [i for i in temp if 'A' in i and len(i) > 1]
print(results)

You can loop through like this:
new_lst = []
lst = ('A', 'B', 'C', 'D', ('A', 'B'), ('A', 'C'), ('C', 'D'))
for i in lst:
if len(i) > 1 and i[0] == "A":
new_lst.append(i)
print new_lst

Related

Attempting to build a loop to change one str out of 3 strs in python

My goal is to create 3 lists.
The 1st one is the input: choose 3 from ABCD to create AAA, ABC...etc
The 2nd one is the output: change the middle letter of each input and create a new list. eg: for AAA -> ABA,ACA,ADA. So 3 times the length of the input.
The third one is the Change: I want to name each change as c_i, for example, AAA->ABA is C1.
For Input,
>>> lis = ["A","B","C","D"]
>>> import itertools as it
>>> inp = list(it.product(lis, repeat = 3))
>>> print(inp)
[('A', 'A', 'A'), ('A', 'A', 'B'), ... ('D', 'D', 'C'), ('D', 'D', 'D')]
>>> len(inp)
64
But I am stuck on how to create the output list. Any idea is appreciated!
Thanks
You can use list comprehension:
import itertools
lst = ['A', 'B', 'C', 'D']
lst_input = list(itertools.product(lst, repeat=3))
lst_output = [(tup[0], x, tup[2]) for tup in lst_input for x in lst if tup[1] is not x]
lst_change = [f'C{i}' for i in range(1, len(lst_output) + 1)]
print(len(lst_input), len(lst_output), len(lst_change))
print(lst_input[:5])
print(lst_output[:5])
print(lst_change[:5])
# 64 192 192
# [('A', 'A', 'A'), ('A', 'A', 'B'), ('A', 'A', 'C'), ('A', 'A', 'D'), ('A', 'B', 'A')]
# [('A', 'B', 'A'), ('A', 'C', 'A'), ('A', 'D', 'A'), ('A', 'B', 'B'), ('A', 'C', 'B')]
# ['C1', 'C2', 'C3', 'C4', 'C5']
For each tuple in lst_input, the middle item is replaced by all the candidate characters, but the replacement is thrown out if that replacement character is the same as the original character (if tup[1] is not x).

Python - How to get all Combinations of names from a list: TypeError: 'list' object is not callable

I get an error when trying to print the permutation/combination of a user generated list of names.
I tried a couple of things from itertools, but can't get either permutations or combinations to work. Ran into some other errors along the way regarding concatenating strings, but currently getting a: TypeError: 'list' object not callable.
I know I'm making a simple mistake, but can't sort it out. Please help!
from itertools import combinations
name_list = []
for i in range(0,20):
name = input('Add up to 20 names.\nWhen finished, enter "Done" to see all first and middle name combinations.\nName: ')
name_list.append(name)
if name != 'Done':
print(name_list)
else:
name_list.remove('Done')
print(name_list(combinations))
I expect:
1) the user adds a name to list
2) the list prints showing user contents of list
3) when finished the user inputs "Done":
a) 'Done' is removed from the list
b) all the combinations of the remaining items on the list printed
Permutations and combinations are two different beasts. Look:
>>> from itertools import permutations,combinations
>>> from pprint import pprint
>>> l = ['a', 'b', 'c', 'd']
>>> pprint(list(combinations(l, 2)))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> pprint(list(permutations(l)))
[('a', 'b', 'c', 'd'),
('a', 'b', 'd', 'c'),
('a', 'c', 'b', 'd'),
('a', 'c', 'd', 'b'),
('a', 'd', 'b', 'c'),
('a', 'd', 'c', 'b'),
('b', 'a', 'c', 'd'),
('b', 'a', 'd', 'c'),
('b', 'c', 'a', 'd'),
('b', 'c', 'd', 'a'),
('b', 'd', 'a', 'c'),
('b', 'd', 'c', 'a'),
('c', 'a', 'b', 'd'),
('c', 'a', 'd', 'b'),
('c', 'b', 'a', 'd'),
('c', 'b', 'd', 'a'),
('c', 'd', 'a', 'b'),
('c', 'd', 'b', 'a'),
('d', 'a', 'b', 'c'),
('d', 'a', 'c', 'b'),
('d', 'b', 'a', 'c'),
('d', 'b', 'c', 'a'),
('d', 'c', 'a', 'b'),
('d', 'c', 'b', 'a')]
>>>
for use combinations , you need to give the r as argument.this code give all combinations for all numbers(0 to length of list),
from itertools import combinations
name_list = []
for i in range(0,20):
name = raw_input('Add up to 20 names.\nWhen finished, enter "Done" to see all first and middle name combinations.\nName: ')
name_list.append(name)
if name != 'Done':
print(name_list)
else:
name_list.remove('Done')
break
for i in range(len(name_list) + 1):
print(list(combinations(name_list, i)))
print("\n")

Create tuples from a list in Python

I have this array:
lst = ['A', 'B', 'C']
How could I append a string 'D' to each element and convert every set as a tuple:
lst2= [('A', 'D'),
('B', 'D'),
('C', 'D')]
Like this, using a list comprehension:
lst = ['A', 'B', 'C']
lst2 = [(x, 'D') for x in lst]
lst2
=> [('A', 'D'), ('B', 'D'), ('C', 'D')]
By the way, it's a bad idea to call a variable list, that clashes with a built-in function. I renamed it.
alternative solution is use zip_longest
from itertools import zip_longest
list(zip_longest(['A', 'B', 'C'], [], fillvalue='D'))
the result wiil be:
[('A', 'D'), ('B', 'D'), ('C', 'D')]
list2 = [(i, 'D') for i in list]
(apart from the fact that list is a very bad variable name)
Another option using zip:
x = ['A', 'B', 'C']
res = list(zip(x,'D'*len(x)))
list1 = ['A', 'B', 'C']
list2 = []
for i in list1:
list2.append((i, 'D'))
print(list2)
You can use the function product():
from itertools import product
lst = ['A', 'B', 'C']
list(product(lst, 'D'))
# [('A', 'D'), ('B', 'D'), ('C', 'D')]

All combinations of list wIthout itertools

I'm trying to make a recursive function that finds all the combinations of a python list.
I want to input ['a','b','c'] in my function and as the function runs I want the trace to look like this:
['a','b','c']
['['a','a'],['b','a'],['c','a']]
['['a','a','b'],['b','a','b'],['c','a','b']]
['['a','a','b','c'],['b','a','b','c'],['c','a','b','c']]
My recursive function looks like this:
def combo(lst,new_lst = []):
for item in lst:
new_lst.append([lst[0],item])
print([lst[0],item])
return combo(new_lst,lst[1:])
The right answer is that you should use itertools.combinations. But if for some reason you don't want to, and want to write a recursive function, you can use the following piece of code. It is an adaptation of the erlang way of generating combinations, so it may seem a bit weird at first:
def combinations(N, iterable):
if not N:
return [[]]
if not iterable:
return []
head = [iterable[0]]
tail = iterable[1:]
new_comb = [ head + list_ for list_ in combinations(N - 1, tail) ]
return new_comb + combinations(N, tail)
This a very elegant way of thinking of combinations of size N: you take the first element of an iterable (head) and combine it with smaller (N-1) combinations of the rest of the iterable (tail). Then you add same size (N) combinations of the tail to that. That's how you get all possible combinations.
If you need all combinations, of all lengths you would do:
for n in range(1, len(iterable) + 1):
print(combinations(n, iterable))
Seems that you want all the product of a list, you can use itertools.product within the following function to return a list of generators:
>>> from itertools import product
>>> def pro(li):
... return [product(l,repeat=i) for i in range(2,len(l)+1)]
...
>>> for i in pro(l):
... print list(i)
...
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]
[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')]

How to use itertools to compute all combinations with repeating elements? [duplicate]

This question already has an answer here:
Which itertools generator doesn't skip any combinations?
(1 answer)
Closed 8 years ago.
I have tried to use itertools to compute all combinations of a list ['a', 'b', 'c'] using combinations_with_replacement with repeating elements. The problem is in the fact that the indices seem to be used to distinguish the elements:
Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Combinations are emitted in lexicographic sort order. So, if the input
iterable is sorted, the combination tuples will be produced in sorted
order.
Elements are treated as unique based on their position, not on their
value. So if the input elements are unique, the generated combinations
will also be unique.
Sot this code snippet:
import itertools
for item in itertools.combinations_with_replacement(['a','b','c'], 3):
print (item)
results in this output:
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'c')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'c')
('c', 'c', 'c')
And what I need is the combination set to contain elements like: ('a', 'b', 'a') which seem to be missing. How to compute the complete combination set?
It sounds like you want itertools.product:
>>> from itertools import product
>>> for item in product(['a', 'b', 'c'], repeat=3):
... print item
...
('a', 'a', 'a')
('a', 'a', 'b')
('a', 'a', 'c')
('a', 'b', 'a')
('a', 'b', 'b')
('a', 'b', 'c')
('a', 'c', 'a')
('a', 'c', 'b')
('a', 'c', 'c')
('b', 'a', 'a')
('b', 'a', 'b')
('b', 'a', 'c')
('b', 'b', 'a')
('b', 'b', 'b')
('b', 'b', 'c')
('b', 'c', 'a')
('b', 'c', 'b')
('b', 'c', 'c')
('c', 'a', 'a')
('c', 'a', 'b')
('c', 'a', 'c')
('c', 'b', 'a')
('c', 'b', 'b')
('c', 'b', 'c')
('c', 'c', 'a')
('c', 'c', 'b')
('c', 'c', 'c')
>>>
For such small sequences you could use no itertools at all:
abc = ("a", "b", "c")
print [(x, y, z) for x in abc for y in abc for z in abc]
# output:
[('a', 'a', 'a'),
('a', 'a', 'b'),
('a', 'a', 'c'),
('a', 'b', 'a'),
('a', 'b', 'b'),
('a', 'b', 'c'),
('a', 'c', 'a'),
('a', 'c', 'b'),
('a', 'c', 'c'),
('b', 'a', 'a'),
('b', 'a', 'b'),
('b', 'a', 'c'),
('b', 'b', 'a'),
('b', 'b', 'b'),
('b', 'b', 'c'),
('b', 'c', 'a'),
('b', 'c', 'b'),
('b', 'c', 'c'),
('c', 'a', 'a'),
('c', 'a', 'b'),
('c', 'a', 'c'),
('c', 'b', 'a'),
('c', 'b', 'b'),
('c', 'b', 'c'),
('c', 'c', 'a'),
('c', 'c', 'b'),
('c', 'c', 'c')]

Categories

Resources