Printing strings in a number array - python

I'm trying to print strings in a matrix. But I couldn't find a solution for that.
game_size = 3
matrix = list(range(game_size ** 2))
def board():
for i in range(game_size):
for j in range(game_size):
print('%3d' % matrix[i * game_size + j], end=" ")
print()
board()
position = int(input("Where to replace ?"))
matrix[position] = "X"
board()
First it prints this as exactly what I want
0 1 2
3 4 5
6 7 8
Where to replace ?5
Then It came up with an error;
TypeError: %d format: a number is required, not str
How can I solve this problem.
I want my output like;
0 1 2
3 4 X
6 7 8
Also X should be stored in array, just printing that doesn't work
Output should be same format as it is.

You are currently using a format string which requires that all the inputs are integers. I've changed this to using f-strings in the solution below.
game_size = 3
matrix = list(range(game_size ** 2))
def board():
for i in range(game_size):
for j in range(game_size):
print(f'{matrix[i * game_size + j]}'.rjust(3), end=" ")
print()
board()
position = int(input("Where to replace ?"))
matrix[position] = "X"
board()
Output with game_size=3:
0 1 2
3 4 5
6 7 8
Where to replace ?5
0 1 2
3 4 X
6 7 8
Output with game_size=5:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
Where to replace ?4
0 1 2 3 X
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

Related

How to print following pattern getting issue with spaces?

I am trying to write the code but not getting how to achieve expected output
Causing issue with space and not able to make proper judgement how to get exact spaces after every iteration
My code :
n=15
cnt=0
lst=[str(' ') for x in range(1,n+1)]
initial_length=len(''.join(lst))
print(initial_length)
for row in range(1,n+1):
lst[cnt-1]=str(row)
cnt=cnt-1
print(' '.join(lst))
Output of above code is not as expected output
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Expected output :
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
7 6 5 4 3 2 1
8 7 6 5 4 3 2 1
9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
14 13 12 11 10 9 8 7 6 5 4 3 2 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Another approximation, by knowing the quantity of spaces in advance using a recursive function:
def findDigits(N):
if N <= 1:
return N
# Changing number to string
s = str(N)
# Add length of number to total_sum
return len(s) + findDigits(N - 1)
def print_inverse_pyramid(n):
# Calculate number of total digits until n
total_digits = findDigits(n)
# Print the pyramid
for row in range(1, n + 1):
total_digits -= len(str(row))
l_r = [str(i) for i in range(row, 0, -1)]
print(" " * (total_digits + (n - row)) + " ".join(l_r))
print_inverse_pyramid(15)
You have to account for larger digits taking up more space, which means that when creating the list that contains spaces, you need to multiply the space by how many digits are in that number which you can get by len(str(number)):
n = 15
# create a list containing how many spaces each number will take up
# in reverse order because the figure is reverse
lst = [' ' * len(str(x)) for x in range(n, 0, -1)]
# go over each number
for x in range(1, n + 1):
# replace the digit in its place from end
# by the string represantion of itself
lst[-x] = str(x)
# print joined list
print(' '.join(lst))
Also:
I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Don't have space around = if it is used as a part of keyword argument (func(arg='value')) but have space around = if it is used for assigning a value (variable = 'some value'). Have space around operators (+-/ etc.: value = x + y(except here value += x + y)). Have two blank lines around function and class declarations. Object method definitions have one blank line around them.
Quick and dirty: 'looking' at the last line
n = 15
def serie(n):
return ' '.join([str(j) for j in range(n, 0, -1)])
maxlen = len(serie(n))
for i in range(1, n +1):
s = serie(i)
print(" " * (maxlen - len(s)) + s)
With math, computing the length as the sum of the int of the log10 of values and adding for the spaces
import math
n = 15
def lenserie(n):
return sum(map(lambda i : int(math.log(i, 10)) + 1 ,range(1, n+1))) + (n-1)
maxlen = lenserie(n)
for i in range(1, n+1):
print(" " * (maxlen - lenserie(i)) + " ".join([str(i) for i in range(i, 0, -1)]))

Formating Print in Python

Hi everyone I have this code :
n=int(input())
for i in range(1,n+1):
for j in range(1,n+1):
print(i*j)
the output is this:
1
2
3
4
5
2
4
6
8
10
3
6
...
but I want to get output like this :
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
I Don't know what to do for print like this.
Pythons print function automatically print a newline each time the function is called. but you can set what it will print at the end of the line, with adding end='' for nothing or for space end=' '.
In you case you can try this bellow:
n=int(input())
for i in range(1,n+1):
for j in range(1,n+1):
print(i*j, end = ' ')
print()
And the print at the end will print a newline after each completion of the first loop.
Finally you output will be like this:
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Python 2.x:
n=int(input())
for i in range(1, n + 1):
val = '';
for j in range(1, n + 1):
sep = '' if(j == 5) else ' '
val += (str) (i * j) + sep
print(val)
Python 3.x:
n=int(input())
for i in range(1, n + 1):
for j in range(1, n + 1):
print(i*j, end = ' ')
print()
Output:
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
n = int(input())
for i in range(1,n + 1):
count = 0
for j in range(1, n + 1):
print(i * j, end = ' ')
count += 1
if count % (n) == 0:
count = 0
print()
I initialized a counter variable and if count mod n is 0, then I assigned the counter to 0 and print a new line.
This is the output
5
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

List to Pandas dataframe where dimensions of dataframe have to be specified

I would like to convert a list to a dataframe.
list = [ '1', '2' , '3','4','5','6','7','8',....]
and I want to have 4 columns, so the dataframe looks like
1
2
3
4
5
6
7
8
etc.
Kind regards,
Wokter
This would be one way:
First create a list of lists with the N-sized chunks (N=4 in this case).
Then create the dataframe.
l = list(range(1,41))
def chunks(l, n):
"""
Yield successive n-sized chunks from list l.
"""
for i in range(0, len(l), n):
yield l[i:i + n]
N = 4
df = pd.DataFrame(list(chunks(l, N)))
Result will be:
0 1 2 3
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 13 14 15 16
4 17 18 19 20
5 21 22 23 24
6 25 26 27 28
7 29 30 31 32
8 33 34 35 36
9 37 38 39 40
use numpy to pad it and reshape it
import math
l = [ '1', '2' , '3','4','5','6','7','8', '9']
pd.DataFrame(np.pad(np.array(l),(0,4-len(l)%4)).reshape(math.ceil(len(l)/4), 4))
0
1
2
3
0
1
2
3
4
1
5
6
7
8
2
9
0
0
0
Use np.array_split if the size of your list can't be divided evenly
l= ['1','2','3','4','5','6','7','8','9']
pd.DataFrame(np.array_split(l,(4,-1)))
0 1 2 3
0 1 2 3 4
1 5 6 7 8
2 9 None None None
fillna() if you need to fill None values
pd.DataFrame(np.array_split(l,(4,-1))).fillna(0)
0 1 2 3
0 1 2 3 4
1 5 6 7 8
2 9 0 0 0

Number pattern using nested loop

Here is my code which prints a particular number pattern. I want my number pattern to be in perfect triangular arrangement like:
a = int(input('Enter number: '))
base = a
while base > 0:
for j in range(1, a + 1):
print(' ' * (2 * j - 2), end = '')
for i in range(1, base + 1):
print(str(i), end = ' ')
print()
base -= 1
The output:
Enter number: 5
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Enter number: 7
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
The program works fine for numbers < 10 but when I input a number > 10 it gives a distorted pattern.
For example:
Enter number: 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
So is there a way to make the pattern right?
If you want to have the same result for two digit numbers, you have to format your string. Here how it also works for two digit results:
a = int(input('Enter number: '))
base = a
while base > 0:
for j in range(1, a + 1):
print(' ' * (2 * j - 2), end = '')
for i in range(1, base + 1):
print('{0:>2}'.format(str(i)), end = ' ')
print()
base -= 1
Result for 15:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Some adjustments and str.rjust will do the trick:
a = base = 15
while base > 0:
for j in range(a):
print(' ' * 3 * j, end='')
for i in range(base):
print(str(i+1).rjust(3), end='')
print()
base -= 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
You might use rjust method of str, it does:
Return a right-justified string of length width. Padding is done using
the specified fill character (default is a space).
Simple example usage:
numbers = [1, 10, 10, 1000, 10000]
for n in numbers:
print(str(n).rjust(5))
Output:
1
10
10
1000
10000
Note that rjust requires at least one argument: width, if original str is shorther than width leading spaces (or other characters if specified) will be added to get str of length equal to width, otherwise original str will be returned.

Creating a number list with nested For loops in Python

I've been working on this now for well over four hours and i've tried to check several resources.
I'm trying to get something like this:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
My current code for this is:
for i in range(10):
print(i, end = '')
for j in range(10):
print(j, end = '')
print()
which prints this:
00123456789
10123456789
20123456789
30123456789
40123456789
50123456789
60123456789
70123456789
80123456789
90123456789
So I just need to get rid of the very most left-hand side. Additionally, I'm trying to produce something that looks like this:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
And I can get it from this:
triangle = ''
n = 9
for i in range(0, n+1):
triangle = triangle + (str(i))
print(triangle)
print()
for i in range(11):
for j in range(0+i):
print(j,end=" ")
print()
The problem with the first one is there isn't two for loops, one nested in the other. The problem with the second one is that I have range at 11 to get it to print to 9.
Lastly, I'm trying for this:
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
Which I've been getting with this:
x = 10
for i in range (10):
print (*range (x, x+i))
x += i
But I need two for loops. I feel like I'm very close, but just can't get the finished product.
Thanks.
For the first instance, try this:
print('', end = '')
For the second instance, the mistake is that you are adding 0 to the second for loop. Change it to:
for j in range(0, 1+i):
The thing with range is that it goes until one number lower. Have a look at docs
For the last one, you can use the following code, where y starts at 10.
y = 10
for i in range(0,10):
for j in range(0, i):
print(y + j, end=' ')
print('')
y += i
Issue with first code is that you are printing i , you do not need to print i . Code would be something like -
for i in range(10):
for j in range(10):
print(j, end = ' ')
print()
For the rest of the question, if you are getting the answer without nested loops, why do you need nested loops?
Here is how to go about it -
First is very simple
ht = 10
y = range(ht)
"\n".join(map(lambda x: " ".join(map(str,x)), [y]*ht))
Second one is a bit interesting
ht = 10
y = range(ht)
for i in range(1, ht+1):
print " ".join(map(str, y[0:i]))
Third one
start = 10
ht = 9
limit = (ht*(ht+1))/2 # using the sum of n to find out total elements
y = range(start, limit+1)
for i in range(1, ht+1):
print " ".join(map(str, y[0:i]))
y = y[i:]
The complicated map(str, y) is only to get a string to be printed.
Is this what you want?

Categories

Resources