簡體   English   中英

python中的這個旋轉程序怎么了?

[英]what is wrong with this rotation program in python?

上下文:(謎題機器)我想做的是讓這段代碼運行,以便每次序列經過第一個輪子時第一個輪子都會旋轉。

問題是,我從互聯網上找到了如何使用下面的this序列進行旋轉的操作,但是當我更改變量周圍的位置以便自動進行更多操作時,旋轉不起作用。 if函數后會顯示錯誤消息。 我已經檢查並更改了變量的名稱,以使它們更簡單且更間距。 並且無法找出代碼中不起作用的內容。 是因為rotate函數不能使用變量還是什么?

import collections

theinput=raw_input('enter letter')
x=0



w=collections.ww=([1,2,3,4,5])


if theinput == 'a':
    w.rotate(x)
    a = w[0]
    x= x+1
    w.rotate(x)
 print a

謝謝

據我所知,您可能要使用的容器是deque ,據我所知,collections模塊中沒有ww這樣的變量。

為了說明背景,雙端隊列與列表非常相似,但是對雙端隊列進行了優化,您可以輕松地(高效地)在兩端添加和刪除項目,這比內置列表的效率略高。 此外,雙端隊列還提供了列表中找不到的一些其他方法,例如旋轉。 使用結合了基本操作的列表來完成相同的事情確實很容易,但對於雙端隊列,並沒有針對此類事情進行優化。 但是對於像Enigma機器模擬這樣的簡單操作,堅持使用列表無論如何都不會改變性能。

我想您正在嘗試執行以下操作:

import collections
w = collections.deque([1, 2, 3, 4, 5])
print "Deque state is ", w
print "First item in deque is", w[0]
w.rotate(1)
print "Deque state after rotation is ", w
print "First item in deque is", w[0]

這應該打印

Deque state is  deque([1, 2, 3, 4, 5])
First item in deque is 1 Deque
state after rotation is  deque([5, 1, 2, 3, 4])
First item in deque is 5

使用負數作為旋轉的參數以反過來

以下是僅使用內置列表的替代實現

w = [1, 2, 3, 4, 5]
print "List state is ", w
print "First item in list is", w[0]
x = 1 # x is rotation
w0 = w[:-x]
w = w[-x:]
w.extend(w0)
print "List state after rotation is ", w
print "First item in list is", w[0]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM