Python Printing Row and Column number on 2d matrix? - python

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 :

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 ?

code not running as aspected given wrong result

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.

How to count string with pattern in series object?

Suppose a data like this:
>>> data
x
0 [wdq, sda, q]
1 [q, d, qasd]
2 [d, b, sdaaaa]
I wonder how many string contains a in each list, which means I need an answer like this:
>>> data
x count_a
0 [wdq, sda, q] 1
1 [q, d, qasd] 1
2 [d, b, sdaaaa] 1
How can I do this in python?
Assuming this is a pandas.DataFrame and x is a list object:
df['count_a'] = df['x'].apply(lambda x: sum('a' in e for e in x))
you can try this;
for i in my_series:
print (i.count('a'))
this gives each your series letter
a = ['a', '12asf3', 'sdf']
b = ['gfdg5', ' ', 'vag gfd4']
c = [' fd4 ', 'sfsa fa', 'df4 a']
abc = [a, b, c]
for mem in abc:
counter = 0
for str in mem:
if 'a' in str:
counter += 1
print abc.index(mem), mem, counter
Output:
0 ['a', '12asf3', 'sdf'] 2
1 ['gfdg5', ' ', 'vag gfd4'] 1
2 [' fd4 ', 'sfsa fa', 'df4 a'] 2
To find out how many Strings in each List contain the letter a, you can use the following:
l = ['wdq', 'sda', 'qaaa']
print(sum([1 for x in l if 'a' in x]))
This prints the following:
2

How to do this program without a counter?

lista = []
for i in range(5):
i = int(input("Digite um valor para o vetor: "))
lista = lista + [i]
x = int(input("Digite um valor para ver sua posição: "))
counter = 0
for j in range(5):
if lista[j] == x:
counter =+ 1
print(j)
if counter == 0:
print(x-1)
In the above program you put any 5 numbers in the list, then you look for the position of the number you inputted in the list, if the number inputted is not in the list it will print x-1.
For example List = [1, 2, 3, 4, 5]
x = 5 then it will print 5
x = 7 it will print 6
How do I make it print x-1 without counter? I tried using:
else:
print(x-1)
but then it will print x-1 5 times, I only want to print it once.
You don't need a counter at all, as you're only using it to check that there were no matches. You can use the for..else structure to check whether the loop completed without exiting from a break.
for j in range(5):
if lista[j] == x:
print(j)
break
else:
print(x-1)
If you want to print each index that matches your search query, I would move to a different approach:
>>> x = 1
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
1 1 1 1 1
0 1 2 3 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10 1
2 4
>>> print(*(i for i,v in enumerate(map(int, input('Enter values separated by space:\n').split())) if v==x))
Enter values separated by space:
2 2 1 10
2

Categories