[ad_1]
指定された行数について、Python で次のパターンを出力します。
N = 5 のパターン
1 2 3 4 5
11 12 13 14 15
21 22 23 24 25
16 17 18 19 20
6 7 8 9 10
私が試したこと:
Python
n = int(input()) upper = int(n/2)+1 lower = n - upper start_i_lower = 0 for i in range(0, upper): if i != 0: i = i + i start = n*i + 1 end = start + n for j in range(start, end): print(j, end =" ") start_i_lower = i print() start_i_lower -= 1 for i in range(0, lower): if(n%2 == 0): start_i_lower -= 1 start = n*(start_i_lower-1) + 1 end = start + n for j in range(1, n+1): print(j+n, end =" ") print()
解決策 1
これを試して:
Python
n = 5 h = 0 d = int(n/2)+1 for r in range(0, n): s='' for c in range(1, n+1): if r<d: h = r*2 elif r==d: h = d else: h = int(d/3) s+=str(h*n+c) + ' ' print(s)
結果:
1 2 3 4 5 11 12 13 14 15 21 22 23 24 25 16 17 18 19 20 6 7 8 9 10
解決策 7
n = int(input()) if n % 2 == 0: n1 = int(n/2) n2 = n-n1 else: n1 = int(n/2)+1 n2 = n-n1 x = 1 i = 1 i1 = 1 #Upper pattern while i <= n1: for j in range(1, n+1): print(x, end=" ") x = x+1 print() if i == n1: break x = x+n i = i+1 #Lowe Pattern if n % 2 == 0: while i1 <= n2: for k in range(1, n+1): print(x, end=" ") x = x+1 x=x-(2*n) print() i1 = i1+1 x = x-n y=y+1 else: while i1 <= n2: x = x-(2*n) for k in range(1, n+1): print(x, end=" ") x = x+1 x=x-n print() i1 = i1+1
解決策 5
より最適化されたバージョンは次のようになります。
Python
n = 5 h = 0 d = int(n/2)+1 for r in range(0, n): s='' if r<d: h = r*2 elif r==d: h = d else: h = int(d/3) for c in range(1, n+1): s+=str(h*n+c) + ' ' print(s)
解決策 6
n = int(input( )) P = 1 for i in range(1, n + 1): for j in range(P, P + n): print(j, end=" ") print() if i == ((n + 1)//2): if (n % 2) != 0: P = n*(n - 2) + 1 else: P = n * (n - 1) + 1 elif i > ((n + 1) // 2): P = P - 2 * n else: P = P + 2 * n
かなり単純明快な質問です。 確かに少しトリッキーなもの
[ad_2]
コメント