I have to print a hollow inverted pyramid:
******
* *
* *
* *
**
*
Following is my code:
n = int(input())
for i in range(n,0,-1):
if i == n:
print(n*'*', end = '')
if i > 1 and i <n:
print('*'+(i-2)*' '+'*')
else:
print('*')
print()
For input as 6 I am not sure why my code is printing 7 stars.
If anyone could help explain what I am doing wrong or missing would be really great!
There are two problems here:
There is no need for the , end=''. You still want a newline to print after this line of stars.
You used if not elif for the second condition, so the third block of code in the else will still run even if the first condition is true.
Here is the corrected code:
n = int(input())
for i in range(n, 0, -1):
if i == n:
print(n * "*")
elif 1 < i < n:
print("*" + (i - 2) * ' ' + '*')
else:
print('*')
If the first iteration of the loop, there are two print calls executing: the first one and the last, so that makes a total of 7 stars in that first line of output.
As the first and last case are different from the other cases, it is easier to just deal with those outside of the loop:
n = int(input())
print(n*'*')
for i in range(n - 3, -1, -1):
print('*' + i*' ' + '*')
if n > 1:
print('*')
There is still one if here to ensure it still works correctly for n equal to 1 or even 0.
To do it without that if, you could do this:
n = int(input())
print(n*'*')
s = '*' + n*' '
for i in range(n - 2, -1, -1):
print(s[:i] + '*')
another type of inverted hollow matrix:
54321
4 1
3 1
2 1
1
Answers:
Hollow Right-angled triangle!!!
n=int(input())
for i in range(n,0,-1):
for k in range(n,0,-1):
if i==n or i==k or k==n-(n-1):
print(k,end=" ")
else:
print(end=" ")
print()
Related
Trying to make a program that asks the user for a height and a character, and then outputs a hollow triangle to that height using that character. Was trying to firstly make a solid triangle, then solve it from there, but so far have only managed to make a half triangle.
Also, using only for loops and no '*' operator
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < rows:
print(C, end="")
count += 1
print()
rows += 1
this results in this:
*
**
***
****
*****
my goal is this:
*
* *
* *
* *
*********
any help would be appreciated!
Slightly changed your script:
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 1
count = 0
while rows <= H:
spaces = 0
while spaces <= (H - rows):
print(" ", end="")
spaces += 1
count = 0
while count < 2*rows-1:
count += 1
if count == 1 or count == 2*rows-1 or rows == H:
print(C, end="")
else:
print(" ", end="")
print()
rows += 1
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
for i in range(H):
for j in range(H - i):
print(' ', end='')
for j in range(2 * i + 1):
if j == 0 or j == 2 * i or i == H - 1:
print(C, end='')
else:
print(' ', end='')
print()
There's already an answer, but considering that I had fun doing this little program, and that our solution are not the same :
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if C == "":
C = "*"
rows = 0
while rows <= H:
cols = 0
if rows == H:
while cols <= H*2:
print(C, end="")
cols += 1
else:
while cols <= H*2:
if rows + cols == H or cols - rows == H:
print(C, end="")
else:
print(" ", end="")
cols += 1
print()
rows += 1
Note that I did this with for loops, and just swapped to while loops to paste it here.
The way to get a hollow triangle is to print spaces in a loop.
If you observe the output you need, you'll see that except for the top and bottom lines, every line has only 2 asterisks (*). That means you need a logic that handles spaces.
There are several ways to write the logic, such as treating each vertical halves as blocks of fixed length and just varying the position of the star or actually counting the spaces for each line. You can explore the different ways to achieve what you need at your convenience. I'll present one soln.
H = int(input("Enter height of triangle: "))
C = str(input("Character: "))
if len(C) != 1:
C = "*"
rows = 1
count = 0
while rows < H:
str = ""
for i in range(H - rows):
str += " "
str += C
if rows > 1:
for i in range(2 * rows - 3):
str += " "
str += C
print(str)
rows += 1
str = ""
for i in range(2 * H - 1):
str += C
print(str)
I have made a change about checking the character. You should not allow characters of more than length 1. Otherwise, the spacing will get messed up
These exercises are meant for you to understand the logic and get comfortable with manipulating code, so do try different variations
This is probably not the most optimized solution but, remember that printing is in general slow as it has to interact with a peripheral (monitor), so try to print in bulk whenever possible. This improves the speed
I am new on Python and I am following a book that purposes the following excercise:
Write a program to generate the following pattern in Python:
*
**
***
****
The suggested code is:
n = input('Enter the number of rows: ')
m = int(n)
*k = 1
for i in range(m):
for j in range(i, i + 2):
print('*', end = " ")
print()
and enter n=5.This lead me to ask to questions. The first one is the *k=1, I am asumming the '' is a typo on the book since my program does not run with it. However i am not seeing that k is being used within the loop. My second question is that I do not understand why my outcome is different than the one I get (once removed the ''). This is what I get when n=5:
**
**
**
**
**
This works for your problem. In python, you can multiply strings. It will be useful for the problem. *k is a typo.
n = input(' num rows: ')
n = int(n)
for i in range(1, n + 1):
print ('*' * i)
You can try this solution. I am pretty sure the *k = 1 is a typo.
n = int(input('Enter the number of rows: '))
k = 1
for i in range(n):
print(k * '* ', end = "\n")
k += 1
Another approach if you don't want to use multiplication approach:
n = input('Enter the number of rows: ')
m = int(n)
for i in range(m):
for j in range(1, i + 2):
print('*', end = " ")
print()
def printStarsInTriangeForm(count):
for i in (range(1, count + 1)):
print("*" * i)
This is one way. :)
yea *k = 1 cant be right, you can delete it.
Your mistake or the mistake in the book is the line:
for j in range(i, i + 2):
if you type i * 2 it works:
for j in range(i, i * 2):
and if you want no spaces between the starts you need to change the print in the loop to:
print("*",end="")
i just removed the space in the "end".
and a better way you can do this is
m = int(input('Enter the number of rows: '))
for i in range(m + 1):
print(i * "*")
Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?
1
232
34543
4567654
567898765
678901109876
This is the code I made:
c = -1
for y in range(1, 7):
print()
print((6-y) * " ", end="")
c += 1
for x in range(1, y+1):
print(y%10, end="")
y += 1
while y - c > 2:
print(y-2, end="")
y -= 1
First of all, I'm guessing that you didn't really want to print that y value of 10; that you really wanted the base-10 reduction to 0. Note that you have an extra character in the pyramid base.
Do not change the value of a loop parameter while you're inside the loop. Specifically, don't change y within the for y loop.
Get rid of c; you can derive it from the other values.
For flexibility, make your upper limit a parameter: you have two constants (6 and 7) that depend on one concept (row limit).
Here's my version:
row_limit = 7
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " ", end="")
for x in range(y, 2*y):
print(x%10, end="")
for x in range(2*(y-1), y-1, -1):
print(x%10, end="")
print()
Output:
1
232
34543
4567654
567898765
67890109876
If you really want to push things, you can shorten the loops with string concatenation and comprehension, but it's likely harder to read for you.
for y in range(1, row_limit):
print()
print((row_limit-y-1) * " " + ''.join([str(x%10) for x in range(y, 2*y)]) + \
''.join([str(x%10) for x in range(2*(y-1), y-1, -1)]), end="")
print()
Each of the loops is turned into a list comprehension, such as:
[str(x%10) for x in range(y, 2*y)]
Then, this list of characters is joined with no interstitial character; this forms half of the row. The second half of the row is the other loop (counting down). In front of all this, I concatenate the proper number of spaces.
Frankly, I prefer my first form.
Here's my implementation.
Python 2:
def print_triangle(n):
for row_num in xrange(1, n + 1):
numbers = [str(num % 10) for num in xrange(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print '{}{}'.format(' ' * (n - row_num), num_string)
Python 3:
def print_triangle(n):
for row_num in range(1, n + 1):
numbers = [str(num % 10) for num in range(row_num, 2 * row_num)]
num_string = ''.join(numbers + list(reversed(numbers))[1:])
print('{}{}'.format(' ' * (n - row_num), num_string))
Input:
print_triangle(5)
print_triangle(6)
print_triangle(7)
Output:
1
232
34543
4567654
567898765
1
232
34543
4567654
567898765
67890109876
1
232
34543
4567654
567898765
67890109876
7890123210987
n = int(input())
i = 1
while i <= n:
j = 1
spaces = 1
p = i
while spaces <= n - i:
print (" ", end ="")
spaces += 1
while j <= i:
print(p, end = "")
j += 1
p += 1
p -= 2
while p >= i:
print(p, end = "")
p -= 1
print()
i += 1
I am trying to write a program that looks something like this if, say, the input number was 6, or something like that the output should look like this:
*
**
***
****
*****
******
*****
****
***
**
*
but when I do it like I was told, this way specifically because this is what a classmate told me to do. :
n = int(input("Enter a value for n: "))
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
for i in range(1, n):
for j in range(n):
if n - j < i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
I get:
*
**
***
****
*****
******
*****
****
***
**
*
What am I doing wrong? Please tell me how to get it to correctly line up, I'd really appreciate it if someone could help me with this so I can learn to do this on my own, please assist me...
If your assignment requires you to write the code exactly as you posted, Austin Kootz answer is the way to go.
However, a more simplifed way of doing this is using ljust
n = 6
for x in range(n - 1, 0, -1):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
for x in range(n):
print ''.ljust(x, ' ') + '*'.ljust(n - x, '*')
Your loops are a bit overcomplicated, so I've simplified somewhat:
n = int(input("Enter a value for n: "))
for x in range(n):
out = ''
for y in range(n-x):
out = out +' '
for y in range(x):
out = out +'*'
print(out)
for x in range(n):
out = ''
for y in range(x):
out = out +' '
for y in range(n-x):
out = out +'*'
print(out)
Enjoy!
What you want in the second set of loops is to take the row number (counting from 1) and print that many spaces (" "), and then print asterisks ("*") for the rest of the row. So if i is the row number and j the column number (and indexing starts from 0), you should print " " while j < i + 1 and "*" otherwise. This gives:
# The top part of the pyramid
for i in range(1, n + 1):
for j in range(n):
if n - j > i:
print(" ", end = " ")
else:
print("*", end = " ")
print("")
# The bottom half of the pyramid
for i in range(n):
for j in range(n):
# Print spaces in the beginning of the row
# (while the column number is less than the row number)
if j < i + 1:
print(" ", end = " ")
# Print asterisks for the rest of the row
else:
print("*", end = " ")
print("")
This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 3 years ago.
I'm not able to remove the spacing in a for-loop as numbers are not coming in the same for making the pattern.
My code:
for i in range(1,5):
for j in range(1,i):
print(j)
Produces the following result:
1
1
2
1
2
3
But my desired output is:
1
12
123
1234
Try this:
print(j, end='')
end by default is \n (see print()). Also, be sure to print a newline at the end of each outer loop iteration:
for i in range(1,6): # notice that I changed this to 6
for j in range(1,i):
print(j, end='') # added end=''
print() # printing newline here
1
12
123
1234
EDIT I just noticed you were using Python 2.7. Since that's the case, you can use print j, instead of print(j, end='') and print instead of print(). Note that print j, will leave spaces between the js. If you don't want this, you can import sys and use sys.stdout.write(j) instead (see sys).
Furthermore, if you want to use the Python 3 print function as shown above, you can always
from __future__ import print_function
One line solution, if you're interested:
print('\n'.join([''.join(['{}'.format(i) for i in range(1,j)]) for j in range(2,6)]))
1
12
123
1234
for r in range(1,5):
for c in range (1,r+1):
print c,
print
here, the print without argument causes printing in the next line
In order to get all of the numbers on one line, you'll have to use one print statement per line you want. One way you could do this is:
for i in range(1, 5):
print(''.join([str(n) for i in range(1, i)]))
Keeping the nested for loops you could do:
for i in range(1, 5):
temp = ''
for j in range(1, i):
temp += str(j)
print(temp)
Try:
def RTN():
x = 1
num = int(input('Type any integer besides 0: '))
if num == 0:
return 'Try again!'
while x < num + 2:
print('')
for y in range(1, x):
print(str(y) + ' ', end = '')
x += 1
def pentagon(num):
j = num
for i in range(0, num + 1):
print('{}{}'.format(' ' * j, ' *' * i))
j -= 1
pentagon(2)
output
*
* *
num = int(input())
for i in range (1,num+1):
for j in range(i):
print(j+1,end = '')
print("")
I thought the idea of #Shiva was really nice and made a slightly more general pyramid function, maybe someone can use/enjoy it it:
def pyramid(n_rows, s, upside_down=False, offset=0):
whites = ' ' * len(s)
offset = ' ' * offset
indices = np.arange(n_rows)
if upside_down:
indices = zip(indices[::-1]+1, indices)
else:
indices = zip(indices+1, indices[::-1])
for i, j in indices:
print(f"{offset + whites * j}{(s + whites) * i}")
pyramid(4, 'SO')
# SO
# SO SO
# SO SO SO
# SO SO SO SO
pyramid(4, '*', upside_down=True, offset=3)
# * * * *
# * * *
# * *
# *
x=input('enter some numerical value')
s=''
for i in range(0,x):
for j in range(0,i+1):
s=s+str(j+1)
print s
s=''