2013-09-30 33 views
1

我有這樣的代碼:Floyd的三角

def floyd(n): 
    count = 1 
    string = "" 
    for i in range(1,n+2): 
      for j in range(1,i): 
       string = string + " " + str(count) 
       count = count + 1 
      print(string) 
      string = "" 
print floyd(6) 

它打印:

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 

,但我希望它看起來像這樣:

 1 
     2 3 
    4 5 6 
    7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 

你幫我該怎麼辦所以?請參考

+0

開始7行看起來偏離中心給我。它距離下一行的左邊緣兩個空格,距右邊緣四個空格。 7不應該對齊,因此它位於「12」中的「1」? – Kevin

回答

5

Python字符串實際上有一個內置的center()方法可以爲你做到這一點。

print(string.center(total_width)) 

您可以事先設置了total_width

total_width = -1 

for i in xrange(0, n): 
    total_width += 1 + len(str((n + n * n)/2 - i)) 

或者

total_width = sum(1 + len(str((n + n * n)/2 - i)) for i in xrange(0, n)) - 1 

也就是說,數字的字符串表示的長度的同一行的總和作爲第n個三角形數(n 2 + n)÷2.

Here’s a demo!

1

使用n你可以先找到最後一排,最後一個數字爲(n**2 + n)/2,所以在最後一行中的第一個數字爲((n**2 + n)/2) - (n-1),現在可以創建的最後一行用str.join和列表理解:

x = ((n**2 + n)/2) 
last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1)) 

現在我們可以在字符串格式中使用此行的寬度來正確居中其他行。

代碼:

from itertools import count 
def floyd(n): 
    x = ((n**2 + n)/2) 
    last_row = ' '.join(str(s) for s in xrange(x-(n-1), x+1)) 
    width = len(last_row) 
    c = count(1) 
    for x in xrange(1, n): 
     line = ' '.join(str(next(c)) for _ in xrange(x)) 
     print "{:^{}}".format(line, width) 
    print last_row 

演示:

>>> floyd(6) 
     1   
     2 3  
     4 5 6  
    7 8 9 10  
11 12 13 14 15 
16 17 18 19 20 21 
>>> floyd(8) 
      1   
      2 3   
     4 5 6   
     7 8 9 10   
    11 12 13 14 15  
    16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 32 33 34 35 36 
0

嘗試...

進口java.util.Scanner的;

公共類主要{

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    boolean status =true; 
    while(status){ 

    int a,b,c,num=1; 
    Scanner scn = new Scanner(System.in); 
    System.out.println("Enter how may row you want"); 
    c = scn.nextInt(); 
    System.out.println("Process done "); 
    for (a=1; a <= c ;a++) 
    { 
     for(b=1 ; b <= a;b++) 
     { 
      System.out.print(num+" "); 
      num++; 
     } 
     System.out.println(); 

    } 
    System.out.println("Do you want to continue?"); 
    String answer = scn.next(); 


    if(answer.equalsIgnoreCase("y")){ 
     status = true;} 
    if(answer.equalsIgnoreCase("n")){ 
     System.out.println("Good bye..."); 
     System.exit(0); 
    } 
} 

}}