Recursively print diamond in python - python

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)

Related

Python Shape Printing

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)

Printing with reversed range

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)

how to turn this code into a function working code?

so i have some code that works perfectly without a function. But i want to change this inside a function, but it does not work properly.
For example, i have the end="". This doesn't work in a function, without using print.
I also have more than one print statements. When i turn these to return, they don't work. So could someone please help me change this code to work in a function?
Thanks!
My code
def underscore_hash_staircase(number):
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
print(end=" ".replace(" ", "_"))
k = k - 1
for j in range(0, i + 1):
print("#", end="")
print("")
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
print('', end=' '.replace(" ", "_"))
j -= 1
k = 1
while k <= i:
print('#', end='')
k += 1
print()
i -= 1
print(underscore_hash_staircase(8))
so the code above doesn't work properly in a function, without the print statements. Please let me know how to get this working in a function without the print statements. Using returns. It should be exact output as what is being returned in this not function-working code.
Thanks again!
Since a function can only return one value, instead of printing, you want to add to a variable to return instead of printing. Try:
def underscore_hash_staircase(number):
returnValue = "" # start as empty string
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
returnValue += "_"
k = k - 1
for j in range(0, i + 1):
returnValue += "#"
returnValue += "\n" # adding a new line
else:
number = int(str(number).replace("-", ""))
i = number
while i >= 1:
j = number
while j > i:
returnValue += "_"
j -= 1
k = 1
while k <= i:
returnValue += "#"
k += 1
returnValue += "\n"
i -= 1
print(underscore_hash_staircase(8))
Edit: missed a print when replacing
The function should append to a string instead of printing, and then return the string. Append \n to add a newline.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(0, number):
for j in range(number-1, k):
result += "_"
k = k - 1
for j in range(0, i + 1):
result += "#"
result += "\n"
else:
number = -number
i = number
while i >= 1:
j = number
while j > i:
result += "_"
j -= 1
k = 1
while k <= i:
result += "#"
k += 1
result += "\n"
i -= 1
return result
print(underscore_hash_staircase(8))
You also don't need all those inner loops. You can repeat a string by multiplying it.
def underscore_hash_staircase(number):
result = ""
if number > 0:
k = 2 * number - 2
for i in range(1, number + 1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
else:
number = -number
for i in range(number, 0, -1):
result += "_" * (number - i)
result += "#" * i
result += "\n"
return result
print(underscore_hash_staircase(8))
print(underscore_hash_staircase(-8))

Can't get output to rotate 180 degrees

I need to make a nested triangle of hash symbols. But I can't get it to rotate 180 degrees like I need it to, I am also not getting the 12 rows like I need to.
This is my code.
n = int(input("Enter a number: "))
for i in range (0, n):
for j in range(0, i + 1):
print("#", end='')
print("")
for i in range (n, 0, -1):
for j in range(0, i -1):
print("#", end='')
print("")
The Input value is 6.
Enter a number:6
#
##
###
####
#####
######
######
#####
####
###
##
#
But I keep getting this:
Enter a number: 6
#
##
###
####
#####
######
#####
####
###
##
#
How do I fix this?
You can use the str.rjust method to align a string to the right:
n = int(input("Enter a number: "))
for i in range(2 * n):
print(('#' * (n - int(abs(n - i - 0.5)))).rjust(n))
Demo: https://ideone.com/27AM7a
A bit late
def absp1(x):
if (x < 0):
return -x - 1
return x
n = int(input("Enter a number: "))
for i in range(-n, n):
for j in range(absp1(i)):
print(' ', end='')
for k in range(n-absp1(i)):
print('#',end='')
print()
You can use this (manually calculating number of spaces and hashtags):
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(" "*(n - i) + "#"*i)
for i in range (n, 0, -1):
print(" "*(n - i) + "#"*i)
Or use rjust:
n = int(input("Enter a number: "))
for i in range (1, n + 1):
print(("#"*i).rjust(n))
for i in range (n, 0, -1):
print(("#"*i).rjust(n))
Also this works fine
num = 6
sing = "#"
for i in range(1, num * 2):
if i > num:
spaces = " " * (i - num)
signs = sign * (2 * num - i)
line = "{0}{1}".format(spaces, signs)
elif i == num:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}\n{0}{1}".format(spaces, signs)
else:
spaces = " " * (num - i)
signs = sign * i
line = "{0}{1}".format(spaces, signs)
print(line)

HackerRank Staircase Python

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)

Categories