2011-07-01 40 views

回答

12

將它們全部添加到集合中。然後從1-100填充的集合中減去。這裏是一個0-9的例子:

>>> set(range(10)) - set([1, 4, 5, 6, 8, 2]) 
set([0, 9, 3, 7]) 
>>> 

我有[1, 4, 5, 6, 8, 2]列出。要找出範圍0-9中的哪些數字缺失,我創建了一個全部爲0-9的集合,然後從中減去集合[1, 4, 5, 6, 8, 2]。並發現[0, 9, 3, 7]失蹤。

集合對此非常有效。作爲一個額外的好處,重複將被優雅地處理。

+1

這是一個非常漂亮的解決方案。 – Chetan

+0

沒有重複的數字,是的,他們將被排序。不,這不是作業:) – curious1

+0

如果你需要輸出排序只是轉儲到排序列表 –

1

如果L是號碼的列表,然後

set(L).difference(xrange(101)) 

保存從x範圍

In [1]: L=[1, 4, 5, 6, 8, 2] 

In [2]: timeit set(range(101)) - set(L) 
10000 loops, best of 3: 21.7 µs per loop 

In [3]: timeit set(L).symmetric_difference(range(101)) 
100000 loops, best of 3: 14.2 µs per loop 

In [4]: timeit set(L).difference(range(101)) 
100000 loops, best of 3: 9.73 µs per loop 
+0

你也可以使用'difference','symmetric_difference'本質上是XOR –

+0

@Eli,好點,更快 –

0

這裏的使用關聯的awk溶液創建一組(鍵值)陣列:

printf '%s\n' 1 4 5 6 8 2 | 
awk -F " " -v first=0 -v last=9 ' 
BEGIN { 
    for(i=first; i<=last; i++) 
    array[i] = 0 
} 
{ 
    for(i=1;i<=NF;i++) 
    array[$i] += 1 
} 
END { 
    for (num in array) 
    if (array[num] == 0) print num 
} 
' 
  • 首先,我們cre吃了一個給定範圍的所有數字,用作默認值爲0的單個鍵。
  • 然後每個輸入數字都被awk處理爲數組的一個鍵,以便數值遞增1.
  • 在結束時,只有那些沒有增加的鍵被打印出來,即值爲0(因爲它們在輸入數字範圍中缺失)。
0

慶典:

# first set up an array containing the whole range 
declare -a nums 
for i in {0..100}; do 
    nums[$i]=1 
done 

# then read the file and remove the numbers from it 
while read number; do 
    unset nums[$number] 
done < file.with.numbers 

# the remaining array keys are the numbers not found in the file 
for number in "${!nums[@]}"; do 
    echo $number 
done