Skip to content Skip to sidebar Skip to footer

Rhombus Shape Based On User Input

I am trying to create a rhombus made out of letters that a user selects, using Python 3. So if a user selects 'B' then the rhombus is A B B A If the user selects 'D' the rh

Solution 1:

golfing time \o/

edit: there's of course an SE for code golf and i'll do as in rome

Python 3, 106 bytes

n=26for x inrange(-n, n):
    x = abs(x)
    print('  '*x+'   '.join([chr(64+n-x) for _ inrange(n-x)]))

Try it online!

explanation

for x in range(-n, n): generate the rows

' '*x: generate the space before each first letter in the row

chr(64+n-x): display the letter, with chr(65) = "A"

' '.join: join all letters with three spaces between each of them

for _ in range(n-x): will generate the right number of letters. the value itself is useless.

output for n=4:

      A   
    B   B   
  C   C   C   
D   D   D   D   
  C   C   C   
    B   B   
      A   

Solution 2:

domochevski's answer is great but we don't actually need those imports.

defrhombus(char):
    A = 64
    Z = A + 26try:
        val = ord(char)
        if val < A or val > Z:
            returnNoneexcept:
        returnNone
    L = [ ''.join(([chr(x)]*(x-A))) for x inrange(A,val+1) ]
    L = [' '.join(list(x)) for x in L]
    max_len = max(len(x) for x in L)
    L = [x.center(max_len) for x in L]
    L += L[-2::-1]
    return'\n'.join(L)

print(rhombus('Z'))

Solution 3:

Well that was an interesting question. Here is some quick and dirty way to do it:

from string import ascii_uppercase

defrhombus(c):  # Where c is the chosen character# Get the position (1-based)
    n = ascii_uppercase.find(c.upper()) + 1if0 < n <= 26:
        # Get the strings for the top of the rhombus without spaces
        l = [ascii_uppercase[i] * ((i)+1) for i inrange(n)]
        # Add in the spaces
        l = [' '.join(list(e)) for e in l]
        # Align everything
        max_len = max(len(e) for e in l)
        l = [e.center(max_len) for e in l]
        # Get the bottom from the top
        l += l[-2::-1]
        # Print the rhombusfor e in l:
            print(e)

As I mentioned this is not beautiful code but it should work.

Post a Comment for "Rhombus Shape Based On User Input"