how to write a function grid that returns an alphabetical grid of size NxN, where a = 0, b = 1, c = 2.... in python
example :
a b c d
b c d e
c d e f
d e f g
here I try to create a script using 3 for loops but it's going to print all the alphabets
def grid(N):
for i in range(N):
for j in range(N):
for k in range(ord('a'),ord('z')+1):
print(chr(k))
pass
Not the most elegant, but gets the job done.
import string
def grid(N):
i = 0
for x in range(N):
for y in string.ascii_lowercase[i:N+i]:
print(y, end=" ")
i += 1
print()
grid(4)
Output
a b c d
b c d e
c d e f
d e f g
Extending from #MichHeng's suggestion, and using list comprehension:
letters = [chr(x) for x in range(ord('a'),ord('z')+1)]
def grid(N):
for i in range(N):
print(' '.join([letters[i] for i in range(i,N+i)]))
grid(4)
output is
a b c d
b c d e
c d e f
d e f g
You have specified for k in range(ord('a'),ord('z')+1) which prints out the entire series from 'a' to 'z'. What you probably need is a reference list comprehension to pick your letters from, for example
[chr(x) for x in range(ord('a'),ord('z')+1)]
Try this:
letters = [chr(x) for x in range(ord('a'),ord('z')+1)]
def grid(N):
for i in range(N):
for j in range(i, N+i):
print(letters[j], end=' ')
if j==N+i-1:
print('') #to move to next line
grid(4)
Output
a b c d
b c d e
c d e f
d e f g
Do you need to add a check for N<=13 ?
Im trying to verify if the last char is not on my list
def acabar_char(input):
list_chars = "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 D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0".split()
tam = 0
tam = (len(input)-1)
for char in input:
if char[tam] in list_chars:
return False
else:
return True
When i try this i get this error:
if char[tam] in list_chars:
IndexError: string index out of range
you can index from the end (of a sting or a list) with negative numbers
def acabar_char(input, list_cars):
return input[-1] is not in list_chars
It seems that you are trying to assert that the last element of an input string (or also list/tuple) is NOT in a subset of disallowed chars.
Currently, your loop never even gets to the second and more iteration because you use return inside the loop; so the last element of the input only gets checked if the input has length of 1.
I suggest something like this instead (also using the string.ascii_letters definition):
import string
DISALLOWED_CHARS = string.ascii_letters + string.digits
def acabar_char(val, disallowed_chars=DISALLOWED_CHARS):
if len(val) == 0:
return False
return val[-1] not in disallowed_chars
Does this work for you?
you are already iterating through your list in that for loop, so theres no need to use indices. you can use list comprehension as the other answer suggest, but I'm guessing you're trying to learn python, so here would be the way to rewrite your function.
list_chars = "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 D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0".split()
for char in input:
if char in list_chars:
return False
return True
list_chars = "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 D E F G H I J K L M N O P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0".split()
def acabar_char(input):
if input in list_chars:
print('True')
i use python to read a txt file.
i have tried using .lstrip to remove the whitespace from the left but it only manages to remove the whitespace from the first line.
In the text file:
when i use this:
puzzle = puzzle.replace('',' ')
x m f y c x v t l j l q b b y b k o u m j q w b t
c a u b m e k n b e y d q m c n z y j p v r a n k
a q a c t i v e x n y v w d v c o s h o y a o h g
p a g h z k c t u d p t j d p h s z t p r h t t l
s b s n a k j w q b o u f t m g n j q b t l i n u
t s e w o h v o b d s d u q j i f f k y y l o d o
o u k w w e f r o y a m a p m l r r p v d o l o p
c q k f x t l k s j v t m t r s b y c m q r r r i
k f e r v l q i d q a x a o a n f q j l m c p j h
y o y y w r b p f c j l f b c b b c o e c s p w l
t w b x e t y u y u f v v m a u a w j m b w l q h
t x o k d e x m d b t g v h p s v s q t m l j d x
d c a t e n r e h t e o x q d g e u e l j t r r n
j a r t e q v t x e j f s q d d k b u h c y s f q
h p d r o w s s a p x t r x h p d x c d h i c o n
what i get when i use: print (puzzle.lstrip())
x m f y c x v t l j l q b b y b k o u m j q w b t
c a u b m e k n b e y d q m c n z y j p v r a n k
a q a c t i v e x n y v w d v c o s h o y a t j d p h s z t p r h t t l
s b s n a k j w q b o u f t m g n j q b t l i n u
t s e w o h v o b d s d u q j i f f k y y l o d o
o u k w w e f r o y a m a p m l r r p v d o l o p
c q k f x t l k s j v t m t r s b y c m q r r r i
k f e r v l q i d q a x a o a n f q j l m c p j h
y o y y w r b p f c j l f b c b b c o e c s p w l
t w b x e t y u y u f v v m a u a w j m b w l q h
t x o k d e x m d b t g v h p s v s q t m l j d x
d c a t e n r e h t e o x q d g e u e l j t r r n
j a r t e q v t x e j f s q d d k b u h c y s f q
h p d r o w s s a p x t r x h p d x c d h i c o n
Instead i want remove all the whitespace from the left to get:
x m f y c x v t l j l q b b y b k o u m j q w b t
c a u b m e k n b e y d q m c n z y j p v r a n k
a q a c t i v e x n y v w d v c o s h o y a o h g
p a g h z k c t u d p t j d p h s z t p r h t t l
s b s n a k j w q b o u f t m g n j q b t l i n u
t s e w o h v o b d s d u q j i f f k y y l o d o
o u k w w e f r o y a m a p m l r r p v d o l o p
c q k f x t l k s j v t m t r s b y c m q r r r i
k f e r v l q i d q a x a o a n f q j l m c p j h
y o y y w r b p f c j l f b c b b c o e c s p w l
t w b x e t y u y u f v v m a u a w j m b w l q h
t x o k d e x m d b t g v h p s
Thanks for your help!!!!
Starting from txt
txt = """xmfycxvtljlqbbybkoumjqwbt
caubmeknbeydqmcnzyjpvrank
aqactivexnyvwdvcoshoyaohg
paghzkctudptjdphsztprhttl
sbsnakjwqbouftmgnjqbtlinu
tsewohvobdsduqjiffkyylodo
oukwwefroyamapmlrrpvdolop
cqkfxtlksjvtmtrsbycmqrrri
kfervlqidqaxaoanfqjlmcpjh
yoyywrbpfcjlfbcbbcoecspwl
twbxetyuyufvvmauawjmbwlqh
txokdexmdbtgvhpsvsqtmljdx
dcatenrehteoxqdgeueljtrrn
jarteqvtxejfsqddkbuhcysfq
hpdrowssapxtrxhpdxcdhicon"""
you can print the desired result like that:
for line in txt.splitlines():
print(' '.join(line))
and if you don't want to print, you can use a list comprehension to store the results in a variable:
result = [' '.join(line) for line in txt.splitlines()]
You can replace all instances of newline followed by space by newline:
puzzle = puzzle.replace('\n ','')
I suppose this might work:
result = [row.lstrip() for row in filehandle.readlines()]
I have this simple txt file:
[header]
width=8
height=5
tilewidth=175
tileheight=150
[tilesets]
tileset=../GFX/ts1.png,175,150,0,0
[layer]
type=Tile Layer 1
data=
1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,1,
1,0,0,0,0,1,1,1,
1,0,0,0,6,0,0,1,
1,1,1,1,4,1,1,1
I want to separate the text by the "[header]", "[tilesets]" and "[layers]". Problem is, if I split it in this way:
m = open(self.fullPath, 'r+')
sliced = m.read().split() # Default = \n
print sliced
It shall separate each line, because read() always leave a '\n' at the end of every line:
['[header]', 'width=8', 'height=5', 'tilewidth=175', 'tileheight=150', '[tilesets]', 'tileset=../GFX/ts1.png,175,150,0,0', '[layer]', 'type=Tile', 'Layer', '1', 'data=', '1,1,1,1,1,1,1,1,', '1,0,0,0,0,0,0,1,', '1,0,0,0,0,1,1,1,', '1,0,0,0,6,0,0,1,', '1,1,1,1,4,1,1,1']
But it's possible to split perfectly if, instead a new-line-character, there was a "#" sign or whatever separating each section.
Then, I thought: "There are empty lines there, and they are new-line-characters, so I just need to test if the line equals to the new-line-character and replace it with '#'":
for line in m.readlines():
if line == '\n':
m.write('#')
for line in m.readlines():
print line
Perfect.. Except that.. Instead of achieving this:
[header]
width=8
height=5
tilewidth=175
tileheight=150
#
[tilesets]
tileset=../GFX/ts1.png,175,150,0,0
#
[layer]
type=Tile Layer 1
data=
1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,1,
1,0,0,0,0,1,1,1,
1,0,0,0,6,0,0,1,
1,1,1,1,4,1,1,1
I get this:
[header]
width=8
height=5
tilewidth=175
tileheight=150
[tilesets]
tileset=../GFX/ts1.png,175,150,0,0
[layer]
type=Tile Layer 1
data=
1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,1,
1,0,0,0,0,1,1,1,
1,0,0,0,6,0,0,1,
1,1,1,1,4,1,1,1##õÙÓ Z d Z d d l Z d d l Z d " Z d $ „ Z d - f d „ ƒ Y Z e H d ƒ Z e I j ƒ Æ Çîà õÙÓ ; | j d ƒ } i < g d 6 g d 6 g d 6 } d = d d g } x 0 ·ð? | j ƒ D u tîà õÙÓI À¶ð ) (–à W # "íà õ#ÎÔ €·ðB | j ƒ D ú ú–à õ(Tò `·ð } | C G H q | #·ð Ñ Ñ–à õ#ÎÔ ¨ ¨–à õ#ÎÔ
E G H | F j ƒ –à õ#ÎÔ S V V–à õ#ÎÔž ÿÿÿÿ t | j d ƒ } i g d 6g d 6g d 6} d d d g } x0 | j ƒ D]" } | d k rk | j d ƒ n qI Wx | j ƒ D] } | GHq| Wd
GH| j ƒ d S `:ð> >§à õ#ÎÔÀ:ðà¢îðà:ð ;ð`ßî ;ð#;ð0ð`;ð £îXð# ï€;ð€ð ;ð`£îÀ;ðà;ð ð2 2›à õ#ÎÔ`<ð€<ðà¤î <ð ?îÀ<ðà<ð =ð =ð#=ðÀ?î ïÐð`=ð¸ï€=ð =ðøðÀ=ðà=ð >ð >ð#>ð`>ð ð€>ð >ðÀ>ðà>ð ?ð#OÑ ?ð#?ð`?ð€?ð ?ðHðpðÀ?ð˜ðÀðà?ð #ðÀ£î##ð`#ð€#ð #ð PðHPðÀ#ðà#ð
It makes no sense :).
Simultaneously reading from and writing to a file tends to have unpredictable effects on what kind of output you get.
If your categories are always separated by two newlines, then just split on that, instead of doing any fancy find/replace operations.
m = open("input.txt", "r+")
sliced = m.read().split("\n\n")
print "data has been split into {} categories.".format(len(sliced))
#print the starting line of each category
for category in sliced:
print category.split("\n")[0]
Result:
data has been split into 3 categories.
[header]
[tilesets]
[layer]