2015-07-11 115 views
1

我必須初始化一個列表L並按照N行給出的N個命令。打印Python列表

命令將在8個命令1,如下所示:

append 
extend 
insert 
remove 
pop 
index 
count 
sort 
reverse 

請在下面找到我的代碼。我只是一個初學者。請原諒我的錯誤。

樣品輸入:

12 
insert 0 5 
insert 1 10 
insert 0 6 
print 
remove 6 
append 9 
append 1 
sort 
print 
pop 
reverse 
print 

輸出應該是:

[6, 5, 10] 
[1, 5, 9, 10] 
[9, 5, 1] 

而且我的代碼是:

L = [] 
L.insert(0,5) 
L.insert(1,10) 
L.insert(0,6) 
print L 
L.remove(6) 
L.append(9) 
L.append(1) 
L.sort() 
print L 
L.pop() 
L.reverse() 
print L 

即使它在某種程度上做這項工作,它是不準確。我怎樣才能簡化它?

+1

輸入如何與代碼相關? –

+0

你得到的輸出是什麼? – Kannaj

+0

另一個說明:如果你剛開始使用python,你可能會考慮用python 3而不是python 2來做這件事。祝你好運! – Klaster

回答

1

顯然的問題是關於編寫解釋這種小型的語言...像

L = [] 

# read the number of commands 
N = int(raw_input()) 

# execute N commands 
for x in xrange(N): 
    # read a line and split on spaces 
    cmd = raw_input().split() 

    # process the command 
    if cmd[0] == "insert": 
     L.insert(int(cmd[1]), int(cmd[2])) 
    elif cmd[0] == "pop": 
     L.pop() 

    ... implement all the commands ... 

    else: 
     raise RuntimeError("Unknown command " + repr(cmd)) 
1

我認爲,這次演習的目的是從數據驅動你的代碼,而不是試圖手動爲輸入的每一行寫入它。

我從輸入文本開始逐行處理它。對於每一行,我將你的文本分成動作和參數。 Python exec命令可用於執行給定的操作,但您應該注意,您的命令所需的格式對於每個命令而言都不相同。

input = """12 
insert 0 5 
insert 1 10 
insert 0 6 
print 
remove 6 
append 9 
append 1 
sort 
print 
pop 
reverse 
print""" 

L = [] 
allowed_commands = ['append', 'insert', 'pop', 'print', 'remove', 'reverse', 'sort']  

# Read the input in above and split it into a row at a time, skip the count at the start. 
for row in input.split("\n")[1:]: 
    # For each row, split it into a list of arguments 
    cols = [col for col in row.split(" ") if len(col)] 
    # The action is taken from the first column 
    action = cols[0] 

    # Ensure the action is one of the allowed commands  
    if action in allowed_commands: 
     arguments = ",".join(cols[1:]) 

     if action == "count": 
      command = "print len(L)" 
     elif action == "index": 
      command = "print L[%s]" % arguments[0] 
     elif action == "print": 
      command = "print L" 
     else: 
      command = "L.%s(%s)" % (action, arguments) 

     exec(command) 
    else: 
     print "'%s' is an unknown command" % action 

這給你以下的輸出:

[6, 5, 10] 
[1, 5, 9, 10] 
[9, 5, 1] 

我將它留給你將其轉換爲創建列表和手動輸入命令。

注意:使用exec可能相當危險,您必須確保只執行您允許的命令。