Python string length generate output - python

I am trying to create ruler by print, it should look like this for input value 5:
Im trying to change in my code numbers to symbols, my code is:
length = str(input("Enter the ruler length = "))
def ruler(string):
top = []
top_out = []
bottom = []
for i in range(length):
top.append((i+1)//10)
bottom.append((i+1)%10)
for i in range(length):
if ((i+1)//10) == 0:
top_out.append(" ")
elif (((i+1)//10) in list(sorted(set(top)))) and (((i+1)//10) not in top_out):
top_out.append(((i+1)//10))
else:
top_out.append(" ")
print (''.join(list(map(str, top_out))))
print (''.join(list(map(str,bottom))))
print (string)
How to correct it to get appropriate output format of a ruler?

Ruler printing can be down by pretty small function like this,
def print_ruler(n):
print('|....'*(n)+'|')
print(''.join(f'{i:<5}' for i in range(n+1)))
Execution:
In [1]: print_ruler(5)
|....|....|....|....|....|
0 1 2 3 4 5
In [2]: print_ruler(10)
|....|....|....|....|....|....|....|....|....|....|
0 1 2 3 4 5 6 7 8 9 10
In [3]: print_ruler(15)
|....|....|....|....|....|....|....|....|....|....|....|....|....|....|....|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
For double-digit numbers, It doesn't come to the center.
For ex: For 12, | align with number 1 or 2 it can't not make into the center of 12

Related

How to delete a matrix cell's neighbors which are the same value with it

I have a matrix as shown below (taken from a txt file with an argument), and every cell has neighbors. Once you pick a cell, that cell and all neighboring cells that containing the same number will disappear.
1 0 4 7 6 8
0 5 4 4 5 5
2 1 4 4 4 6
4 1 3 7 4 4
I've tried to do this with using recursion. I separated function four parts which are up(), down() , left() and right(). But I got an error message: RecursionError: maximum recursion depth exceeded in comparison
cmd=input("Row,column:")
cmdlist=command.split(",")
row,column=int(cmdlist[0]),int(cmdlist[1])
num=lines[row-1][column-1]
def up(x,y):
if lines[x-2][y-1]==num and x>1:
left(x,y)
right(x,y)
lines[x-2][y-1]=None
def left(x,y):
if lines[x-1][y-2]==num and y>1:
up(x,y)
down(x,y)
lines[x-1][y-2]=None
def right(x,y):
if lines[x-1][y]==num and y<len(lines[row-1]):
up(x,y)
down(x,y)
lines[x-1][y]=None
def down(x,y):
if lines[x][y-1]==num and x<len(lines):
left(x,y)
right(x,y)
lines[x][y-1]=None
up(row,column)
down(row,column)
for i in lines:
print(str(i).strip("[]").replace(",","").replace("None"," "))
When I give the input (3,3) which represents the number of "4", the output must be like this:
1 0 7 6 8
0 5 5 5
2 1 6
4 1 3 7
I don't need fixed code, just the main idea will be enough. Thanks a lot.
Recursion error happens when your recursion does not terminate.
You can solve this without recursing using set's of indexes:
search all indexes that contain the looked for number into all_num_idx
add the index you are currently at (your input) to a set tbd (to be deleted)
loop over the tbd and add all indexed from all_num_idx that differ only in -1/+1 in row or col to any index thats already in the set
do until tbd does no longer grow
delete all indexes from tbd:
t = """4 0 4 7 6 8
0 5 4 4 5 5
2 1 4 4 4 6
4 1 3 7 4 4"""
data = [k.strip().split() for k in t.splitlines()]
row,column=map(int,input("Row,column:").strip().split(";"))
num = data[row][column]
len_r =len(data)
len_c = len(data[0])
all_num_idx = set((r,c) for r in range(len_r) for c in range(len_c) if data[r][c]==num)
tbd = set( [ (row,column)] ) # inital field
tbd_size = 0 # different size to enter while
done = set() # we processed those already
while len(tbd) != tbd_size: # loop while growing
tbd_size=len(tbd)
for t in tbd:
if t in done:
continue
# only 4-piece neighbourhood +1 or -1 in one direction
poss_neighbours = set( [(t[0]+1,t[1]), (t[0],t[1]+1),
(t[0]-1,t[1]), (t[0],t[1]-1)] )
# 8-way neighbourhood with diagonals
# poss_neighbours = set((t[0]+a,t[1]+b) for a in range(-1,2) for b in range(-1,2))
tbd = tbd.union( poss_neighbours & all_num_idx)
# reduce all_num_idx by all those that we already addded
all_num_idx -= tbd
done.add(t)
# delete the indexes we collected
for r,c in tbd:
data[r][c]=None
# output
for line in data:
print(*(c or " " for c in line) , sep=" ")
Output:
Row,column: 3,4
4 0 7 6 8
0 5 5 5
2 1 6
4 1 3 7
This is a variant of a "flood-fill-algorythm" flooding only cells of a certain value. See https://en.wikipedia.org/wiki/Flood_fill
Maybe you should replace
def right(x,y):
if lines[x-1][y]==num and y<len(lines[row-1]):
up(x,y)
down(x,y)
lines[x-1][y]=None
by
def right(x,y):
if lines[x-1][y]==num and y<len(lines[row-1]):
lines[x-1][y]=None
up(x - 1,y)
down(x - 1,y)
right(x - 1, y)
and do the same for all the other functions.
Putting lines[x-1][y]=None ensure that your algorithm stops and changing the indices ensure that the next step of your algorithm will start from the neighbouring cell.

Multiplication Tables in Python

this is my code right now:
loop_count = 1
for i in range(mystery_int):
for x in range(1,mystery_int):
print(x*loop_count, end=" ")
print (loop_count)
loop_count+=1
this is what it is supposed to print:
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
But it prints:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
5 10 15 20 5
You need to range till mystery_int + 1 because in range, second argument is exclusive. So, for example, range(1,6) gives numbers from 1 to 5.
Also, I added an empty print() which basically adds a newline to match with desired output.
Using end='\t' further aligns output properly.
loop_count = 1
mystery_int = 5
for i in range(mystery_int):
for x in range(1, mystery_int + 1):
print(x * loop_count, end='\t')
print()
loop_count += 1
the range for x should be range(1,mystery_int+1), and you also incorrectly print loop_count at the end of each line (which I replaced with the empty string, just to produce a newline).
loop_count = 1
for i in range(mystery_int):
for x in range(1,mystery_int+1):
print(x*loop_count, end=" ")
print('')
loop_count+=1
Note that the loop_count variable is not really needed. You could write the program as:
for i in range(1,mystery_int+1):
for x in range(1,mystery_int+1):
print(x*i, end=" ")
print('')
or even better as:
for i in range(1,mystery_int+1):
print(*[x*i for x in range(1,mystery_int+1)], sep=" ")
you are running on two for loops in addition to using another counter, i would recommend sticking only to the loops:
for i in range(1,mystery_int+1):
for x in range(1,mystery_int+1):
print(i*x, end=" ")
print("") # new line

How to make a grid with integers in python?

I have the following code which has to print out a board with numbers according to the size the user specified (for instance 3 means a 3 x 3 board):
n = d * d
count = 1
board = []
for i in range(d):
for j in range(d):
number = n - count
if number >= 0 :
tile = number
board.append[tile]
else:
exit(1)
count += 1
print(board)
I need to get this in a grid, so that the board is 3 x 3 in size ike this:
8 7 6
5 4 3
2 1 0
What I tried to do is to get each row in a list (so [8 7 6] [5 4.. etc) and then print those lists in a grid. In order to do that, I guess I would have to create an empty list and then add the numbers to that list, stopping after every d, so that each list is the specified length.
I now have a list of the numbers I want, but how do I seperate them into a grid?
I would really appreciate any help!
Here a function that takes the square size and print it.
If you need explanation don't hesitate to ask.
def my_print_square(d):
all_ = d * d
x = list(range(all_))
x.sort(reverse=True) # the x value is a list with all value sorted reverse.
i=0
while i < all_:
print(" ".join(map(str, x[i:i+d])))
i += d
my_print_square(5)
24 23 22 21 20
19 18 17 16 15
14 13 12 11 10
9 8 7 6 5
4 3 2 1 0
By default the print() function adds "\n" to the end of the string you want to print. You can override this by passing in the end argument.
print(string, end=" ")
In this case we are adding a space instead of a line break.
And then we have to print the linebreaks manually with print() at the end of each row.
n = d * d
count = 1
max_len = len(str(n-1))
form = "%" + str(max_len) + "d"
for i in range(d):
for j in range(d):
number = n - count
if number >= 0 :
tile = number
else:
exit(1)
count += 1
print(form%(tile), end=" ")
print()
EDIT: by figuring out the maximum length of the numbers we can adjust the format in which they're printed. This should support any size of board.
You can create the board as a nested list, where each list is a row in the board. Then concatenate them at the end:
def get_board(n):
# get the numbers
numbers = [i for i in range(n * n)]
# create the nested list representing the board
rev_board = [numbers[i:i+n][::-1] for i in range(0, len(numbers), n)]
return rev_board
board = get_board(3)
# print each list(row) of the board, from end to start
print('\n'.join(' '.join(str(x) for x in row) for row in reversed(board)))
Which outputs:
8 7 6
5 4 3
2 1 0
If you want to align the numbers for 4 or 5 sized grids, just use a %d format specifier:
board = get_board(4)
for line in reversed(board):
for number in line:
print("%2d" % number, end = " ")
print()
Which gives an aligned grid:
15 14 13 12
11 10 9 8
7 6 5 4
3 2 1 0

Line up numbers in multiple lines

world!
I'm stuck at a basic question.
We're using simple commands for these questions (format, if, while, and all basics).
I came as far as to be able to produce this:
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
by using the following code:
number= 0
while number<= 0:
number = input("Give a number which is bigger than 0 : ")
if number.isdigit():
number=int(number)
else:
print("Give an integer")
number= 0
for x in range(number):
for y in range(1,number+1):
print(" {}{} ".format('',y), end='' )
print('')
The problem comes with the next question:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Unfortunately I'm stuck at being able to change the code so it will follow the pattern shown above.
Thanks in advance!
You just need to take a new variable and increment it in every iteration:
number= 0
while number<= 0:
number = input("Give a number which is bigger than 0 : ")
if number.isdigit():
number=int(number)
else:
print("Give an integer")
number= 0
z=0
for x in range(number):
for y in range(1,number+1):
z += 1
print(" {}{:<3} ".format('',z), end='' )
print('')
Output:
>>>
Give a number which is bigger than 0 : 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
You can also do it in for loop instead of two:
for i in range(number*number):
i+=1
print(" {}{:<3} ".format('',i), end='' )
if i%number==0:
print('')

Multiplication Table For Python in IEP?

I Am using python 3.3 with IEP and i am trying to make a multiplication table that is nice an orderly. Everywhere i look online says it will be nice but it ends up just being 1 row and long where i want
1 2 3 4
2 4 6 8
3 6 9 12
the code i find is generally like this... SO whats wrong with it?
def main():
i = 1
print("-" * 50)
while i < 11:
n = 1
while n <= 10:
print("%4d" % (i * n),)
n += 1
print("")
i += 1
print("-" * 50)
main()
Because there is a line break after each print
Change 7th line to
print("%4d" % (i * n), end=" ")
The problem is right here:
print("%4d" % (i * n),)
Each print call implicitly puts a line break at the end of the output, but you can change that by providing the end keyword argument to print().
You can do something like this:
In [1]: def print_table(size):
...: for i in range(1, size+1):
...: print(''.join('{:>4d}'.format(i*j) for j in range(1, size+1)))
...:
In [2]: print_table(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

Categories