4 ms·
A one-line solution in Python: print '\n'.join(['%s%s%s' % (' '*((9-step)/2), '*'*step, ' '*((9-step)/2)) for step in [1, 3, 5, 7, 9, 9, 7, 5, 3, 1]]) Not
by RyanMcGreal 17y ago
A one-line solution in Python:
print '\n'.join(['%s%s%s' % (' '*((9-step)/2), '*'*step, ' '*((9-step)/2)) for step in [1, 3, 5, 7, 9, 9, 7, 5, 3, 1]])
Not diamond shaped, but moderately obfuscated.
- BoppreH 17y agoI think the hardest part of the problem is defining the formula that generates the number (or position) of asterisks at each line. And you hard-coded it in a list. I consider this cheating.
- BoppreH 17y agoHere, a one-liner that makes its own calculations: print '\n'.join(max(4-i, i-5)*' ' + (min(i, 9-i)*2+1)*'*' for i in range(0, 10)) Edit: shaved off a few more characters and somehow made it slightly clearer. I would make it diamond shaped, but python will whine because of "invalid indentation".
- paulbaumgart 17y agoParameterized! def d(n): return '\n'.join(int(max((n-1)/2-i,i-n/2))*' '+(min(i,n-1-i)*2+1)*'*' for i in xrange(0,n))
- BoppreH 17y agoI have made a version of that myself just before posting here, but I made n be width, not the height. Still an interesting solution.
- joss82 17y agoSlightly shorter: print '\n'.join([" "abs(4-i) + ""(9-abs(8-i2)) for i in range(9)])
- BoppreH 17y agoThat actually doesn't do the trick because there is only one line 9 asterisks wide when it should be two. I don't think you can accomplish this replacing max/min with any combination of abs.
- joss82 17y agoYou're right, but I couldn't correct it right away (because of noprocrast and life). Also, formatting was wrong: print '\n'.join([" "abs(int(4.5-i)) + ""(10-abs(9-i2)) for i in range(10)])
- rbonvall 16y agoIf you enclose the expression with parenthesis, you can indent it however you like: print ('\n' .join(max (4-i, i-5) * ' ' + (min(i, 9 -i) * 2 + 1) * '*' for i in range (0, 10) ))