How to use dictionary - python

How do I make 2d lists in run time when user inputs some number.

There are easy and difficult things:
horizontal ist trivial - simply join the inner list and replace the word and the word reversed by its upper case representation, then split the string into letters
vertical is mildly more difficult, but you can handle it by transposing the matrix via zip and after replacing transpose again
vertical is handled in the linked question Find Letter of Words in a Matrix Diagonally
Here is how to do horizontal and vertical:
data = [['l', 'd', 'l', 'o', 'h', 'p'],
['i', 't', 'i', 'f', 'w', 'f'],
['g', 'n', 'r', 'k', 'q', 'u'],
['h', 'g', 'u', 'a', 'l', 'l'],
['t', 'c', 'v', 'g', 't', 'l'],
['d', 'r', 'a', 'w', 'c', 's']]
words = ['draw', 'full', 'hold', 'laugh', 'light', 'start', 'all', 'kid']
from pprint import pprint as p
for w in words:
print()
# horizontal
data1 = [list(''.join(line).replace(w,w.upper())) for line in data]
# horizontal, word reversed
data1 = [list(''.join(line).replace(w[::-1],w[::-1].upper())) for line in data1]
# vertical
data1 = list(zip(*[list(''.join(line).replace(w,w.upper()))
for line in zip(*data1)]))
# vertical, word reversed
data1 = list(zip(*[list(''.join(line).replace(w[::-1],w[::-1].upper()))
for line in zip(*data1)]))
if data1 != data:
print(f"Found: {w}:")
data = data1
p(data)
else:
print(f"No {w} - check diagonally")
Output:
Found: draw:
[('l', 'd', 'l', 'o', 'h', 'p'),
('i', 't', 'i', 'f', 'w', 'f'),
('g', 'n', 'r', 'k', 'q', 'u'),
('h', 'g', 'u', 'a', 'l', 'l'),
('t', 'c', 'v', 'g', 't', 'l'),
('D', 'R', 'A', 'W', 'c', 's')]
Found: full:
[('l', 'd', 'l', 'o', 'h', 'p'),
('i', 't', 'i', 'f', 'w', 'F'),
('g', 'n', 'r', 'k', 'q', 'U'),
('h', 'g', 'u', 'a', 'l', 'L'),
('t', 'c', 'v', 'g', 't', 'L'),
('D', 'R', 'A', 'W', 'c', 's')]
Found: hold:
[('l', 'D', 'L', 'O', 'H', 'p'),
('i', 't', 'i', 'f', 'w', 'F'),
('g', 'n', 'r', 'k', 'q', 'U'),
('h', 'g', 'u', 'a', 'l', 'L'),
('t', 'c', 'v', 'g', 't', 'L'),
('D', 'R', 'A', 'W', 'c', 's')]
Found: laugh:
[('l', 'D', 'L', 'O', 'H', 'p'),
('i', 't', 'i', 'f', 'w', 'F'),
('g', 'n', 'r', 'k', 'q', 'U'),
('H', 'G', 'U', 'A', 'L', 'L'),
('t', 'c', 'v', 'g', 't', 'L'),
('D', 'R', 'A', 'W', 'c', 's')]
No light - check diagonally
No start - check diagonally
No all - check diagonally
No kid - check diagonally

For horizontal you can use this:
>>> for i in range(len(l)):# l is the list
temp = ''.join(l[i])
x = temp.find(word) #word is the user input eg. draw
y = len(word)
if x != -1:
for j in range(y):
l[i][j]=l[i][j].capitalize()
I'll try to make for vertical and diagonal as well

this one:
l = [['l', 'd', 'l', 'o', 'h', 'p'],
['i', 't', 'i', 'f', 'w', 'f'],
['g', 'n', 'r', 'k', 'q', 'u'],
['h', 'g', 'u', 'a', 'l', 'l'],
['t', 'c', 'v', 'g', 't', 'l'],
['d', 'r', 'a', 'w', 'c', 's']]
word = input("Please enter a word: ")
for i in range(len(l)):
for j in range(len(l[i])):
if l[i][j] in word:
l[i][j]=l[i][j].capitalize()
print(l)
outs:
Please enter a word: hello
[['L', 'd', 'L', 'O', 'H', 'p'], ['i', 't', 'i', 'f', 'w', 'f'], ['g', 'n', 'r', 'k', 'q', 'u'], ['H', 'g', 'u', 'a', 'L', 'L'], ['t', 'c', 'v', 'g', 't', 'L'], ['d', 'r', 'a', 'w', 'c', 's']]

Related

How to prepare batches of data from a list of values? [duplicate]

This question already has answers here:
Iterate an iterator by chunks (of n) in Python?
(14 answers)
Closed 2 years ago.
Here's a list that I have,
data = (i for i in list("abcdefghijklmnopqrstuvwxyzabcedefghijklmnopqrstuvwxyz"))
Here data is a generator and I want to iterate over it and prepared batches of 12 equal datapoints, if it is less than 12 in last batch I need it too, but below code is not working,
subsets = []
subset = []
for en, i in enumerate(data):
if en % 12 == 0 and en > 0:
subsets.append(subset)
subset = []
else:
subset.append(i)
print(subsets)
[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
['n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x'],
['z', 'a', 'b', 'c', 'e', 'd', 'e', 'f', 'g', 'h', 'i'],
['k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u']]
But my code is not working properly because the first nested list has 12 values but rest of it have 11 values and it missed out last few values which are less than 12 in the last batch
Expected Output:
[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
['m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x'],
['y', 'z', 'a', 'b', 'c', 'e', 'd', 'e', 'f', 'g', 'h', 'i'],
['j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u'],
['v', 'w', 'x', 'y', 'z']]
Two changes, you need to start iterating from 1 and append in the sublist before emptying it:
data = (i for i in list("abcdefghijklmnopqrstuvwxyzabcedefghijklmnopqrstuvwxyz"))
subsets = []
subset = []
# start counting from index '1'
for en, i in enumerate(data, 1):
if en % 12 == 0 and en > 0:
# append the current element before emptying 'subset'
subset.append(i)
subsets.append(subset)
subset = []
else:
subset.append(i)
# append the left-over sublist/subset to your main list as well
subsets.append(subset)
for i in subsets:
print(i)
gives
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
['m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x']
['y', 'z', 'a', 'b', 'c', 'e', 'd', 'e', 'f', 'g', 'h', 'i']
['j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u']
['v', 'w', 'x', 'y', 'z']
Alternative solution is using buit-in itertools.islice. You can check to see which approach is faster or more convenient. Kr.
import itertools
def gen_sublist(your_iter, size):
while True:
part = tuple(itertools.islice(your_iter, size))
if not part:
break
yield part
data = (i for i in list("abcdefghijklmnopqrstuvwxyzabcedefghijklmnopqrstuvwxyz"))
for c in gen_sublist(data, size=12):
print(c)
which returns:
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l')
('m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x')
('y', 'z', 'a', 'b', 'c', 'e', 'd', 'e', 'f', 'g', 'h', 'i')
('j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u')
('v', 'w', 'x', 'y', 'z')
A different approach which does not use modulo or enumeration (just another option since other answers already correct your approach):
In [1]: subsets = []
In [2]: data = (i for i in list("abcdefghijklmnopqrstuvwxyzabcedefghijklmnopqrstuvwxyz"))
In [3]:
...: while True:
...: try:
...: x = []
...: for i in range(12):
...: x.append(next(data))
...: subsets.append(x)
...: except: # Catch StopIteration Exception when generator runs out of values
...: subsets.append(x)
...: break
...:
Outputs:
In [4]: subsets
Out[4]:
[['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
['m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x'],
['y', 'z', 'a', 'b', 'c', 'e', 'd', 'e', 'f', 'g', 'h', 'i'],
['j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u'],
['v', 'w', 'x', 'y', 'z']]

I just want to get same index letter for each element on my list

For ex:
a = "pandaxngeqrymtso-ezmlaesowxaqbujl-noilktxreecytrql-gskaboofsfoxdtei-utsmakotufodhlrd-iroachimpanzeesa-nintrwflyrkhcdum-jcecahkktiklsvhr-mhvsbaykagodwgca-koalatcwlkfmrwbb-jsrrfdolphinuyt"
a = a.split("-")
mylist = []
word = ""
while i < len(a[0]): #16
for elem in a:
word+= elem[i]
mylist.append(kelime)
i += 1
word = ""
I just want a list which contains "penguinjmhkj, azostrichos..." But I get an Index error.
What can I do?
You can try this:
>>> word = [''.join(letters) for letters in zip(*(list(word) for word in a.split('-')))]
>>> word
['penguinjmkj',
'azostrichos',
'nmiksonevar',
'dllamatcslr',
'aakbacrabaf',
'xetokhwhatd',
'nsxooifkyco',
'gorftmlkkwl',
'ewesupytalp',
'qxeffarigkh',
'racoonkkofi',
'yqyxdzhldmn',
'mbtdhecswru',
'turtledvgwy',
'sjqersuhcbt']
Explanation:
You can understand what it is doing if you print the individual parts,
for e.g.:
>>> print(*(list(word) for word in a.split('-'))
['p', 'a', 'n', 'd', 'a', 'x', 'n', 'g', 'e', 'q', 'r', 'y', 'm', 't', 's', 'o'] ['e', 'z', 'm', 'l', 'a', 'e', 's', 'o', 'w', 'x', 'a', 'q', 'b', 'u', 'j', 'l'] ['n', 'o', 'i', 'l', 'k', 't', 'x', 'r', 'e', 'e', 'c', 'y', 't', 'r', 'q', 'l'] ['g', 's', 'k', 'a', 'b', 'o', 'o', 'f', 's', 'f', 'o', 'x', 'd', 't', 'e', 'i'] ['u', 't', 's', 'm', 'a', 'k', 'o', 't', 'u', 'f', 'o', 'd', 'h', 'l', 'r', 'd'] ['i', 'r', 'o', 'a', 'c', 'h', 'i', 'm', 'p', 'a', 'n', 'z', 'e', 'e', 's', 'a'] ['n', 'i', 'n', 't', 'r', 'w', 'f', 'l', 'y', 'r', 'k', 'h', 'c', 'd', 'u', 'm'] ['j', 'c', 'e', 'c', 'a', 'h', 'k', 'k', 't', 'i', 'k', 'l', 's', 'v', 'h', 'r'] ['m', 'h', 'v', 's', 'b', 'a', 'y', 'k', 'a', 'g', 'o', 'd', 'w', 'g', 'c', 'a'] ['k', 'o', 'a', 'l', 'a', 't', 'c', 'w', 'l', 'k', 'f', 'm', 'r', 'w', 'b', 'b'] ['j', 's', 'r', 'r', 'f', 'd', 'o', 'l', 'p', 'h', 'i', 'n', 'u', 'y', 't']
So it breaks up all the individual words delimited by - into characters.
Then zip does this:
>>> print(zip(*(list(word) for word in a.split('-'))))
('p', 'e', 'n', 'g', 'u', 'i', 'n', 'j', 'm', 'k', 'j') ('a', 'z', 'o', 's', 't', 'r', 'i', 'c', 'h', 'o', 's') ('n', 'm', 'i', 'k', 's', 'o', 'n', 'e', 'v', 'a', 'r') ('d', 'l', 'l', 'a', 'm', 'a', 't', 'c', 's', 'l', 'r') ('a', 'a', 'k', 'b', 'a', 'c', 'r', 'a', 'b', 'a', 'f') ('x', 'e', 't', 'o', 'k', 'h', 'w', 'h', 'a', 't', 'd') ('n', 's', 'x', 'o', 'o', 'i', 'f', 'k', 'y', 'c', 'o') ('g', 'o', 'r', 'f', 't', 'm', 'l', 'k', 'k', 'w', 'l') ('e', 'w', 'e', 's', 'u', 'p', 'y', 't', 'a', 'l', 'p') ('q', 'x', 'e', 'f', 'f', 'a', 'r', 'i', 'g', 'k', 'h') ('r', 'a', 'c', 'o', 'o', 'n', 'k', 'k', 'o', 'f', 'i') ('y', 'q', 'y', 'x', 'd', 'z', 'h', 'l', 'd', 'm', 'n') ('m', 'b', 't', 'd', 'h', 'e', 'c', 's', 'w', 'r', 'u') ('t', 'u', 'r', 't', 'l', 'e', 'd', 'v', 'g', 'w', 'y') ('s', 'j', 'q', 'e', 'r', 's', 'u', 'h', 'c', 'b', 't')
So it takes all the corresponding characters from each group, each of the tuples get passed as letters in each iteration in the main code.
Then you join each tuple, for e.g. in first iteration:
>>> ''.join(('p', 'e', 'n', 'g', 'u', 'i', 'n', 'j', 'm', 'k', 'j'))
'penguinjmkj'
[<item after some operation> for <each item> in <item_list>] this structure is called list comprehension. * is used for iterable unpacking.
it took a while but i cracked it;
what you just need to do is to handle the Index Error: String out of range.
if you count the words they are over 16 while the array items after splitting are just over 11. to cut long story short; Handle the exception with a try_except where you are appending the letters at:
word+= elem[i]
here is my code and how i solved it using try_catch
a = "pandaxngeqrymtso-ezmlaesowxaqbujl-noilktxreecytrql-gskaboofsfoxdtei-utsmakotufodhlrd-iroachimpanzeesa-nintrwflyrkhcdum-jcecahkktiklsvhr-mhvsbaykagodwgca-koalatcwlkfmrwbb-jsrrfdolphinuyt"
newArr = a.split('-')
newWord = []
i = 0
mylist = []
while i < len(newArr[0]):
word = ""
for item in newArr:
try:
word += item[i]
except:
break
i += 1
mylist.append(word)
print(mylist)
I used a try_except to handle the Index Error when appending the letter, then break when ever the 'i' used for the while loop is greater than the newArr length in the for loop.
try for your self!
Similar to the code from Sayandip, but it would have been more readable for me in the past:
mylist =[]
for element in zip(*a.split('-')):
mylist.append(''.join(element))
print(mylist)
I get
['penguinjmkj', 'azostrichos', 'nmiksonevar', 'dllamatcslr', 'aakbacrabaf', 'xetokhwhatd', 'nsxooifkyco', 'gorftmlkkwl', 'ewesupytalp', 'qxeffarigkh', 'racoonkkofi', 'yqyxdzhldmn', 'mbtdhecswru', 'turtledvgwy', 'sjqersuhcbt']
I am moving the splitting in the for loop, and using the * construct to pass the whole list resulting from splitting, see usage here and here.

Remove a '\n' list item from a list of a reading file

I have a similar problem. My code so far is:
file='/Users/Giannis/Desktop/Python Assegments/Week 6/boardlist1.txt'
boardlist = []
file = open(file, 'r')
line = file.readlines()
wordstring = ''
for i in range(0,len(line)):
final_list = []
raw = list(line[i])
boardlist.append(raw)
print(boardlist)
file.close()
The file you see is a txt which is:
EFJAJCOWSS
SDGKSRFDFF
ASRJDUSKLK
HEANDNDJWA
ANSDNCNEOP
PMSNFHHEJE
JEPQLYNXDL
My print results are:
[['E', 'F', 'J', 'A', 'J', 'C', 'O', 'W', 'S', 'S', '\n'], ['S', 'D', 'G', 'K', 'S', 'R', 'F', 'D', 'F', 'F', '\n'], ['A', 'S', 'R', 'J', 'D', 'U', 'S', 'K', 'L', 'K', '\n'], ['H', 'E', 'A', 'N', 'D', 'N', 'D', 'J', 'W', 'A', '\n'], ['A', 'N', 'S', 'D', 'N', 'C', 'N', 'E', 'O', 'P', '\n'], ['P', 'M', 'S', 'N', 'F', 'H', 'H', 'E', 'J', 'E', '\n'], ['J', 'E', 'P', 'Q', 'L', 'Y', 'N', 'X', 'D', 'L']]
And I want to remove every \n character in it. How can I do that with this code?
Use strip(), here is the shortest version of your code :
file='/Users/Giannis/Desktop/Python Assegments/Week 6/boardlist1.txt'
with open(file, 'r') as f:
print([list(i) for i in [i.strip() for i in f]])
[['E', 'F', 'J', 'A', 'J', 'C', 'O', 'W', 'S', 'S'], ['S', 'D', 'G', 'K', 'S', 'R', 'F', 'D', 'F', 'F'], ['A', 'S', 'R', 'J', 'D', 'U', 'S', 'K', 'L', 'K'], ['H', 'E', 'A', 'N', 'D', 'N', 'D', 'J', 'W', 'A'], ['A', 'N', 'S', 'D', 'N', 'C', 'N', 'E', 'O', 'P'], ['P', 'M', 'S', 'N', 'F', 'H', 'H', 'E', 'J', 'E'], ['J', 'E', 'P', 'Q', 'L', 'Y', 'N', 'X', 'D', 'L']]
Note : You don't need to use readlines(), just iterate the file object.

Flattening lists containing 2-tuples and 1-tuples by splitting the 2-tuples

I'm having trouble with making lists like
[['G', 'U'], ['G', 'U'], 'R', 'G']
into all the possible combinations like the following
[['G', 'G', 'R', 'G'],
['G', 'U', 'R', 'G'],
['U', 'G', 'R', 'G'],
['U', 'U', 'R', 'G']]
in Python. How do I go about it?
You can use itertools.product():
lst = [['G', 'U'], ['G', 'U'], 'R', 'G']
from itertools import product
[x for x in product(*lst)]
#[('G', 'G', 'R', 'G'),
# ('G', 'U', 'R', 'G'),
# ('U', 'G', 'R', 'G'),
# ('U', 'U', 'R', 'G')]
You can easily do this using itertools.product. It does exactly what you describe.
>> import itertools
>> l = [['G', 'U'], ['G', 'U'], 'R', 'G']
>> i = itertools.product(*l)
>> list(i)
[('G', 'G', 'R', 'G'), ('G', 'U', 'R', 'G'), ('U', 'G', 'R', 'G'), ('U', 'U', 'R', 'G')]

Python - Permutation/Combination column-wise

I have a list
mylist = [
['f', 'l', 'a', 'd', 'l', 'f', 'k'],
['g', 'm', 'b', 'b', 'k', 'g', 'l'],
['h', 'n', 'c', 'a', 'm', 'j', 'o'],
['i', 'o', 'd', 'c', 'n', 'i', 'm'],
['j', 'p', 'e', 'e', 'o', 'h', 'n'],
]
I want do permutation/combination column-wise, such the elements of the column are restricted to that column i.e., f,g,h,i,j remain in Column 1, l,m,n,o,p remain in Column 2 and so on, in the results of permutation/combination. How can this be achieved in Python 2.7?
You could use zip(*mylist) to list the "columns" of mylist. Then use the * operator (again) to unpack those lists as arguments to IT.product or IT.combinations. For example,
import itertools as IT
list(IT.product(*zip(*mylist)))
yields
[('f', 'l', 'a', 'd', 'l', 'f', 'k'),
('f', 'l', 'a', 'd', 'l', 'f', 'l'),
('f', 'l', 'a', 'd', 'l', 'f', 'o'),
('f', 'l', 'a', 'd', 'l', 'f', 'm'),
...]

Categories

Resources