나는 이렇게 학습한다/Algorithm & SQL

Give me a Diamond

daco2020 2022. 8. 14. 20:23
반응형

Jamie is a programmer, and James' girlfriend. She likes diamonds, and wants a diamond string from James. Since James doesn't know how to make this happen, he needs your help.

Task

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:

 *
***
 *

...which would appear as a string of " *\n***\n *\n"

A size 5 diamond:

  *
 ***
*****
 ***
  *

...that is:

"  *\n ***\n*****\n ***\n  *\n"

 

 

Solution:

def diamond(n):
    exception = (n % 2 == 0 or n <= 0)
    return {True : None}.get(exception, make_diamond(n))

def make_diamond(n):
    asc = [(int((n-i)/2)*' ')+(i*'*'+'\n') for i in range(1, n+1) if i%2 == 1]
    desc = asc[::-1][1:]
    return ''.join(asc+desc)

 

 

Other Solution:

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

 

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Row Weights  (0) 2022.08.16
Playing with digits  (0) 2022.08.15
Consecutive strings  (0) 2022.08.13
Maximum subarray sum  (0) 2022.08.12
List Filtering  (0) 2022.08.11