Reputation: 91
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 rhombus would be:
A
B B
C C C
D D D D
C C C
B B
A
Can anyone help me get started on this? As of now, I am thinking if a user selects D then that corresponds to 4 and you would use the equation 2k-1 to determine the size of the "square." I would also create a linked list containing all the letters so letter = ['A', 'B', 'C', 'D'.... 'Z'] (or would a dictionary be better?) so:
def rhombus(n):
squareSize = 2n-1
for i in range(1,squareSize):
for l in letter:
print l + "/n"
Upvotes: 1
Views: 336
Reputation: 1281
golfing time \o/
edit: there's of course an SE for code golf and i'll do as in rome
n=26
for x in range(-n, n):
x = abs(x)
print(' '*x+' '.join([chr(64+n-x) for _ in range(n-x)]))
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
Upvotes: 2
Reputation: 922
domochevski's answer is great but we don't actually need those imports.
def rhombus(char):
A = 64
Z = A + 26
try:
val = ord(char)
if val < A or val > Z:
return None
except:
return None
L = [ ''.join(([chr(x)]*(x-A))) for x in range(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'))
Upvotes: 1
Reputation: 553
Well that was an interesting question. Here is some quick and dirty way to do it:
from string import ascii_uppercase
def rhombus(c): # Where c is the chosen character
# Get the position (1-based)
n = ascii_uppercase.find(c.upper()) + 1
if 0 < n <= 26:
# Get the strings for the top of the rhombus without spaces
l = [ascii_uppercase[i] * ((i)+1) for i in range(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 rhombus
for e in l:
print(e)
As I mentioned this is not beautiful code but it should work.
Upvotes: 0