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)
Related
Hi everyone, I have an assignment to acquire this shape in Python. I am a beginner, I tried to use nested loops to create this shape but I couldn't. Could someone help? Thanks a lot. (I couldn't copy the output exactly I'm sorry)
I used nested for loops, if and else statements in various ways (for example, I've tried to write stars at the end of a row) but I couldn't get the shape. I am editing the post in order to show you my effort. I am really sorry that my output is really different from the wanted one.
len = int(input("enter an odd number: "))
if len % 2 == 0:
print("enter an odd number")
else:
row = int((len+1) / 2)
for i in range (0,len):
print("#",end="")
print()
for i in range(0,row):
print("*")
print("*", end=" ")
for j in range(1,len):
print("*",end="")
for i in range(0,len):
print("#",end="")
for n = 5
#####
* *
* *
* *
* *
* *
* *
#####
This could be one way of solving it:
if we define n as the sample input, the shape can be divided into 3 steps of length (n//2) each.
Initialization: print('#'*n)
Step 1: for i in range(n//2): print('*'+' '*(n-2)+'*')
Step 2a: create a print_list: print_list = [k*' ' + '*'+ (n-2-2*k)*' ' + '*' + k*' ' for k in range(n//2)]
Step 2b: Now print each line in print_list
Step 3: Then print each line in print_list[::-1]
End: print('#'*n)
Implemented Code:
n = int(input("enter an odd number: "))
if n % 2 == 0:
print("enter an odd number")
else:
print("#"*n)
for i in range(n//2):
print('*'+' '*(n-2)+'*')
print_list = [k * ' ' + '*' + (n - 2 - 2*k) * ' ' + '*' + k * ' 'for k in range(n//2)]
for p in print_list: print(p)
for p in print_list[::-1]: print(p)
print("#"*n)
I am writing a program that calculates the factorial of a number, I am able to display the correct answer, however along with the answer I need the actual calculation to display, I am having trouble with that. So for example, when the user enters 4, I need it to display as:
I have been trying to figure out the right code, but do not know what to do.
Here is the code I have so far
number = int(input("Enter a number to take the factorial of: "))
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
print (factorial)
Right now, it displays the correct answer, however I need for it to include the equation as well as follows: 4! = 1 x 2 x 3 x 4 = 24
The simplest approach is to construct the string as you are iterating:
equation = str(number) + "! = "
factorial = 1
for i in range(1, number + 1):
factorial = factorial * i
equation += str(i) + "x"
equation = equation[:-1] + " = " + str(factorial)
print(equation)
Note that this method appends an unwanted 'x' after the last factor. This is removed by equation[:-1].
Alternatively, you could append this one-line solution to the end of your code. It uses the join method of the string class to concatenate an array of strings:
print(str(number) + "! = " + "x".join(str(n) for n in range(1, number + 1)) + " = " + str(factorial))
As you loop through the numbers to be multiplied, you can append each number's character to a string containing the equation, e.g ans, and print it at last. At the end of the code, I omitted the last letter because I didn't want an extra 'x' to be displayed.
def fact(number):
num_string=str(number)
factorial = 1
ans=num_string+"!="
for i in range(1, number + 1):
factorial = factorial * i
ans+=str(i)+"x"
ans=ans[:-1]
print(ans)
return factorial
fact(4)
You can append each value to the list and then print the equation using the f-string:
num = 5
l = []
f = 1
for i in range(1, num + 1):
f *= i
l.append(i)
print(f"{num}! = {' x '.join(map(str, l))} = {f}")
# 5! = 1 x 2 x 3 x 4 x 5 = 120
The pattern is given below. The number of rows is to be specified by the user. In this image it is 6. I know how to print the upper half but I am finding difficulty in the lower half. Please help.
I tried this code:
def asterisk_triangle(n):
x = 1
while (x <= n):
print("*" * x)
x = x + 1
return
If you have top half done, the bottom is similar, but reversed (rather than printing a number of stars equal to the row number, print a number of starts equal to the total number of rows minus the current row number). For example:
num = raw_input("Please enter number: ")
for i in range(num):
print "*" * i
then the opposite would be:
for j in range(num):
print "*" * (num-i)
def pattern(lines):
for i in range(0, lines / 2):
print "*" * i
for i in range(lines / 2, 0, -1):
print "*" * i
I am trying to create a program that allows me to make a "pyramid" or "triangle" using asterisks, in the Python program. I've already started the code, but can't seem to figure it out.
Here's the code I've managed to figure out:
def triangle():
totalRows = int(eval(input("How big? ")))
for currentRows in range(1,totalRows+1):
for currentCol in range (1, currentRows+1):
print("*", end = " ")
triangle()
The end result is supposed to mirror this!
How big? 1
*
------------------------------------------------------
How big? 2
*
* *
------------------------------------------------------
How big? 3
*
* *
* * *
------------------------------------------------------
Slight modification to RParadox's solution to match requirement:
for i in range(totalRows + 1):
numWhite = totalRows - i
print ' ' * numWhite + '* ' * i
n = 10
for i in range(n-1):
numwhite = n-i
print ' '*numwhite + '*'*i + '*'*i
**
****
******
********
**********
************
**************
****************
def build_pyr(depth):
rows = [ (depth-i)*' ' + i*2*'*' + '*' for i in range(depth-1) ]
for i in rows:
print i
This works, however, it adds 2n + 1 asterisks at each depth. Just remove the + 1 asterisks from the list comprehension and add an initial asterisk to the row list before hand.
kiko="*"
empty=" "
def star(n):
for i in range(n):
print((n-i-1)*empty+(i+i+1)*kiko)
star(5)
def xmastree(maxwidth):
for i in xrange(1,maxwidth,2):
print '{0}'.format('*'*i).center(maxwidth)
or:
def xmastree2(maxrows):
for i in xrange(1,maxrows*2,2):
print '{0}'.format('*'*i).center(maxrows*2)
hmm, still no response, maybe not generic enough ? ok try this ;-) :
def triangle(pattern, n):
maxwidth = n*len(pattern)*2
for i in xrange(1,n*2+1,2):
print '{0}'.format(pattern*i).center(maxwidth)
>>> triangle(' ^', 5)
^
^ ^ ^
^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^ ^
^ ^ ^ ^ ^ ^ ^ ^ ^
Woah, guys, you are going at it from a really complicated point of view! why don'y you just use this program? :
asterisknum = int(raw_input('How many asterisks? Input here: '))
base = 0
if asterisknum % 2 == 0:
print ('Added 1 to even number')
asterisknum = asterisknum + 1
while asterisknum != -1 :
print (' ' * base + '*' * asterisknum)
base = base + 1
asterisknum = asterisknum - 2
raw_input('Press <Enter> to exit')
I just made this program to work once, but I used the extremely simple parts of python that everybody should know. It could be tweaked to work again in the same program, or whatever...
def triangle(height):
maxstars = 1+ 2*(height -1)
spaces = int(maxstars/2)
for i in range(0,height):
print(" " * spaces +"*" * (1+ 2*i))
spaces = spaces -1
number = int(input("Please enter height of triangle: "))
triangle(number)
Imagine you have "blocks" of stars and space. Now add them on a canvas.
This is Python.
It glues objects together in this particular case
This code prints a diamond, the first loop is the upper half, the second loop is the lower half.
Note that i had to make new variables(objects) for the second loop.
Hope this helps guys :)
star = "*"
space = "." # dots are for presentation purposes
rows = 10
star_counter = 1
space_counter = rows
for i in range(rows):
print((space * (space_counter - 1 )) + (star * star_counter) +
(star * (star_counter - 1)) + (space * (space_counter - 1)) )
star_counter += 1
space_counter -= 1
star_counter_new = (rows - 1) # one row less for the lower triangle
# the upper triangle takes the base row
# that's why rows - 1
space_counter_new = 1
for j in range(rows - 1): # same goes here
print((space * (space_counter_new)) + (star * (star_counter_new)) +
(star * (star_counter_new - 1)) + (space * (space_counter_new )))
space_counter_new += 1
star_counter_new -= 1
it can be done in just few steps:
def main():
rows = input(" enter the number of rows : ")
for i in range (rows):
print ' '*(rows-i-1) + '*'*(2*i+1)
main()
def pypart2(n):
k = 2*n-2
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k=k-1
for j in range(0, i+1):
print("* ", end="")
print("\r")
n = 5
pypart2(n)
Can anyone help me out here, I am stuck on the base cases for turning this code into a recursive function... Can't use loops in the recursive function obviously.
def diamond(a):
assert a > 0, "width must be greater than zero"
for i in range(0, a, 2):
for c in range(0, a - i, 2):
print(" ", end='')
if a % 2 == 0:
i += 1
for m in range(0, i - 1):
print("*", end='')
print()
for i in range (0, a, 2):
for c in range(0, i, 2):
print(" ", end='')
for m in range(0, a - i):
print("*", end='')
print()
Because this must be homework, I won't give you the code, but explain how to do it in words:
Instead of looping, you make a function that calls itself, and passes the variables you need as parameters. Then you have a test with an "if" in the function that when true, stops the looping and instead returns. That was you will then "fall" out of the loop.
So in this case you would pass in a and i as parameters, increase i with one in the function, and when i is greater than a, just return.
Try this
def triangles(n):
if not n & 1:
raise ValueError('n must be odd')
print_diamond(0, n, n >> 1)
def print_diamond(start, stop, midpoint):
if start < stop:
if start <= midpoint:
print(' ' * (midpoint - start) + '* ' * ((start << 1) + 1))
else:
print(' ' * (start - midpoint) + '* ' * ((stop - start << 1) - 1))
print_diamond(start + 1, stop, midpoint)
triangles(5)