I am trying to print 2 circles pattern in one row and two in the next row like this
Here is my Code:
cell = {}
row = 5
col = 5
for i in range(0,row):
for j in range(0,col):
if((j == 0 or j == col-1) and (i!=0 and i!=row-1)) :
cell[(i,j)] = '*'
#end='' so that print statement should not change the line.
elif( ((i==0 or i==row-1) and (j>0 and j<col-1))):
cell[(i,j)] = '*'
else:
cell[(i,j)] = " "
print(cell[(i, j)], end=" ")
print(end='\n')
And with this code I'm getting the output as follows:
what should I change in this code to make it correct?
You essentially need a template for top/bottom of a circle and the middle part of a circle.
Then you need to print enough of them per line:
nums = 7 # only squares supported
amount = 3 # shapes per line & shape rows in total
spacer = 2 # space horizontally, vertically it is 1 line
# prepare shapes
top_botton = f" {'*'*(nums-2)} "
middle = f"*{' '*(nums-2)}*"
space_h = " " * spacer
for row in range(amount * nums):
# detect which row we are in
mod_row = row % nums
# bottom or top of row
if mod_row in (0, nums-1):
print(*([top_botton]*amount), sep=space_h )
if mod_row == nums-1:
print()
# middle of row
else:
print(*([middle]*amount), sep=space_h)
Output:
# nums = 5, count = 2
*** ***
* * * *
* * * *
* * * *
*** ***
*** ***
* * * *
* * * *
* * * *
*** ***
# nums = 7, count = 3
***** ***** *****
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
***** ***** *****
***** ***** *****
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
***** ***** *****
***** ***** *****
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
***** ***** *****
The distance between the circles is handled by the sep=... of the print statement. It prints the decomposed list of (amount) shapes.
You could as well handle a "single char" printer like you did for your single cirle, but all those loops in loops and values modular checking are getting confusing fast.
for i in range(0,row):
for j in range(0,col):
if((j == 1 or j == col-1) and (i!=0 and i!=row+1)) :
cell[(i,j)] = ''
elif( ((i==0 or i==row-1) and (j>0 and j<col+1))):
cell[(i,j)] = ''
else:
cell[(i,j)] = " "
print(cell[(i,j)], end=" ")
print(end='\n')
Related
I am trying to print this following pattern , But not able to frame logic
My code :
for i in range(1,row+1):
if i == 1:
print(row * '* ')
elif i<row:
print( '* ' + ((row - 3) * 2) * ' ' + '*')
row = row - 1
else:
print('*')
Expected output :
* * * * * * * *
* *
* *
* *
* *
* *
* *
*
But my code gives me abnormal output :
* * * * * * * *
* *
* *
* *
*
*
*
*
#stacker's answer is nifty but mathematically a little overkill. This should do the trick just as well:
row = 8
print(row * '* ')
for i in range(1,row - 1):
rowlength = (row - i) * 2 - 3
print('*', end='')
print(rowlength * ' ', end='')
print('*')
print('*')
import math
row = 8;
for i in range(1,row+1):
if i == 1:
print(row * '* ')
elif i<(row * row) / (math.pi / math.sqrt(7)):
print( '* ' + ((row - 3) * 2) * ' ' + '*')
row = row - 1
else:
print('*')
Output:
* * * * * * * *
* *
* *
* *
* *
* *
* *
*
row=10
for i in range(1,row):
if i == 1:
print(row * '* ')
elif i < row:
print('* ' + (row-2)*2 * ' ' + '*')
row = row-1
elif i > row-2:
print('* ' + (row - 2) * 2 * ' ' + '*')
row = row - 1
Output:
* * * * * * * * * *
* *
* *
* *
* *
* *
* *
* *
* *
Process finished with exit code 0
Hope this helps
I'm trying to create a histogram in python
My fuction is the next one:
def hist_hor(diccionario):
dict={}
for e in diccionario:
if e in dict:
dict[e] += '*'
else:
dict[e]= '*'
for i in sorted(dict):
print(f'{i}: {dict[i]}')
histograma_horizontal(d)
It is supposed to look like this:
a: *****
b: **********
c: ************
d: ***********
e: ***************
f: ********************
g: ***************
h: *********
i: *******
j: **
but with my function it looks like this:
a: *
b: *
c: *
d: *
e: *
f: *
g: *
h: *
i: *
j: *
Besides, anyone who knows to represent it in that way too ?:
*
*
*
*
* * *
* * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
You can complete the first part without creating a new dictionary (remember to use end to prevent a new line):
NOTE - Tested in Ubuntu 20.04, using Python 3.8.
def hist_hor(diccionario):
for key, value in diccionario.items():
print(f"{key}: ", end="")
for _ in range(value):
print("*", end="")
print()
diccionario = {"a": 5, "b": 10, "c": 12, "d": 11, "e": 15,
"f": 20, "g": 15, "h": 9, "i": 7, "j": 2, }
hist_hor(diccionario)
Output:
a: *****
b: **********
c: ************
d: ***********
e: ***************
f: ********************
g: ***************
h: *********
i: *******
j: **
But if you need to create a new dictionary, use update instead of trying to manipulate indexes:
def hist_hor(diccionario):
# Do not use dict as a variable name; it shadows a builtin type
new_dicc = {}
for key, value in diccionario.items():
temp = ""
for _ in range(value):
temp += "*"
new_dicc.update({key: temp})
return new_dicc
d = hist_hor(diccionario)
for key, value in d.items():
print(f"{key}: {value}")
The output will be the same.
For the second part, get the max value first and create a reverse loop. Iterate through the values, and if the value is greater than or equal to the loop index, print an asterisk:
def hist_hor(diccionario):
m = max(diccionario.values())
for i in range(m, 0, -1):
for x in diccionario.values():
if x >= i:
print("* ", end="")
else:
print(" ", end="")
print()
Output:
*
*
*
*
*
* * *
* * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
I need to add line after line to a 2d array in python using numpy.
def read_file(file):
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
maze = np.zeros((rows, cols), dtype=int)
for line in lines:
maze = np.append(maze, line)
return maze
First I read a file and get the lines from that one. Then I am creating a 2d array using the count of lines and columns (-1 because of '\n' at the end). Then I want to append them to the array, but it looks really weird:
['0' '0' '0' ...
'* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *\n'
'* * * * * * * * * B*\n'
'*****************************************************************\n']
['0' '0' '0' ...
'* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *\n'
'* * * * * * * * * B*\n'
'*****************************************************************\n']
What am I doing wrong? Where is the error?
Expected output is a 2d array (17,65).
Something like:
[[0,0,0,0,0...0,0], [0,0,0,0...,0,0]...]
etc.
I want to generate an array from this file:
*****************************************************************
*A * * * * * *
*** * ***** * ******* *** *** * *************** * *********** * *
* * * * * * * * * * * * * * *
* ******* * ******* ******* * * * ***** * * ******* * ***** *** *
* * * * * * * * * * * * * * * * *
* ***** * *** *********** * * * *** * * * * * *** *** *** ***** *
* * * * * * * * * * * * * * * * *
*** * * *** ***** ******* ******* *** ******* * * *** * * *** ***
* * * * * * * * * * * * * * * * * * *
* ***** ***** * *** * * *** * * * ***** *** * * *** * * *** *** *
* * * * * * * * * * * * * * * * * * *
* * ***** ***** * * * *** * ******* ********* * * * ***** * * * *
* * * * * * * * * * * * * * * * * * * * *
* * * ******* *** * * * * *** ******* * * ***** *** * ***** *** *
* * * * * * * * * B*
*****************************************************************
every line is in brackets [] and after a new line a new bracket beginns.
If I get you right, you want to have all the integers in a numpy array padded with zeros. This is how I would do this.
# open and read file
file = open(data, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
maze = np.zeros((rows, cols),dtype=str)
for index,line in enumerate(lines):
for i in range(0,len(line)-1):
maze[index][i]= line[i]
return maze
this will produce this output:
[['*' '*' '*' ... '*' '*' '*']
['*' 'A' ' ' ... ' ' ' ' '*']
['*' '*' '*' ... '*' ' ' '*']
...
['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '']]
The user will be asked to enter any positive number and the output will be the following:
If he enters '1':
***
* *
***
If he enters '2':
*******
* *
* *** *
* * * *
* *** *
* *
*******
If he enters '3':
***********
* *
* ******* *
* * * *
* * *** * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
And so on. That means if the input is 'n', the output will be 'n' number of nested box in the following pattern.
PS:
Here I've tried some codes. But not getting the desired pattern.
try:
n = int(raw_input("Please Enter A Positive Number: "))
list = range(1, 4*n)
if n > 0:
for n in list:
if n % 2 == 0:
print "*" + " " * (list[-1]-2) + "*"
else:
if n:
print "*" * list[-1]
else:
pass
else:
print "You must choose any positive number."
except:
print "You must enter a number."
You could create a function to add a nesting layer to an existing box and then call this the required number of times as follows:
def add_nested(box):
new_box = []
lines = box.splitlines()
width = len(lines[0])
l1 = '*' * (width + 4)
l2 = '*{}*'.format(' ' * (width + 2))
new_box.extend([l1, l2])
for row in lines:
new_box.append('* {} *'.format(row))
new_box.extend([l2, l1])
return '\n'.join(new_box)
n = int(raw_input("Please Enter A Positive Number: "))
box = "***\n* *\n***"
for _ in range(n-1):
box = add_nested(box)
print box
So if 5 was entered, it would display:
Please Enter A Positive Number: 5
*******************
* *
* *************** *
* * * *
* * *********** * *
* * * * * *
* * * ******* * * *
* * * * * * * *
* * * * *** * * * *
* * * * * * * * * *
* * * * *** * * * *
* * * * * * * *
* * * ******* * * *
* * * * * *
* * *********** * *
* * * *
* *************** *
* *
*******************
How does it work?
The function first splits the existing box into lines and determines the width of the first line. It then creates two lines to go above and below the box (called l1 and l2). These have the correct number of * and for the new outer box. It then adds these to a list of lines. Then for each line in the existing box, it added * to the start of each line and * to the end. It then adds l2 and l1 to the end to complete the new nested box. It then returns this list of lines as a single string joined with newlines to create the new box. This function can then be called again and again to add further layers.
The code below progressively builds the top left corner of a nested set of boxes. It builds the right side by reflecting the left side, and it builds the bottom by reflecting the top.
We start with an empty base string and alternately add a star (on even lines) or a space (on odd lines) to this base; the current half-row is constructed from the base string by padding it with a star or space as appropriate.
The nested_box function does no printing, it returns a list of strings, so it's up to the calling code to do the actual printing.
def nested_box(n):
w = 2 * n
rows = []
base = ''
for i in range(w):
c = '* '[i % 2]
base += c
row = base.ljust(w, c)
rows.append(row + row[-2::-1])
return rows + rows[-2::-1]
# Test
for i in range(1, 5):
print('\n', i)
for row in nested_box(i):
print(row)
output
1
***
* *
***
2
*******
* *
* *** *
* * * *
* *** *
* *
*******
3
***********
* *
* ******* *
* * * *
* * *** * *
* * * * * *
* * *** * *
* * * *
* ******* *
* *
***********
4
***************
* *
* *********** *
* * * *
* * ******* * *
* * * * * *
* * * *** * * *
* * * * * * * *
* * * *** * * *
* * * * * *
* * ******* * *
* * * *
* *********** *
* *
***************
To run this code correctly on Python 2, put from __future__ import print_function at the top of the script. That's really only necessary for the print('\n', i) call, the box printing doesn't need it.
Just for fun, here's a "code golf" version:
def b(n):
r,a=[],''
for i in range(2*n):c='* '[i%2];a+=c;l=a.ljust(2*n,c);r+=[l+l[-2::-1]]
return'\n'.join(r+r[-2::-1])
for i in range(1, 5):print(i,b(i),sep='\n')
I have a code that loops to create a diamond, but I would want it to be reversed.
width = int(input("Please enter a width: "))
i = 1
while i < width*2:
if i < width:
print("-" * (width-i) + " *" * i + "-" * (width-i))
else:
print("-" * (i-width) + " *" * (2*width-i) + "-" * (i-width))
i += 1 [EDIT: formatting mistake]
My output is as follows:
---- *----
--- * *---
-- * * *--
- * * * *-
* * * * *
- * * * *-
-- * * *--
--- * *---
---- *----
but I want it to be like this:
* * * * *
- * * * *-
-- * * *--
--- * *---
---- *----
---- *----
--- * *---
-- * * *--
- * * * *-
* * * * *
Help would be appreciated!
width = int(input("Please enter a width: "))
i = 0
while i < width*2:
if i < width:
print("-" * i+ " *" * (width-i) + "-" * i)
else:
print("-" * ((2*width-i) -1) + " *" * (i - width + 1) + "-" * ((2*width-i) -1))
i += 1