I'm having trouble making this diamond. Whenever I make chars equal to an even length, it turns out fine. However, when it is odd, only the bottom portion of the diamond gets messed up. I've been working hours on this and am almost done. Thanks in advance for the help.
chars = 'ABCDEF'
length = len(chars)
string = ''
dots = (length*2 - 1)*2 - 1
for i in range(length):
string1 = ''
string += chars[i]
length1 = len(string)
for j in range(0, length1):
if j % 2 != 0:
string1 += chars[length -1 - j].center(3, '.')
else:
string1 += chars[length - 1 - j]
for k in range(i - 1, -1, -1):
if k % 2 != 0:
string1 += chars[length - 1 - k].center(3, '.')
else:
string1 += chars[length - 1 - k]
string1 = string1.center(dots, '.')
print(string1)
string=''
for i in range(length - 1):
string1 = ''
string += chars[i]
length1 = len(string)
for j in range(length - 1 - i):
if j % 2 != 0:
string1 += chars[length - 1 - j]
else:
string1 += chars[length -1 - j].center(3, '.')
for k in range(i + 2, length):
if k % 2 != 0:
string1 += chars[k].center(3, '.')
else:
string1 += chars[k]
string1 = string1.center(dots, '.')
print(string1)
When char length is odd
When char length is even
This is python. There are a multitude of useful string functions you could use to create inventive ASCII art in a handful lines of code.
Some of the most important ones would be
str.join
,str.Xjust
. We'll also make use ofchr
andord
to iterate over character ranges.First, define a function that'll handle padding.
The first line of code will build the first half of the diamond line. The second line joins the first half with the centre letter, and the reversed version of the first half.
Next, determine the range - how big your diamond is going to be.
Now, you'll need two separate loops - one for the upper diamond and the other for the lower one. Both loops call
pad
at each iteration.end = 'E'
:end = 'F'
:Seth Difley's answer explores an alternative approach which involves building the first half of the diamond and reversing it to obtain the second half. Indeed, this approach can also be adopted to this solution, something along the lines of:
Which also results in the same output, and is faster.