Reputation: 15
I'm trying to make a function, diamond(num), where num is the size of the 'diamond' that is made up of forward/backward slashes and spaces. E.g.
>>> diamond(3)
/\
/ \
/ \
\ /
\ /
\/
>>> diamond(2)
/\
/ \
\ /
\/
>>> diamond(1)
/\
\/
However, I feel like my code is too complicated. Is there a simpler way of doing this?
def reverse(value,end):
if end %2 != 0:
return None
MAX = end/2
START = (end/2)-1
turningPoint = (end/2)+1
numbers = {}
second = -MAX
for x in range(1,end+1):
if x < turningPoint:
numbers[x] = START-(2*(x-1))
if x >= turningPoint:
numbers[x] = second
return value + numbers[value]
def diamond(length):
output = ''
MAX = length
length *= 2
if length == 0 or length % 2 != 0:
return None
for x in range(1,length+1):
var = int(reverse(x,length))
if x < MAX+1:
output += ' '*var + '/' + ' '*((MAX-var)*2) + '\\' + '\n'
else:
output += ' '*var + '\\' + ' '*((MAX-var)*2) + '/' + '\n'
return print(output)
Upvotes: 1
Views: 63
Reputation: 939
This will help:
def printDiamond(n):
upperHalf = ""
lowerHalf = ""
for row in range(1, n + 1):
outerSpaces = n - row
innerSpaces = 2*row - 2
rowTempl = outerSpaces * " " + "{c1}" + innerSpaces * " " + "{c2}" + "\n"
upperHalf += rowTempl.format(c1='/', c2='\\')
lowerHalf = rowTempl.format(c1='\\', c2='/') + lowerHalf
print(upperHalf + lowerHalf)
printDiamond(1)
printDiamond(2)
printDiamond(5)
printDiamond(7)
Output:
/\
\/
/\
/ \
\ /
\/
/\
/ \
/ \
/ \
/ \
\ /
\ /
\ /
\ /
\/
/\
/ \
/ \
/ \
/ \
/ \
/ \
\ /
\ /
\ /
\ /
\ /
\ /
\/
Upvotes: 0
Reputation: 22031
May I recommend the following function?
def get_diamond(size):
return '\n'.join([' ' * (size - i - 1) + '/' + ' ' * i + '\\'
for i in range(size)] +
[' ' * (size - i - 1) + '\\' + ' ' * i + '/'
for i in reversed(range(size))])
You can use it like so:
for i in range(5):
print(get_diamond(i + 1))
After running the code, your screen should look like this:
/\
\/
/\
/ \
\ /
\/
/\
/ \
/ \
\ /
\ /
\/
/\
/ \
/ \
/ \
\ /
\ /
\ /
\/
/\
/ \
/ \
/ \
/ \
\ /
\ /
\ /
\ /
\/
If you do not mind something a bit more convoluted, this function does the same as the first:
def get_diamond(s):
return '\n'.join(' ' * (s - w - 1) + a + ' ' * w + z for a, z, r in (
('/', '\\', range(s)), ('\\', '/', reversed(range(s)))) for w in r)
Upvotes: 2