I didn't know how to describe it in the question properly, so I'll try again here.
I have to solve this question where my code should print different types of squares. I have all of that figured out, however, I'm stuck at the printing part.
So, I start by inputting 4 as the size, and it results in different types of squares being made. For example, these two:
first = ""
for j in range(size-1):
first += "*" * size + "\n"
first += "*" * size
two = ""
for j in range(size-1):
if j == 0:
two += "*" * size + "\n"
else:
two += "*" + ((size - 2) * " ") + "*" + "\n"
two += "*" * size
Now, I have to print them like this:
**** ****
**** * *
**** * *
**** ****
separated by a '\t'.
Since these squares are 'stored' in different strings, this is unfamiliar territory for me as the cursor is at the end of the first square. I don't know what to do, help pls.
There are many ways for that, one is here:
>>> v = '\n'.join([i+'\t' + j for i,j in list(zip([i for i in first.split('\n') if i], [ i for i in two.split('\n') if i]))])
>>> print(v)
**** ****
**** * *
**** * *
**** ****
What i did:
Splitted both strings at newline character, then took corresponding parts and joined them by tab in between, then assembled the whole string.
You can change the data structure you use. Let the square will be not a string, but list of strings, where each string is line should be printed.
Then you can for each line write line_first + '\t' + line_two and print it.
This code worked as you expect.
first = []
for j in range(size - 1):
first.append("*" * size)
first.append("*" * size)
two = []
for j in range(size - 1):
if j == 0:
two.append("*" * size)
else:
two.append("*" + ((size - 2) * " ") + "*")
two.append("*" * size)
for f, t in zip(first, two):
print(f + '\t' + t)
I would like to print the following pattern in Python 3.5 (I'm new to coding):
*
***
*****
*******
*********
*******
*****
***
*
But I only know how to print the following using the code below, but not sure how to invert it to make it a complete diamond:
n = 5
print("Pattern 1")
for a1 in range (0,n):
for a2 in range (a1):
print("*", end="")
print()
for a1 in range (n,0,-1):
for a2 in range (a1):
print("*", end="")
print()
*
**
***
****
*****
****
***
**
*
Any help would be appreciated!
Since the middle and largest row of stars has 9 stars, you should make n equal to 9. You were able to print out half of the diamond, but now you have to try to make a function that prints a specific number of spaces, then a specific number of stars. So try to develop a pattern with the number of spaces and stars in each row,
Row1: 4 spaces, 1 star, 4 spaces
Row2: 3 spaces, 3 stars, 3 spaces
Row3: 2 spaces, 5 stars, 2 spaces
Row4: 1 space, 7 stars, 1 space
Row5: 0 spaces, 9 stars, 0 spaces
Row6: 1 space, 7 stars, 1 space
Row7: 2 spaces, 5 stars, 2 spaces
Row8: 3 spaces, 3 stars, 3 spaces
Row9: 4 spaces, 1 star, 4 spaces
So what can you deduce? From row 1 to (n+1)/2, the number of spaces decreases as the number of stars increase. So from 1 to 5, the # of stars = (row number * 2) - 1, while # of spaces before stars = 5 - row number.
Now from row (n+1)/2 + 1 to row 9, the number of spaces increase while the number of stars decrease. So from 6 to n, the # of stars = ((n+1 - row number) * 2) - 1, while # of spaces before stars = row number - 5.
From this information, you should be able to make a program that looks like this,
n = 9
print("Pattern 1")
for a1 in range(1, (n+1)//2 + 1): #from row 1 to 5
for a2 in range((n+1)//2 - a1):
print(" ", end = "")
for a3 in range((a1*2)-1):
print("*", end = "")
print()
for a1 in range((n+1)//2 + 1, n + 1): #from row 6 to 9
for a2 in range(a1 - (n+1)//2):
print(" ", end = "")
for a3 in range((n+1 - a1)*2 - 1):
print("*", end = "")
print()
Note that you can replace n with any odd number to create a perfect diamond of that many lines.
Here is a solution base on height equals to top to the middle, or half of the height. For example, height is entered as 4(7) or 5(9) below. This method will yield odd number actual height
h = int(input("please enter diamond's height:"))
for i in range(h):
print(" "*(h-i), "*"*(i*2+1))
for i in range(h-2, -1, -1):
print(" "*(h-i), "*"*(i*2+1))
# please enter diamond's height:4
# *
# ***
# *****
# *******
# *****
# ***
# *
#
# 3, 2, 1, 0, 1, 2, 3 space
# 1, 3, 5, 7, 5, 3, 1 star
# please enter diamond's height:5
# *
# ***
# *****
# *******
# *********
# *******
# *****
# ***
# *
#
# 4, 3, 2, 1, 0, 1, 2, 3, 4 space
# 1, 3, 5, 7, 9, 7, 5, 3, 1 star
Here is another solution base on height equals to top to the bottom, or the actual total height. For example, height is entered as 7 or 9 below. When the user enters an even number for height, the diamond will be slightly slanted.
h = int(input("please enter diamond's height:"))
for i in range(1, h, 2):
print(" "*(h//2-i//2), "*"*i)
for i in range(h, 0, -2):
print(" "*(h//2-i//2), "*"*i)
# please enter diamond's height:7
# *
# ***
# *****
# *******
# *****
# ***
# *
#
# 3, 2, 1, 0, 1, 2, 3 space
# 1, 3, 5, 7, 5, 3, 1 star
#
# please enter diamond's height:9
# *
# ***
# *****
# *******
# *********
# *******
# *****
# ***
# *
#
# 4, 3, 2, 1, 0, 1, 2, 3, 4 space
# 1, 3, 5, 7, 9, 7, 5, 3, 1 star
I learned a very simple solution today and would like to share it. :)
num = 9
for i in range(1, num+1):
i = i - (num//2 +1)
if i < 0:
i = -i
print(" " * i + "*" * (num - i*2) + " "*i)
The logic is the following:
(A space is represented as "0" here.)
# i = 1 | new i = 1 - 5 = -4 | * : 9 - 8 = 1 | 0000 + * + 0000
# i = 2 | new i = 2 - 5 = -3 | * : 9 - 6 = 3 | 000 + *** + 000
# i = 3 | new i = 3 - 5 = -2 | * : 9 - 4 = 5 | 00 + ***** + 00
# i = 4 | new i = 4 - 5 = -1 | * : 9 - 2 = 7 | 0 + ******* + 0
# i = 5 | new i = 5 - 5 = 0 | * : 9 - 0 = 9 | *********
# i = 6 | new i = 6 - 5 = 1 | * : 9 - 2 = 7 | 0 + ******* + 0
# i = 7 | new i = 7 - 5 = 2 | * : 9 - 4 = 5 | 00 + ***** + 00
# i = 8 | new i = 8 - 5 = 3 | * : 9 - 6 = 3 | 000 + *** + 000
# i = 9 | new i = 9 - 5 = 4 | * : 9 - 8 = 1 | 0000 + * + 0000
The result would be the following:
*
***
*****
*******
*********
*******
*****
***
*
As pointed out by Martin Evans in his post: https://stackoverflow.com/a/32613884/4779556 a possible solution to the diamond pattern could be:
side = int(input("Please input side length of diamond: "))
for x in list(range(side)) + list(reversed(range(side-1))):
print('{: <{w1}}{:*<{w2}}'.format('', '', w1=side-x-1, w2=x*2+1))
Simplest Answer
n=5
for i in range(1,n+1):
print ((n-i)*(" ")+(i*" *"))
for i in range(n-1,0,-1):
print((n-i)*(" ")+(i*" *"))
Hope this helps some one
Another possibility. Depending on which (space or star) one uses, (I used space) convert it to absolute value. This implementation doesn't require splitting the diamond into two loops (upper and lower halves).
def diamond(n):
star = 1
main = ''
# if required to manage zero or negative n
if n%2 == 0:
return None
if n<0:
return None
else:
for i in range(1,n+1):
string = ''
space = abs(i - int((n+1)/2))
star = n - 2 * space
string = space * ' ' + star * '*' + '\n'
main += string
# not necessary but useful to visualize diamond
#print(main)
return(main)
There are two version of this
Space between Stars
Without Space between Stars
Space between Stars
n = 4
for i in range(n):
print(' '*(n-i-1) + '* '*(i+1) )
for i in range(n):
print(' '*(i+1) + '* '*(n-i-1))
Without Space between Stars
n = 4
for i in range(n):
print(' '*(n-i-1) + '*'*((2*i)+1) )
for i in range(n):
print(' '*(i+1) + '*'*((2*((n-1)-i))-1))
side = int(input("side length: "))
count = 0
bl = 0
while count < side:
x = side - count
print (x * " ", (count * "*") * 2)
count += 2
while count >= 0:
print (bl * " ", (count * "*") * 2)
count -= 1
bl += 1
if you want both upper part and down side to be same change the count += 2 to count += 1
#author Tahir Baku
#have fun
print "\nWelcome to diamond builder"
print "\n----D.I.A.M.O.N.D B.U.I.L.D----"
diagonal=int(input("Give me the diagonal: "))
s=1
h1=1
h=(diagonal-1)/2
diagonal1=diagonal-2
while s<=diagonal:
print (' '*h+'*'*s+' '*h)
h=h-1
s=s+2
while diagonal1>=0:
print (' '*h1+'*'*diagonal1+' '*h1)
h1=h1+1
diagonal1=diagonal1-2
print('This is in python 3.7')
h=eval(input('Enter the diagonal?'))
j=1
for i in range(h,h//2,-1):
print(' '*(i-(h//2)-1),'*'*j)
j+=2
j-=4
for i in range(1,(h//2)+1,1):
print(' '*i,'*'*(j))
j-=2
simple way ...
n= 11 #input is even number 1,3,5,...
a = 1
b = 1
for a in range(n+1):
if a%2 != 0:
val = (n - a) // 2
print (" "*val + "*"*(a) + " "*val ,end = "\n")
for b in range(n-1,0,-1):
if b%2 != 0:
val2 = (n-b)//2
print (" "*val2 + "*"*(b) + " "*val2 ,end = "\n")
Output:
*
***
*****
*******
*********
***********
*********
*******
*****
***
*
Or using reverse method, first one is diamond, second one is series of diamond
import copy
n = 10 #input: size of diamon
raw = []
lst = []
re_lst = []
for a in range(n+1):
if a%2 != 0:
val = (n - a) // 2
raw = ''.join(" "*val + "*"*(a) + " "*val)
lst.append(raw)
re_lst = copy.deepcopy(lst)
lst.reverse()
#print diamond
for i in re_lst:
print(i)
for i in lst:
print(i)
print("\n")
#print series of diamond
for i in re_lst:
print(i)
for i in lst:
print(i)
a = 10
for x in range (a):
print(" " * (a - x) + "*" * (x+1) + "*" *(x))
#+ this = diamond
for x in reversed(range(a-1)):
print(" " * (a - x) + "*" * (x) + "*" *(x+1))
def pattern2(row):
s=1
c = row / 2
d = int(c)-1
for i in range(1,row+1):
if i<c:
print(" "*d,star(s))
s+=2
d-=1
elif i==(c+0.5):
print(star(row))
s=s-2
d=0
else:
print(" "*d,star(s))
s=s-2
d+=1
def star(s):
return '*'*s
def main():
row=int(input("enter the no. of row but the rows should be odd \n#special case of pattern"))
try:
a=row%2
assert a!=0 and row!=0
pattern2(row)
except:
print('Worng selection of rows for the perfect diamond.')
if __name__=="__main__":
main()
#maybe it could help
height = eval ( input ( 'How high? ' ) )
height = int (height//2)
for i in range(1, height+1):
print(' ' *(height-i+1), '*'*i + '*' * (i-1) )
for i in range (height+1, 0, -1):
print (' ' * (height+1-i), '*' * i + '*' * (i-1))
First find logic from the dressing table, then I think it's easier above all (n=11, m=(n+1)/2 = 6) :
n = int(input("Input odd number of layers: "))
m = (n+1)/2
i = 1
while i<=n :
if(i < m):
b = m-i
s = 2*i -1
else:
b = i-m
s = 2*(n-i)+1
j = 1
while j <= b:
print('.',end="") # dot or space
j += 1
j = 1
while j <= s:
print('*',end="")
j+=1
print()
i += 1
h = int(input('Height -> '))
for i in range(h):
if i <= (h // 2):
print(' ' * (h // 2 - i), end='')
print('*' * (i + 1), end='')
print('*' * (i + 1))
else:
print(' ' * abs((h // 2 - i)), end='')
print('*' * (h - i), end='')
print('*' * (h - i))
length = 5
for i in range(1,length,2):
space = length//2 -i//2
print(" "*space, end="")
print('*'*i)
for j in range(length, 0, -2):
space = length//2 - j//2
print(" "*space, end="")
print('*'*j)
#coder_rishabh_darmwal
#it_is_a_simple_codewith_an_easy_logic
row=int(input('enter the no. of rows')
for i in range(row):
if i<=row//2:
for j in range(row//2-i):
print(" ",end='')
for k in range(i*2-1):
print("*",end="")
print()
else:
for j in range(i-row//2):
print(" ",end="")
for k in range((row-i)*2-1):
print("*",end="")
print()
#the output will be
[output for row=30][1]
#i also wrote a programme fro hollow diamonds
row=int(input('enter the no. of rows')
for i in range(row):
if i<=row//2:
for j in range(row//2-i):
print(" ",end='')
for k in range(i*2-1):
if k==0 or k==i*2-2:
print("*",end="")
else:
print(' ',end='')
print()
else:
for j in range(i-row//2):
print(" ",end="")
for k in range((row-i)*2-1):
if k==0 or k==(row-i)*2-2:
print("*",end="")
else:
print(' ',end="")
print()
[out for hollow rhombus row=20
][2]
[1]: https://i.stack.imgur.com/3j0bx.png
[2]: https://i.stack.imgur.com/tCxI3.png
I am trying to print out an arrow head using *s.
So far my code looks like this.
def head(n):
while n > 0:
print n * "*"
n = n - 1
print head(input())
and it works but if for example I enter 11, it prints this:
***********
**********
*********
********
*******
******
*****
****
***
**
*
But I want it to print like this:
*
***
*****
*******
*********
***********
Which has less arrows, but I can't figure out how to do it.
It makes the function a little simpler to think in terms of how many lines do you want:
def head(lines):
for n in range(1,lines*2,2): # count 1,3,5...
print(('*'*n).center(lines*2-1))
Output:
>>> head(5)
*
***
*****
*******
*********
Here's an alternate way to use a variable length format that is a little less obvious:
def head(lines):
for n in range(1,lines*2,2):
print('{:^{}}'.format('*'*n,lines*2-1))
use string formatting:
def head(size):
n=1
while n < size+1:
stars = n * "*"
print '{:^30}'.format(stars)
n += 2
it will center your asterisks on the field 30 chars wide.
def printHead(n):
for l in range(1,n):
print " "*(n-l)+"*"*(1 if l==1 else 2*l-1)
Each row has level-1 spaces. Then if it's the first level one start, otherwise it has 2*level-1.
>>> printHead(6)
*
***
*****
*******
*********
def head(n):
total = 2 * n - 1
s = ''
for i in xrange(1, n + 1):
k = 2 * i - 1
s += ' ' * ((total - k) / 2) + '*' * k + '\n'
return s
The number of stars on a line is equal to 2n - 1 where n is the line number.
I wouldn't call the parameter "n" in this function as it is not clear to me whether it refers to lines or stars.
You can use the center function to surround a string with whitespace, based on a specified width. You want the arrow to be centred around the longest line so you need 2 variables, one to keep track of the current line and another to remember the largest line.
You want to iterate in the opposite direction to what you have demonstrated, as you want the arrow to point up, not down.
I think this should work for you:
def head(total_lines):
for current_line in range(1, total_lines + 1):
print ((2 * current_line - 1) * "*").center(2 * total_lines - 1)
Yes, this is a homework task. But just please, if you're going to give me the code please tell me what you've done in detail. I am extremely new to this.
So the task is to print an ASCII diamond depending on what width the user inputs. I can do the first half of the diamond, just not the bottom half, for some reason I just cannot see how to do it.
Here's my code:
wid = int(input("Width: "))
i = 1
while i <= wid:
print(" " * (wid - i) + "* " * i)
i = i + 1
Which will output the following if wid = 5:
Width: 5
*
* *
* * *
* * * *
* * * * *
I tried to explain the code with comments. I hope it helps.
wid = int(input("Width: "))
#no. of lines will be double the width
#each loop prints a line.
for i in range(wid *2):
#first half of the diamond
if i<=wid:
no_of_spaces = wid - i
no_of_stars = i
print(" "*no_of_spaces + "* "*no_of_stars)
#next half of the diamond
else:
no_of_spaces = i - wid
no_of_stars = 2*wid - i
print(" "*no_of_spaces + "* "*no_of_stars)
i=1
j=input("ENTER NO =")
l=0
for i in range(i,j-((j/2)-1),1):
print (' ' * ((j+1)/2-i)+'*' *(i*2-1))
l=(j/2+1)
while (i==l):
i=1
for i in range(i,j,1):
print (' ' *((i*2)-i)+'*' *(j-i*2))
if [i==j-1]:
l=raw_input('<press enter to exit>')
You start with i = 1 and go until i > wid to make the top. To make the bottom of the diamond, you must do the reverse of what you did for the top. The code is easy, but I won't write it unless you want me to.
after your while
i=i-2
while i>0:
print(" "*(wid-i)+"* "*i)
i=i-1;
One method
The simplest way would probably be have two loops; one counting i up to width, another counting i back down to 1.
width = int(input("Width: "))
i = 1
while i < width:
print " " * (width-i) + "* " * i
i += 1
while i > 0:
print " " * (width-i) + "* " * i
i -= 1
This is a bit unattractive because it's a little clumsy, but it's simple.
Another method
Another method is to have have a loop that counts to twice the width, doing one of two things. What it does depends on if i has passed the point of maximum width or not. So it does 'up' and 'down' in the same loop, counting i from 1 up to width*2.
width = int(input("Width: "))
i = 1
while i < width*2:
if i < width:
print " " * (width-i) + "* " * i
else:
print " " * (i-width) + "* " * (2*width-i)
i += 1
This:
print " " * (width-i) + "* " * i
...is your code. Spaces count from width down to 0, *'s from 1 up to width.
And this:
print " " * (i-width) + "* " * (2*width-i)
...is the same thing but inverted. Spaces count from 0 back up to width, and the *'s go back down from width to 1. This comes into play when i exceeds width.
Width: 4
* # first half does this onward
* *
* * *
* * * *
* * * # second half does the rest downward
* *
*
And another
Another alternative, more complex way is to use a for loop on a list that contains numbers counting up and down. For example: [1, 2, 3, 2, 1]
To make this list, this code has to be. I know, it's a bit ugly:
rows = []
for i in range(1, max+1):
rows.append(i)
rows += rows[-2::-1]
Then, you see, we run the for loop off it.
width = int(input("Width: "))
rows = []
for i in range(1, width+1):
rows.append(i)
rows += rows[-2::-1] # takes a reversed list and adds it on to the end: [1, 2, 3, 2, 1]
for i in rows:
print " " * (width-i) + "* " * i
i iterates through each of the numbers in the rows list, which looks something like [1, 2, 3, 2, 1]. Then we just need one printing gizmo.
In python, there's almost always a shorter and less comprehensible way of doing for loops, and in this case, we can get rid of two extra lines by shortening the first for loop:
width = int(input("Width: "))
rows = [ i for i in range(1, width+1)] # Brain-bending way of doing a for loop
rows += rows[-2::-1]
for i in rows:
print " " * (width-i) + "* " * i
And if you're feeling a bit crazy, here's a mere two line version of the whole thing!
width = int(input("Width: "))
print "\n".join([ " "*(width-i) + "* "*i for i in [ i for i in range(1, width+1) ]+[ i for i in range(1, width+1) ][-2::-1] ])
But I don't recommend this style of coding in general.
Sorry, I got a bit carried away at the end... but the best thing I can say to you now is try everything and play around!
Hope that helps. :)
Since some good methods have been addressed, here are some fun little hacky solutions.
Here's one using Python 2.7 string.center just for shits.
import string
width = int(raw_input("Width:"))
for i in range(width):
print string.center(i * " *", width * 2 )
for i in range(width,0,-1):
print string.center(i * " *", width * 2 )
And here's an outrageous one that ouputs using HTML to center.
file = open('file.html','w')
file.write("<div align='center'>")
for i in range(width):
file.write(i * " *")
file.write("<br>")
for i in range(width,0,-1):
file.write(i * " *")
file.write("<br>")
file.write("</div>")
file.close()
import webbrowser
webbrowser.open("file.html")
check it out (for python 2.7x) :
Filled ASCII Diamond :
width = 1
width += int(raw_input('Width : '))
for i in range (1,width):
for j in range (width,i,-1):
print " ",
for j in range (1,i,1):
print " * ",
print
for i in range (width,1,-1):
for j in range (width,i,-1):
print " ",
for j in range (1,i,1):
print " * ",
print
This works!! But not in any Browser window . . .