Creating pyramid using symbols in Python - python

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

Related

How to draw right side up triangle recursively with ONE argument

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.

Printing Pattern Horizontally in Python

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.

Printing two different squares (made of asterisks) adjacent to each other?

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 do I fix my definition to properly close with a return statement rather than ending with print?

Doing some exercises to learn Python and facing issues while closing the code properly. The idea is to get something that does this:
d4 = """ /\\
//\\\\
\\\\//
\\/ """
print(d4)
/\
//\\
\\//
\/
Below is the code I have written:
def diamond(height):
"""Return a string resembling a diamond of specified height (measured in lines).
height must be an even integer.
"""
shape = ''
lchar_top, rchar_top = '/', '\\'
lchar_bottom, rchar_bottom = '\\' , '/'
for i in range((height//2)):
shape += (lchar_top * (i + 1)).rjust(height) + (rchar_top * (i + 1)).ljust(height) + '\n'
for j in range((height//2)):
shape += (lchar_bottom * (height//2 - j)).rjust(height) + (rchar_bottom * (height//2 - j)).ljust(height) + '\n'
print(shape)
Which popped the below output
diamond(8)
/\
//\\
///\\\
////\\\\
\\\\////
\\\///
\\//
\/
However, when I attempt to use a return statement as below:
def diamond(height):
"""Return a string resembling a diamond of specified height (measured in lines).
height must be an even integer.
"""
shape = ''
lchar_top, rchar_top = '/', '\\'
lchar_bottom, rchar_bottom = '\\' , '/'
for i in range((height//2)):
shape += (lchar_top * (i + 1)).rjust(height) + (rchar_top * (i + 1)).ljust(height) + '\n'
for j in range((height//2)):
shape += (lchar_bottom * (height//2 - j)).rjust(height) + (rchar_bottom * (height//2 - j)).ljust(height) + '\n'
return shape
I get this output:
diamond(8)
Out[215]: ' /\\ \n //\\\\ \n ///\\\\\\ \n ////\\\\\\\\ \n \\\\\\\\//// \n \\\\\\/// \n \\\\// \n \\/ \n'
Here is the solution offered via Kaggle(sorry about the formatting issue):
def diamond(height):
s = ''
# The characters currently being used to build the left and right half of
# the diamond, respectively. (We need to escape the backslash with another
# backslash so Python knows we mean a literal "\" character.)
l, r = '/', '\\'
# The "radius" of the diamond (used in lots of calculations)
rad = height // 2
for row in range(height):
# The first time we pass the halfway mark, swap the left and right characters
if row == rad:
l, r = r, l
if row < rad:
# For the first row, use one left character and one right. For
# the second row, use two of each, and so on...
nchars = row+1
else:
# Until we go past the midpoint. Then we start counting back down to 1.
nchars = height - row
left = (l * nchars).rjust(rad)
right = (r * nchars).ljust(rad)
s += left + right + '\n'
# Trim the last newline - we want every line to end with a newline character
# *except* the last
return s[:-1]
What do I need to change so that my attempted return statement also gives me the desired shape rather than a literal string of the appended characters and new line statements from iterating?
You're not wrong; your function returns what it should. It's just that the shell doesn't display it properly: if it sees a 'naked' value, it prints its represenation (the same you would get using the repr() function). The print the formatted value, use print(). Compare (I'm using IDLE while you seem to be using IPython, but the principle is the same):
>>> "line 1\nline 2\n"
'line 1\nline 2\n'
>>> print("line 1\nline 2\n")
line 1
line 2
So what you have to do: instead of just calling your function, you need to call print() with the result of the function:
>>> print(diamond(8))
/\
//\\
///\\\
////\\\\
\\\\////
\\\///
\\//
\/

(python) How to convert number into symbol ' * '

I just thinking how to convert the numbers into the ' * ' (eg. if I enter 4 then **** and the result will be like this: ****, ***, **, *)
I know that the code should be like this:
number = int(input())
while number >= 0:
print (number)
number = number - 1
but how to make it become ' * '?
Thanks.
Try this:
print(number * '*')
It will print * number times. Example:
>>> print(4 * '*')
'****'
Another approach:
''.join('*' for _ in range(4))
However, as #GingerPlusPlus points out, this approach is slower than the other one overloading the * operator.
If I understand you correctly, you want to print the astericks * symbol X amount times based on the number entered and then you want to count down to 1? That explanation might be rough, so here's an example of what I believe you are asking for:
If the user enters 3, you want to print:
***
**
*
If that is correct then here's a possible implementation (coded for Python 3.x):
number = int(input())
while (number > 0):
print( '*' * number)
number -= 1
# End While

Categories

Resources