You need to return a string that looks like a diamond shape when printed on the screen, using asterisk (*) characters. Trailing spaces should be removed, and every line must be terminated with a newline character (\n).
Return null/nil/None/... if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
Examples
A size 3 diamond:
*
***
*
def diamond(n):
if n < 1 or not n % 2:
# n is negative or even
return None
s = ''
for i in range(n):
# Build asterisks for the line
ast = '*'*(i*2 + 1) if i <= n/2 else '*'*((n-i)*2 - 1)
# Add a line
s += ' '*int((n-len(ast)) / 2) + ast + '\n'
return s
def diamond(n):
if n > 0 and n % 2 == 1:
diamond = ""
for i in range(n):
diamond += " " * abs((n/2) - i)
diamond += "*" * (n - abs((n-1) - 2 * i))
diamond += "\n"
return diamond
else:
return None
print(diamond(5))
Training on Give me a Diamond | Codewars
No comments :
Post a Comment