How to print following empty up side down pattern - python

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

Related

printing 2 stars using strings side by side

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

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

Python Loop Reverse Diamond

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

Categories

Resources