Generating permutations of a given length - Python - python-2.7

I want to generate a list of permutations over a given alphabet of length n.
For example, if n = 3 and the alphabet includes {A,B}, output should be: AAA,AAB,ABA,BAA,ABB,BAB,BBA,BBB

I'm guessing from the desired output that you want to generate the cartesian product of an alphabet with itself repeated n times rather than a list of permutations. This admittedly tricky wrapper of itertools.product() will do the job just fine:
>>> import itertools
>>> def nprod(x, n):
... args = 'x' + (n-1)*', x'
... return [''.join(z) for z in eval('itertools.product(%s)' % args)]
...
>>> nprod('AB', 3)
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>> nprod(['1', '2', '3'], 2)
['11', '12', '13', '21', '22', '23', '31', '32', '33']
EDIT: Oh, silly me!!! I didn't notice in the documentation the optional repeat keyword argument :D
>>> [''.join(x) for x in itertools.product('AB', repeat=3)]
['AAA', 'AAB', 'ABA', 'ABB', 'BAA', 'BAB', 'BBA', 'BBB']
>>>> [''.join(x) for x in itertools.product(['1', '2', '3'], repeat=2)]
['11', '12', '13', '21', '22', '23', '31', '32', '33']

Related

Convert a file into a list with integers

with open('askhsh11.txt', 'r') as f:
raw_list = f.read().split('\n')
for i in range(len(raw_list)):
print raw_list[i].split(',')
for i in range(len(raw_list)):
raw_list[i]=int(i)
print raw_list
the result is :
['1', '2', '3', '4']
['5', '6', '7', '8']
[0, '5,6,7,8']
[0, 1]
but i want the result to be:
['1', '2', '3', '4']
['5', '6', '7', '8']
[1, 2, 3, 4]
[5, 6, 7, 8]
How i convert a list of strings into a integers?
you can use:
result = [int(c) for s in raw_list for c in s.split(',')]
output:
[1, 2, 3, 4, 5, 6, 7, 8]
you can just replace the "'" character to remove them
with open('askhsh11.txt', 'r') as f:
raw_list = f.read().replace("'","").split('\n')
numbers = [int(num) for num in raw_list]
To be honnest . i'm biginner in this langage . but i can tell you that you can use the 2 first output to generate the 2 second output .
what i mean that it's easy to convert
this :
['1', '2', '3', '4']
to this :
[1, 2, 3, 4] .
just use the function that convert the string like '1' to the integer 1 .
sorry i gorget its name but u find it on python support
for evryone who know the function's name .plz make a comment and thank you so much

Python: binary vector

I have a set of indices:
indices = (['1', '1.2', '2', '2.2', '3', '4'])
and a dataset, where the first element identifies a person, the second a round, and the third is the index from the indices set:
dataset = [['A', '1', '1'], ['A', '1', '1.2'], ['B', '1', '2'], ['C', '2', '3']]
I would like to form a binary vector, where for each person and for each individual round, the indices are marked either present (with a 1) or not (with a 0).
The desired output would be something like so, where for A, the vector represents the presence of the indices 1 and 1.2, for B, the index 2, and for C, the index 3. Note that for A, there is only one record, but 2 indices are present.
['A', '1', '1, 1, 0, 0, 0, 0']
['B', '1', '0, 0, 1, 0, 0, 0']
['C', '2', '0, 0, 0, 0, 1, 0']
I'm having a bit of trouble getting my head around the looping of the indices over the dataset. My idea was to loop through the indices set the same amount of time as the number of lists in the dataset. But I dont think this is the most efficient way, and any help would be appreciated!
I'd do it something like this:
from itertools import groupby
for k, g in groupby(dataset, lambda x: x[:2]):
vals = [x[2] for x in g]
print(k + [", ".join("1" if x in vals else "0" for x in indices)])
Output
['A', '1', '1, 1, 0, 0, 0, 0']
['B', '1', '0, 0, 1, 0, 0, 0']
['C', '2', '0, 0, 0, 0, 1, 0']
Is this what you were looking for?
Here's a solution without loops
import pandas as pd
indlist=['1', '1.2', '2', '2.2', '3', '4']
dataset = [['A', '1', '1'], ['A', '1', '1.2'], ['B', '1', '2'], ['C', '2', '3']]
df=pd.DataFrame(dataset,columns=['player','round','ind']).set_index('ind').reindex(indlist)
ans=df.reset_index().pivot('player','ind','round').fillna(0)[1:]

Creating a dictionary from list of lists

I have a list of lists in the following format:
[['a'],['1'],['2'],['3'], ['b'],['4'],['5'],['6']]
My desired output is:
[['a', '1'], ['a', '2'], ['a','3'],['b', '4'],['b', '5'],['b', '6']]
or even better would be:
{'a':['1','2','3'], 'b':['4','5','6']}
Essentially, the "number values" are never the same size (think that a could include 1 2 and 3, and b could include 4 5 6 7 and 8, etc)
What would be the easiest way of doing this? Using regex?
Thanks
You can use a for loop and check if the element is a digit or not:
d = {}
for i in lst:
if not i[0].isdigit(): # Check if element is a digit. If not, add a key with the current value of i[0]
d[i[0]] = []
current = i[0]
else:
d[current].append(i[0])
Output:
>>> d
{'a': ['1', '2', '3'], 'b': ['4', '5', '6']}
This is assuming everything in the list is a string

how to unpack a nested list in Python

How to unpack a list, which is nested inside another list.
Practically to transform this:
l=['aa','bb',['ccc','ddd'],'ee']
to
l=['aa','bb','ccc','ddd','ee']
See this thread and e. g. the solution of elqott
>>> from compiler.ast import flatten
>>> l = ['1','2',['3','4'],'5']
>>> flatten(l)
Following your edit
['1', '2', '3', '4', '5']
>>> l = ['aa','bb',['ccc','ddd'],'ee']
>>> flatten(l)
['aa', 'bb', 'ccc', 'ddd', 'ee']

Find overlapping List in 2 Lists of Lists

I would like to find overlapping lists in two lists of lists.
ListLeft = [['A', 'B', 'C'], ['1', '2', '3', '4'], ['x', 'y'], ['one', 'two', 'three']]
ListRight = [['h', 'i', 'j'], ['A', 'B', 'C'], ['1', '2', '3', '4'], ['5', '6', '7'], ['x', 'y']]
Someone might have a solution to find/print content of overlapping lists and lists which are not in both lists
Maybe this is possible without importing modules.
This can be simply achieved by using loop:
overlap = []
for ll in ListLeft:
for lr in ListRight:
if ll == lr:
overlap.append(ll)
break
print overlap
>>> [['A', 'B', 'C'], ['1', '2', '3', '4'], ['x', 'y']]