So I have to print * in the shape of A which I did.
pattern = ""
for row in range(7):
for col in range(5):
if ((col==0 or col==4) and row!=0) or ((row==0 or row==3) and (col>0 and col<4)):
pattern = pattern + "*"
else:
pattern = pattern + " "
pattern = pattern + "\n"
pattern = pattern + " "
print(pattern, end="")
OUTPUT:
***
* *
* *
*****
* *
* *
* *
But I want to print more A horizontally.
Example: L displayed as star program 3 times looks as below
* * *
* * *
* * * * * * * * *
Please help!
I did not change a lot in your code, but thought that putting it in a function might be useful. As you can see in the last line, you now just have to call it with the number of letters you want to print. Furthermore, I added a for-loop in between yours, in order to get all the required symbols into the according line.
Lastly, I added an if/else staement that checks this is the end of the row and otherwise does not go into the next line.
def multiplePatterns(n):
pattern = ""
for row in range(7):
for i in range(n):
for col in range(5):
if ((col==0 or col==4) and row!=0) or ((row==0 or row==3) and (col>0 and col<4)):
pattern = pattern + "*"
else:
pattern = pattern + " "
if i == n-1:
pattern = pattern + "\n"
else:
pattern += " "
pattern = pattern + " "
return pattern
print(multiplePatterns(2))
The easiest way is to use a library like pyfiglet : https://pypi.org/project/pyfiglet/ .
If you want to do it yourself, python console write per line, you must print your text (ex:"AAA") line per line.
if your final goal is just that, then:
print(" *** *** ***")
print("* * * * * *")
print("* * * * * *")
print("***** ***** *****")
print("* * * * * *")
print("* * * * * *")
print("* * * * * *")
will do the job.
If your goal is to write any text, then its probably better to create some kind of "font" with each letter in a list.
Related
Write a recursive function called draw_triangle() that outputs lines of *'s to form a right side up isosceles triangle. Function draw_triangle() has one parameter, an integer representing the base length of the triangle. Assume the base length is always odd and less than 20. Output 9 spaces before the first '*' on the first line for correct formatting.
Hint: The number of '*' increases by 2 for every line drawn.
Ex: If the input of the program is: 3,
Then the function draw_triangle outputs:
*
***
If the input of the program is 19,
Then the function outputs
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
No space is output before the first asterisk on the last line when the base length is 19.
I was able to code this non-recursively as follows:
def draw_triangle(n):
lines_to_print = int(((n // 2) + 1))
spaces_to_print = 9
asts_to_print = 1
for i in range(lines_to_print):
print(spaces_to_print * ' ', end='')
print(asts_to_print * '*', end='')
print()
spaces_to_print -= 1
asts_to_print += 2
base_length = int(input())
draw_triangle(base_length)
But I cannot, for my life, figure out how to do it recursively, let alone with only one argument. What am I missing about recursion?
The simple trick here is to use the str.center() method.
def draw_triangle(n):
if n == 1:
print('*'.center(19))
else:
draw_triangle(n-2)
print((n*'*').center(19))
Test it:
draw_triangle(19)
*
***
*****
*******
*********
***********
*************
***************
*****************
*******************
One method is is to define functions to print the symbole you want to use and the spaces between them:
def print_ecart(ecart):
if (ecart == 0):
return;
print(" ", end = "")
print_ecart(ecart - 1)
def print_etoile(etoile):
if(etoile == 0):
return
print("* ", end = "")
print_etoile(etoile - 1)
def pattern(n, num):
if (n == 0):
return
print_ecart(n - 1)
print_etoile(num - n + 1)
print("");
pattern(n - 1, num)
In this case print_ecrat prints spaces and print_etoile prints the stars:
pattern(10,10)
returns:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
By printing after the recursion itself happens, you can print smaller lines over the bigger lines:
def draw_triangle(n):
spaces = 9 - n // 2 # Ensures correct spacing for each line
if n == 1:
print(spaces * ' ' + '*')
else:
draw_triangle(n-2)
print(spaces * ' ' + n * '*')
draw_triangle(19)
Well, it is a quite interesting question.
The main obstacle is that you have to preserve initial base length of triangle.
You can't save it via assigning input value to another parameter inside a recursive function because:
only one argument is allowed
assigning will work every function call.
Not sure if the following code is convenient with the conditions of the task but it may be useful to illustrate an idea of recursive functions for you:
base_length = 20
def draw_triangle(base=base_length):
if base % 2 == 0:
base = base - 1
draw_triangle(base)
else:
if base > 0:
# print(base)
# print(int(base/2 - 1))
print(' '*int((base - 2)/2+1) + '*'*(base_length - base) + ' '*int((base - 2)/2))
base = base - 2
draw_triangle(base)
elif base == 0:
return 0
draw_triangle(base=base_length)
Formally there is only one argument in this recursive function, but you have to define base_length paramater outside of the function and the function uses base_length inside.
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)
How can I change this code that instead of printing the shape below, it prints it like a lozenge (rhomboid)?
def star (m):
for i in range (m + 1):
print ("*" * i)
for i in range ( m + 1 ):
print ("*" * (m - 1))
m -= 1
Output
*
**
***
****
***
**
*
A lozenge is equilateral, a rhomboid typically not. For illustration, I will do a rhomboid, but allow it to be equilateral.
To define a function, you should first specify the domain, in this case positive ints (or include 0 if you wish).
Functions should generally return an object that can be compared with the desired output for a given input. You can then write an automated test for example outputs. In this case, the function should produce an iterable of strings. The desired output can most easily be represented as a tuple or list of strings and the function output converted if necessary.
r43 = (
'****',
' ****',
' ****',
)
def rhom(width, height):
if not(isinstance(width, int) and width > 0 and
isinstance(height, int) and height > 0):
raise ValueError('width and height must be positive ints')
stars = width * '*'
for i in range(height):
yield i * ' ' + stars
out43 = tuple(rhom(4, 3))
print(r43 == out43)
for line in out43:
print(line)
prints
True
****
****
****
I like the following a bit better because it's more symmetrical:
def star(m):
def star_line(n):
print('{s:^{f:d}s}'.format(s='*'*n, f=m))
for i in range(1,m,2):
star_line(i)
for i in range(m,0,-2):
star_line(i)
star(5)
*
***
*****
***
*
This solution uses the nice feature of Python's new(er) formatting syntax which enables you to specify the width of a field dynamically as well as the contents of the field: e.g. '{s:^{f:d}}'.format(s='*'*3, f=5) becomes '{s:^5s}'.format(s='***') which becomes ' *** '.
def print_lozenge(num):
str = '*'
str_2 = str + (num - 1) * ' *'
size = 2 * num - 1
for n in range(num):
print str.center(size, ' ')
str += ' *'
for n in range(num):
str_2 = str_2[: -2]
print str_2.center(size, ' ')
print_lozenge(5)
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
Is this what you wanted?
def star(m):
for i in range(1, m + 1):
print(("*" * i).center(m))
for i in reversed(range(1, m)):
print(("*" * i).center(m))
star(10)
Output:
*
**
***
****
*****
******
*******
********
*********
**********
*********
********
*******
******
*****
****
***
**
*
This is the assignment:
Write a python function that accepts a character and an integer and then uses that character to create a triangular structure like the example below. Make sure that the number of lines is in the range 1 to 10 and that only the first character in the user entered symbol is used if they enter more than one character.
Symbol? *
Lines? 4
*
* *
* * *
* * * *
I've got all of it except the spacing right... here's what I figured out so far.
def Triangle():
lines = -1
while lines not in range(1,11):
symbol=input("Symbol? ")
lines=input("Lines? ")
for i in range(lines + 1):
spaces = lines - i
print ((' ' * spaces) + (symbol * i))
This prints out:
*
**
***
****
Can't seem to get this right... thoughts?
Also if anyone has ideas on how to ensure only the first character is used as the symbol as noted in the question, that'd be awesome.
You need add in spaces after each symbol:
print ((' ' * spaces) + ((symbol + ' ') * i))
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 . . .