I want to print the following:
*
**
***
****
But both
for i in range(5):
for j in reversed(range(5)):
if j < i:
print('*', end='')
print()
and
for i in range(5):
for j in range(5):
if j < i:
print('*', end='')
print()
gives the same answer.
isn't the code with reversed supposed to give this?
*
**
***
****
You need to understand what is happening when you run those codes.
for i in range(5): # 0,1,2,3,4
for j in range(5): # 0,1,2,3,4
if j < i:
# when i = 0, no stars printed. j is never less than 0:
# when i = 1, one star printed. when j is 0, print a star.
# when i = 2, two starts printed. when j is 0,1 print stars.
print('*', end='')
print()
for i in range(5): # 0,1,2,3,4
for j in reversed(range(5)): # 4,3,2,1,0
if j < i:
# when i = 0, no stars printed. j is never less than 0:
# when i = 1, on last iteration when j = 0 one start printed.
# when i = 2, two starts printed. when j is 1,0 print stars.
print('*', end='')
print()
So basically both of the for loops are doing the same thing.
you are just printing stars. If you want to print spaces,
you have to tell the program to print spaces.
for i in range(5): # 0,1,2,3,4
for j in reversed(range(5)): # 4,3,2,1,0
if j < i:
print('*', end='')
else:
print(' ', end='') # telling to print the spaces.
print()
You can use ljust and rjust to help:
x = 5
for i in range(x):
print(('*'*i).ljust(x, ' '))
# Output:
*
**
***
****
for i in range(x):
print(('*'*i).rjust(x, ' '))
# Output:
*
**
***
****
Reversing the range doesn't work because it still prints the asterisks the same amount of times in the same way since you are not doing anything with the numbers. As the comments have said, the correct way to do this would be to print spaces before your asterisks. Here is a way to do this:
for i in range(5):
print(" "*(5-i) + "*" * i)
Related
I have the code for the 1st and the second pyramid, I just don't know how to put it together like how the question is asking. The first code below is for pyramid 1 and second is for the 2nd pyramid.
`
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
`
`
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
count1+=1
print(i+k-(2*count1), end=" ")
k += 1
count1 = count = k = 0
print()
`
You just need to run the second loop after the first loop. Also your code for the second pyramid is incorrect so I changed that.
rows = int(input("Enter number of rows: "))
k = 0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(end=" ")
while k!=(2*i-1):
print("* ", end="")
k += 1
k = 0
print()
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
for k in range(i,0,-1):
print(k, end=' ')
for k in range(2,i+1):
print(k, end=' ')
count = 0
print()
Since the algorithm for constructing both pyramids is similar, it is better to make a function
def pyramid(n_rows, s_type='*'):
max_width = n_rows * 2 - 1
for i in range(0, n_rows):
stars = i * 2 + 1
side = (max_width - stars) // 2
if s_type == '*':
print(f"{' ' * side}{'* ' * stars}")
else:
side_nums = ' '.join(f'{x+1}' for x in range(0,i+1))
print(f"{' ' * side}{side_nums[1:][::-1]}{side_nums}")
rows = int(input("Enter number of rows: "))
pyramid(rows)
pyramid(rows, s_type='0')
You only need to input the row count once. You may also find using str.rjust easier for formatting.
rows = int(input('Enter a number from 1 to 9: '))
assert rows > 0 and rows < 10
output = [None] * (rows*2)
stars = '*' * (rows * 2 - 1)
for i in range(rows):
output[i] = stars[:i*2+1].rjust(rows+i)
s = ''.join(map(str, range(1, i+2))) + ''.join(map(str, range(i, 0, -1)))
output[i+rows] = s.rjust(rows+i)
print(*output, sep='\n')
Output:
Enter a number from 1 to 9: 6
*
***
*****
*******
*********
***********
1
121
12321
1234321
123454321
12345654321
I am facing some issues with for loop in Python. The correct result is on the left, mine is on the right: the result
rows = 9
for row in range(1, rows+1):
a = 1
for j in range(rows, 0, -1):
if j > row:
print(' ', end='')
else:
print(a, end='')
a += 1
print('')
The bottom part suppose to be on the right side (mirrored from the top one), but with that code it stays right under the top part without being moved to the right:
for i in range(rows, 0, -1):
rows -= 1
for j in reversed(range(1, i + 1)):
print(j, end='')
print('')
So, any ideas what I am doing wrong and how I can move the bottom part to the right?
Don't forget to print the left-trailing spaces in your second pyramid!
adding:
print(' ' * 9, end='')
here:
rows = 9
for i in range(rows, 0, -1):
rows -= 1
print(' ' * 9, end='')
for j in reversed(range(1, i + 1)):
print(j, end='')
print('')
does it.
Given n = 5
My triangle should look like this :
*
*+*
*+++*
*+++++*
*********
What i have tried :
n = 5
for x in range(0, n):
for y in range(0, n-x-1):
print(end = "")
for z in range(0,x+1):
print("*", end = "")
print()
but the result is like this :
*
**
***
****
*****
Thanks for help and maybe some explanations
def print_triangle(n):
print(" "*(n+1)+"*")
for x in range(0, n):
for y in range(0, n-x):
print(end=" ")
print("*+", end="")
for z in range(0,x):
print("++", end = "")
print("*")
print((1+2*(n+1))*"*")
print_triangle(5)
Try this function:
def tr(n):
print(" "*(n-1)+"*")
for x in range(1, n-1):
print(" "*(n-x-1), end="")
print('*', end="")
num = ((x-1)*2) +1
print("+"*num + "*")
print(((2*n)-1) *"*")
>>tr(5)
*
*+*
*+++*
*+++++*
*********
I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *
I have been experimenting over the past couple days and have had little success.
This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing.
num=int(input("Please type in an odd integer."))
if num%2==0:
print("Your number is incorrect")
This should do it:
Python 2
N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print '*',
else:
print ' ',
print ''
Python 3
N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print('*', end = '')
else:
print(' ', end = '')
print('')
(thanks to Blckknght for Python 3 knowledge)
You're looping through all the rows in the outer loop, then all the columns or cells in the inner. The if clause checks whether you're on a diagonal. The comma after the print statement ensures you don't get a new line every print. The 3rd print gives you a new line once you're finished with that row.
If this is helpful / works for you; try making a Y using the same approach and post your code in the comments below. That way you could develop your understanding a bit more.
I'll give you a hint :
n = int(input("Please type in an odd integer."))
for i in range(n):
print('x', end='')
print()
This prints a x, n times on the same line and then go back to next line.
I'll let you figure out how you print this same line n times.
Using single for loop:
for i in range(num):
a = [' '] * num
a[i] = '*'
a[num-i-1] = '*'
print(''.join(a))
Using nested for loops:
for i in range(num):
s = ''
for j in range(num):
if j in [i, num-i-1]:
s += '*'
else:
s += ' '
print(s)
I am trying to solve a problem in HackerRank and I am having an issue with my submission. My code works in PyCharm but HackerRank is not accepting my submission.
Here is the problem I am trying to solve: https://www.hackerrank.com/challenges/staircase
Here is my code:
def staircase(num_stairs):
n = num_stairs - 1
for stairs in range(num_stairs):
print ' ' * n, '#' * stairs
n -= 1
print '#' * num_stairs
staircase(12)
Any ideas why HackerRank is not accpeting my answer?
Your output is incorrect; you print an empty line before the stairs that should not be there. Your range() loop starts at 0, so you print n spaces and zero # characters on the first line.
Start your range() at 1, and n should start at num_stairs - 2 (as Multiple arguments to print() adds a space:
from __future__ import print_function
def staircase(num_stairs):
n = num_stairs - 2
for stairs in range(1, num_stairs):
print(' ' * n, '#' * stairs)
n -= 1
print('#' * num_stairs)
You can simplify this to one loop:
def staircase(num_stairs):
for stairs in range(1, num_stairs + 1):
print(' ' * (num_stairs - stairs) + '#' * stairs)
Note that I use concatenation now to combine spaces and # characters, so that in the last iteration of the loop zero spaces are printed and num_stairs # characters.
Last but not least, you could use the str.rjust() method (short for “right-justify”) to supply the spaces:
def staircase(num_stairs):
for stairs in range(1, num_stairs + 1):
print(('#' * stairs).rjust(num_stairs))
You can use rjust to justify the string to the right:
def staircase(n):
for i in range(1, n+1):
print(("#" * i).rjust(n))
Another solution
n = int(raw_input())
s = '#'
for i in xrange( 1 , n+1):
print " "*(n-i) + s*i
first, create a list, then print with join \n'
def staircase(n):
print("\n".join([' ' * (n-x) + '#' * x for x in range(1, n+1)]))
def staircase(n):
for i in range(0, n): # n rows
print(' '*(n-i-1) + '#'*(i+1)) # first print n-i-1 spaces followed by i '#'
n = int(input())
staircase(n)
its look like secondary diagonal
def staircase(n):
for i in range(n):
for j in range (n):
if i+j == n-1:
print(" "*j+"#"*(n-j))
output-
#
##
###
####
#####
######
for i in range(n):
result = ' '*(n-i-1) +('#')*(i+1)
print(result)
I was getting an error until I replaced the comma with a plus sign:
print(' ' * (n - i - 1) + '#' * (i + 1))
Understanding the problem is 80% of the solution. The requirement states the min/max total of stairs.
"""
Prints a staircase with a total number of stairs
Note: total number of stairs must be between 1 and 100 inclusive, as per requirements
"""
def staircase(n):
if n < 1 or n > 100:
print("Error: Total number of stairs must be between 1, 100 inclusive!")
else:
for x in range(1, n+1):
print(" " * (n - x) + "#" * x )
#-----------------------
staircase(0)
Error: Total number of stairs must be between 1, 100 inclusive!
staircase(101)
Error: Total number of stairs must be between 1, 100 inclusive!
staircase(4)
#
##
###
####
def staircase(n):
space = n-1
for i in range(n):
x = i + 1
print(" " * space + "#" * x)
space -= 1
one more solution:
def staircase(n):
for i in reversed(range(n)):
print(i*' '+(n-i)*'#')
You can just change the sep argument of print from ' ' to '', and your answer will be correct
def staircase(n):
for i in range(1, n+1):
print(' ' * (n-i), '#' * (i), sep='')
The answer you submitted is not accepted because the default print settings adds an empty space in front of the printouts, and one of the question requirements is for there to have no spaces in the output.
The default sep in print is a space character i.e. ' '.
This might not be the cleanest way to write the code, but it works:
print('\n'.join(' ' * (n - i) + '#' * i for i in range(1, n + 1)))
Another Answer
H = int(input())
for i in range(1,H+1):
H = H - 1
print(' '*(H) + ('#'*(i)))
you can simply use while loop also.
import sys
n1=int(raw_input())-1
n2=1
while n1>=0:
print " "*n1,"#"*n2
n1=n1-1
n2=n2+1
def staircase(n):
for in range(i,n+1):
print str("#"*i).rjust(n)