+ 4

How to print a hollow rectangle pattern with numbers using FOR loop? (Or any other loop)

/*The pattern should be like this*/ 1 2 3 4 5 16 6 15 7 14 8 13 12 11 10 9

24th Feb 2017, 6:23 AM
Logan
Logan - avatar
4 Answers
+ 5
# static version pat = [] for i in range(5): pat.append([' ']*5) j = 4 k = 4 for i in range(16): s = str(i+1) if i < 9: s = ' ' + s if i < 5: pat[0][i] = s elif i < 9: pat[i-4][4] = s elif i < 13: j = j - 1 pat[4][j] = s else: k = k - 1 pat[k][0] = s for i in range(len(pat)): pat[i] = ' '.join(pat[i]) pat = '\n'.join(pat) print(pat) # parametric version def get_pat(w,h=None): if h is None: h = w j = w - 1 k = h - 1 sz = ( j + k ) * 2 sp = ' ' * len(str(sz)) pat = [] for i in range(h): pat.append([sp]*w) for i in range(sz): s = str(i+1) n = len(str(sz)) - len(s) if n != 0: s = ' ' * n + s if i < w: pat[0][i] = s elif i < w + h - 1: pat[i-j][j] = s elif i < 2 * w + h - 2: j = j - 1 pat[k][j] = s else: k = k - 1 pat[k][0] = s for i in range(len(pat)): pat[i] = ' '.join(pat[i]) return '\n'.join(pat) print() print(get_pat(5)) print() print(get_pat(15,8)) # it seems that code playground trims outputs, so you can fix it by prepending a character different from a space at each line: replace the last join() call ( return statement in parametric version, and final assignement of 'pat' in static one ) with: # '.'+'\n.'.join(pat)
24th Feb 2017, 11:28 AM
visph
visph - avatar
+ 3
/*You can write code in any programming language you love*/
24th Feb 2017, 6:34 AM
Logan
Logan - avatar
+ 3
I want logic.
24th Feb 2017, 9:44 AM
Logan
Logan - avatar
+ 1
Use print, what's the problem?
24th Feb 2017, 7:49 AM
Leshark
Leshark - avatar