Reputation: 23
I've been trying to make a diamond out of forward and backwards slashes, so far I have this piece of code:
def upper_diamond(level,length):
if level <=length:
print(" " * (length - level), end="")
print("/", end="")
print(" " * 2 * (level-1), end=" ")
print("\\")
upper_diamond(level + 1,length)
def lower_diamond(level,length):
def diamond(length):
upper_diamond(1,length)
diamond(4)
and when I print it comes out as such:
/ \
/ \
/ \
/ \
I want to make a complete diamond and making the bottom part is stumping me, how do I make the bottom half print with the rest of the diamond?
Upvotes: 2
Views: 1115
Reputation: 519
You can also simplify it into a single function where you can specify the size and the characters used for each side of the diamond. Rather than printing each line, it might be cleaner to build the entire string with the function then print the returned string.
def build_diamond(half_width=4, char_tl='/', char_tr='\\', char_bl='\\', char_br='/'):
top_rows = []
bot_rows = []
for i in range(half_width):
offset = (half_width - i - 1)
top_rows.append(offset * ' ' + (2 * i * ' ').join((char_tl, char_tr)))
bot_rows.append(i * ' ' + (2 * offset * ' ').join((char_bl, char_br)))
return '\n'.join(top_rows + bot_rows)
print(build_diamond())
Result:
/\
/ \
/ \
/ \
\ /
\ /
\ /
\/
Upvotes: 0
Reputation: 16184
Basing off your code, you can replicate the same behavior adjusting the offsets (changed end
after spacing section to empty string to avoid opened edges):
def upper_diamond (level, length):
if level <= length:
print(' ' * (length - level), end='')
print('/', end='')
print(' ' * 2 * (level - 1), end='')
print('\\')
upper_diamond(level + 1, length)
def lower_diamond (level, length):
if level <= length:
print(' ' * (level - 1), end='')
print('\\', end='')
print(' ' * 2 * (length - level), end='')
print('/')
lower_diamond(level + 1, length)
def diamond(length):
upper_diamond(1, length)
lower_diamond(1, length)
diamond(4)
Outputs:
/\
/ \
/ \
/ \
\ /
\ /
\ /
\/
Upvotes: 1