printing 2 stars using strings side by side - python

Without using the function call, how can I modify my string to have the stars come out as side by side?
This is what I did:
print(" *\n * *\n * *\n * *\n * * * * * *\n"
" * *\n * *\n **********" , end = "\n *\n * *\n * *\n * *\n * * * * * *\n"
" * *\n * *\n **********" )
but this results in the stars coming out as top and bottom. I want it to print side by side.

You could use a triple quoted multi-line string to create an "arrow template" then utilize .splitlines() and zip() to print them side by side(with optional spacing between).
UP_ARROW = """
*
* *
* *
* *
* * * * * *
* *
* *
**********
""".strip("\n").splitlines()
for arrows in zip(UP_ARROW, [" "] * len(UP_ARROW), UP_ARROW):
print(*arrows)
Output:
* *
* * * *
* * * *
* * * *
* * * * * * * * * * * *
* * * *
* * * *
********** **********

#pass one arrow in a variable y
y = ''' *\n * *\n * *\n * *\n * * * * * *\n * *\n * *\n **********'''
#split on the linebreak
spl = y.split('\n')
#get width of the arrow
max_len = max([len(x) for x in spl])
#compute space for new arrow points as max width - position of last element
#of first arrow and repeat after space
new = [x + (max_len - len(x))*' ' +x for x in spl]
#join back on linebreaks
new = '\n'.join(new)
print(new)
* *
* * * *
* * * *
* * * *
* * * * * * * * * * * *
* * * *
* * * *
********** **********

Related

How to print following empty up side down pattern

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

Create a histogram in Python

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:
*
*
*
*
*
* * *
* * *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *

printing shapes in one line in python

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

How to make the output appear vertically?

import random
Bins=1
while Bins!=0:
Bins = input("Masukkan jumlah bin antara 1-25(0 untuk berhenti): ")
Bins = eval(Bins)
if Bins==0:
print("Done! Program selesai.")
break
elif Bins>1:
x=[]
c=random.randint(0,10000)
for i in range(Bins):
x.append(c)
c=random.randint(0,10000-c)
if sum(x)!=10000:x.append(10000-sum(x))
else:x.append(0)
elif Bins==1: x=[10000]
if Bins<0 or Bins>25:
print("Maaf, hanya menerima angka 1-25")
continue
tmp=-1
for i in range(Bins):
tmp=round(100/Bins*i)+1
tmp1=round(100/Bins*(i+1))
print((str(tmp)+"-"+str(tmp1)).rjust(6)+" :"+"*"*(x[i]//100)+"("+str(x[i])+")")
This is how the output appear so far
Masukkan jumlah bin antara 1-25(0 untuk berhenti): 3
1-33 :*************************************************************************************(8529)
34-67 :*************(1302)
68-100 :*************************************************************************(7321)
But i need to make it appear vertically
And how to make the output as "Maaf, hanya menerima angka 1-25"(Sorry, only number 1-25 allowed) if the user input alphabetical character?
Thankyou.
With minimizing mods to your code.
import random
def print_words_vertical(lst):
'''
Print words in columns
lst is a list of strings
Each string is comma separated words
'''
words_list = [x.split(',') for x in lst]
# Longest word sublist
longest_word_list = max(words_list, key=len)
# Longest individual word
longest_word = max([word for sublist in words_list for word in sublist], key = len)
widest_width = len(longest_word)
# Vertical Print
for index in range(len(longest_word_list), -1, -1):
for sublist in words_list:
if index < len(sublist):
# This sublist has enough word to show at this index
print(sublist[index].center(widest_width), end ='')
else:
# Insert space since we don't have a word for this column
print(' '*widest_width, end = '')
print() # Newline between rows
print()
Bins=1
while Bins!=0:
Bins = input("Masukkan jumlah bin antara 1-25(0 untuk berhenti): ")
Bins = int(Bins) # Preferable to use int() function to convert number to int since eval is unsafe
if Bins==0:
print("Done! Program selesai.")
break
elif Bins>1:
x=[]
c=random.randint(0,10000)
for i in range(Bins):
x.append(c)
c=random.randint(0,10000-c)
if sum(x)!=10000:x.append(10000-sum(x))
else:x.append(0)
elif Bins==1: x=[10000]
if Bins<0 or Bins>25:
print("Maaf, hanya menerima angka 1-25")
continue
tmp=-1
# Capture bin information into a comma delimited string s
lst = []
for i in range(Bins):
tmp=round(100/Bins*i)+1
tmp1=round(100/Bins*(i+1))
# Append bin information into string, with commas between major units
lst.append((str(tmp)+"-"+str(tmp1)).rjust(6)+" "+","+"*,"*(x[i]//100)+"("+str(x[i])+")")
# Vetrical print bins
print_words_vertical(lst)
Example Run
Masukkan jumlah bin antara 1-25(0 untuk berhenti): 10
(7701)
*
*
*
*
*
*
* (7048)
* *
(6886) * *
* * *
* * *
* * *
* * *
* * *
* * *
(6151) * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * *
* * * * (5104)
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
* (3000) * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * (1914) * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * * * (1376) *
* * * * * * * *
* * * * * * * *
* * * * * * * *
* * * * * (980) * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * (513) * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
1-10 11-20 21-30 31-40 41-50 51-60 61-70 71-80 81-90 91-100

How can i display a nested box inside the terminal using python with minimum codes?

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

Categories

Resources