2014-11-03 35 views
-9

我可以在python中單行寫入以下代碼嗎?
在單行中寫入python代碼

t=int(input()) 
while t: 
    t-=1 
    n=int(input()) 
    a=i=0 
    while not(n&1<<i): 
     i+=1 
    while n&1<<i: 
     n^=1<<i 
     a=a*2+1 
     i+=1 
    print(n^1<<i)+a/2 

如果沒有,我怎麼能寫這段代碼在儘可能小的線?
(PS:我可以減少這6條線,它可以是任何更好)
我的解決方案
t=int(input()) while t: t-=1;n=int(input());a=i=0 while not(n&1<<i):i+=1 while n&1<<i:n^=1<<i;a=a*2+1;i+=1 print(n^1<<i)+a/2
感謝

+3

第一個問題 - 's1','s2','s7'會影響'expr1'的真實性嗎? 's3'影響'expr2'嗎? 's4','s5'或's6'會影響'expr3'嗎?如果沒有真正的代碼,我們甚至無法告訴你是否有一些'while'循環會執行,更不用說執行是否會停止。 – furkle 2014-11-03 19:58:59

+0

我認爲's'代表'語句' – Beginner 2014-11-03 19:59:46

+2

@Beginner是的,我知道,但這並不能幫助我們真正理解代碼中會發生什麼。如果我們甚至不知道'expr2'是否會首先是'真',或者如果它'真',那麼它是否會被假'假',我們怎麼能壓縮它呢?如果它是前者,我們可以通過扔掉'expr2'來壓縮它。如果是後者,我們可以扔掉'expr3'。無論如何,代碼將是相當無用的。 – furkle 2014-11-03 20:01:09

回答

1

由於蟒蛇list comprehensions是圖靈完備,不需要換行,任何程序都可以寫成python oneliner。

如果執行任意限制(???像「陳述的順序」 - 這是什麼,即使是在源代碼意味着執行順序首先apperarance),那麼答案是:可以消除一些換行符,但不是全部。

,而不是

if x: 
    do_stuff() 

你可以這樣做:

if x: do_stuff() 

,而不是

x = 23 
y = 42 

你可以這樣做:

x,y = 23, 42 

和替代

do_stuff() 
do_more_stuff() 

你可以做

do_stuff; do_more_stuff() 

如果你真的,真的要,可以exec某行的多行Python程序,使你的程序變得例如:

exec('''t=int(input())\nwhile t:\n t-=1;n=int(input());a=i=0\n while not(n&1<<i):i+=1\n while n&1<<i:n^=1<<i;a=a*2+1;i+=1\n print(n^1<<i)+a/2\n''') 

但是,如果你在「真實」代碼中這樣做,例如不只是爲了好玩,小貓死了。

0

它不建議經常崩潰在Python行,因爲你失去的Python著名的簡單性和清晰度的方式。而且你經常不能摺疊線條,因爲縮進級別用於定義塊結構/嵌套。

但是,如果你真的想要一個濃縮版:

print "s0" 
while True: 
    print "s1"; print "s2" 
    while True: print "s3" 
    while True: print "s4"; print "s5"; print "s6" 
    print "s7" 

(如果你的表情已被替換爲True simplicity`)