code not running as aspected given wrong result - python

I want to print
A
B C
C D E
E F G H
I tried but showing the result
A
B C
C D D
D E E E
a = chr(65)
for i in range(0, 4):
i = i + 1
for j in range(65, 65+i):
print(a, end=" ")
a = chr(65 + i)
print("\n")

Make it simple:
letter_a_code = ord('A')
for i in range(4):
for j in range(i+1):
letter = chr(letter_a_code+j+i)
print(letter, end=" ")
print()
prints:
A
B C
C D E
D E F G
You have to print 4 rows. i is your index.
Each row is made of i elements.
Add the offset for letter A code (don't hardcode it, use ord('A')): done.

Related

lines repeat in List python

I need your help with the next problem,
i need that a python recieve an string "EEEEDDSGES" and the output would by the sum of charactes that repeat in line,
E 4
D 2
S 1
G 1
E 1
S 1
my code is the next,
diccionario = {}
contador = 0
for palabra in cadena:
if palabra.upper() in diccionario:
diccionario[palabra.upper()] += 1
else:
diccionario[palabra.upper()] = 1
for palabra in diccionario:
frecuencia = diccionario[palabra]
print(palabra, end=" ")
print(frecuencia) ```
the output is ,
S,S,d,f,s
S 1
S 2
d 3
f 4
s 5
Try itertools.groupby:
from itertools import groupby
s = "EEEEDDSGES"
for v, g in groupby(s):
print(v, sum(1 for _ in g))
Prints:
E 4
D 2
S 1
G 1
E 1
S 1
I'm sorry I don't understand what this language is, but I guess I understand what you are trying to do. I have changed the variable names for my comprehension.
s="EEEEDDSGES"
letters={}
for i in s:
i=i.upper()
try:
letters[i]+=1
except(KeyError):
letters.update({i:1})
for i in letters: print(f"{i}: {letters[i]}", end=" ")

Alphabetical Grid using python3

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 ?

Python Printing Row and Column number on 2d matrix?

I'm trying to print output as follows.
Strings: ["cat", "dog", "big"]
Print:
0 1 2
0 c a t
1 d o g
2 b i g
But I can't seem to print the indices properly
for i in a:
for j in i:
print(j, end=' ')
print()
I know this prints the matrix itself but doesn't give me the row and column numbers I need
Ideal job for pandas:
import pandas as pd
lst = ["cat", "dog", "big"]
df = pd.DataFrame([[y for y in x] for x in lst])
print(df)
# 0 1 2
# 0 c a t
# 1 d o g
# 2 b i g
please try below:
str_list = ["cat", "dog", "big"]
print (" ", " ".join([str(x) for x in range(len(str_list))]))
for i, x in enumerate(str_list):
print (i, " ".join(x))
Demo
Ta-da! This solution should work regardless of list dimensions.
str_list = ['cat', 'dog', 'loooong', 'big']
max_row_len = len(max(str_list, key=len))
#header
print(' ', end='')
print(*range(max_row_len), sep=' ')
#rows
for idx, val in enumerate(str_list):
print(idx, end=' ')
print(*val, sep=' ')
Output:
0 1 2 3 4 5 6
0 c a t
1 d o g
2 l o o o o n g
3 b i g
You can achieve your output without using any library by following code, Otherwise PANDAS would be helpful for oneliner
str = ['cat','dog','big']
r = 0
c = 0
print(' ',end='')
for i in range(0,(max([len(i) for i in str]))):
print(c,end=' ')
c+=1
print()
for i in str:
print(r,end=' ')
for j in i:
print(j , end=' ')
print()
r+=1
Output :

Trying to verify last position of a string

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')

Print number of the rows Python

I am trying to print the number of the row in 2d array (list of the list) like:
A B C D E F
1: - - - - - -
2: - - - - - -
I need to print only the number of rows 1:
can someone pls guide me
def printChart(list):
print('\n A B C D E F')
for i in list:
for e in i:
print(' ', e, end='')
print()
print()
From my understanding, you want to add a number to the line.
def printChart(abc):
print('\n A B C D E F')
for x,i in enumerate(abc):
print(x, ' ', i)
alpha = ["A", "B" , "C" ,"D", "E", "F"]
printChart(alpha)
OUTPUT:
0 A
1 B
2 C
3 D
4 E
5 F

Categories