Print number of the rows Python - 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

Related

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

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.

Given an N-side square matrix, is there a way to find the ring value of a cell without using loops or if conditions?

For instance, imagine you have a 6-side square matrix.
These are the cells cartesian indices:
(0,0) (0,1) (0,2) (0,3) (0,4) (0,5)
(1,0) (1,1) (1,2) (1,3) (1,4) (1,5)
(2,0) (2,1) (2,2) (2,3) (2,4) (2,5)
(3,0) (3,1) (3,2) (3,3) (3,4) (3,5)
(4,0) (4,1) (4,2) (4,3) (4,4) (4,5)
(5,0) (5,1) (5,2) (5,3) (5,4) (5,5)
A 6-side square has 3 rings: a
A A A A A A
A B B B B A
A B C C B A
A B C C B A
A B B B B A
A A A A A A
QUESTION: What's the function that takes the coordinates of a cell, the side N of the square and returns the ring value accordingly? Ex:
f(x = 1, y 2, N = 6) = B
A,B,C... can be any numerical value: 1,2,3 ... or 0,1,2 ... or whatever. What matters is that they are congruent for any N. Ex:
N = 1 => A = 1
N = 2 => A = 1
N = 3 => A = 1, B = 2
N = 4 => A = 1, B = 2
N = 5 => A = 1, B = 2, C = 3
N = 6 => A = 1, B = 2, C = 3
N = 7 => A = 1, B = 2, C = 4, D = 4
...
Using if conditions the problem is easily solved.
Given a pair (x,y) and the square side N:
# N//2 is the number of rings in a N-side square
for k in range(1,N//2+1):
if x == 0+k-1 or y== 0+k-1 or x == N-k or y == N-1:
return k
This seems like a very expensive way to find the ring value of the cell though.
I have been trying to find the function using diagonals, sum of the coordinates, difference of the coordinates ... of the cells, but I still couldn't find anything.
Has anyone ever encountered this problem?
Is there a way to solve it?
Looks like a math problem to solve.
EDIT: Updated function, should be better able to handle even and odd cases after the mid point i hope. However, OP's request to turn this into a mathematical equation, i'm not sure how to do that.
import math
def ring_finder(x, y, N, outer_ring = 0):
'''
x and y are the coordinates of a cell, N is the length of the side of square
Returns the correct ring count starting from outer_ring value (default, 0)
'''
if x >= N or y >= N:
print("coordinates outside square, please check")
return None
no_of_squares = math.ceil(N/2)
x = N - x - 1 if x >= no_of_squares else x
y = N - y - 1 if y >= no_of_squares else y
return min(x, y) + outer_ring
ring_finder(5, 5, 6)
ring_finder(1, 2, 6)
I think this function does what you want:
def ring_id(n, i, j):
even = n % 2 == 0
n_2 = n // 2
i = i - n_2
if even and i >= 0:
i += 1
i = abs(i)
j = j - n_2
if even and j >= 0:
j += 1
j = abs(j)
ring_id = i + max(j - i, 0)
return n_2 - ring_id
Small test with letters:
import string
def print_rings(n):
ring_names = string.ascii_uppercase
for i in range(n):
for j in range(n):
rid = ring_id(n, i, j)
print(ring_names[rid], end=' ')
print()
print_rings(6)
# A A A A A A
# A B B B B A
# A B C C B A
# A B C C B A
# A B B B B A
# A A A A A A
print_rings(7)
# A A A A A A A
# A B B B B B A
# A B C C C B A
# A B C D C B A
# A B C C C B A
# A B B B B B A
# A A A A A A A
EDIT: If you insist in not having the word if in your function, you can (somewhat awkwardly) rewrite the above function as:
def ring_id(n, i, j):
even = 1 - n % 2
n_2 = n // 2
i = i - n_2
i += even * (i >= 0)
i = abs(i)
j = j - n_2
j += even * (j >= 0)
j = abs(j)
ring_id = i + max(j - i, 0)
return n_2 - ring_id
Or if you want it looking more "formula-like" (albeit unreadable and with more repeated computation):
def ring_id(n, i, j):
i2 = abs(i - (n // 2) + (1 - n % 2) * (i >= (n // 2)))
j2 = abs(j - (n // 2) + (1 - n % 2) * (j >= (n // 2)))
return (n // 2) - i2 + max(j2 - i2, 0)
This is not any more or less "mathematical" though, it is fundamentally the same logic.
The ring value is the complement of the distance to the center of the array, in the "infinity norm" sense.
N/2 - max(|X - (N-1)/2|, |Y - (N-1)/2|).
This assigns the value 0 for A, 1 for B and so on.
To avoid the half integers, you can use
(N - min(|2X - N + 1|, |2Y - N + 1|) / 2.
The max and abs functions may involve hidden ifs, but you can't avoid that.
def Ring(X, Y, N):
return (N - max(abs(2 * X - N + 1), abs(2 * Y - N + 1))) // 2
for N in range(1, 8):
for X in range(N):
for Y in range(N):
print(chr(Ring(X, Y, N) + 65), '', end= '')
print()
print()
A
A A
A A
A A A
A B A
A A A
A A A A
A B B A
A B B A
A A A A
A A A A A
A B B B A
A B C B A
A B B B A
A A A A A
A A A A A A
A B B B B A
A B C C B A
A B C C B A
A B B B B A
A A A A A A
A A A A A A A
A B B B B B A
A B C C C B A
A B C D C B A
A B C C C B A
A B B B B B A
A A A A A A A

Categories