簡體   English   中英

在數字序列中查找丟失的數字

[英]Find lost number in number sequence

好的,所以基本上我所要做的就是按順序找到丟失的號碼。

對於輸入數據:

5
2 3 1 5

正確答案是

4
def findMissing(n):
    
    tempList = []
    for i in range(0, n-1):
        tempList.append(str(input()))
    return [x for x in range(tempList[0], tempList[-1]+1) if x not in tempList] 
    

findMissing(5)

Output:

---> 11     return [x for x in range(tempList[0], tempList[-1]+1) if x not in tempList]

TypeError: must be str, not int

我已經嘗試過類似的方法,我想創建一個列表,輸入將出現在該列表中,然后我將從該列表中返回缺失的值,但它不起作用。

您可以使用range生成一set “完整”序列,然后將set.difference與給定的數據列表一起使用,然后應該包含缺少的項目。

def findMissing(n, data):
    return set(range(1, n+1)).difference(data).pop()

>>> findMissing(5, [2, 3, 1, 5])
4

由於您知道序列是連續的,因此您也可以通過算法來執行此操作

def findMissing(n, data):
    return sum(range(1,n+1)) - sum(data)

>>> findMissing(5, [2, 3, 1, 5])
4

這個錯誤實際上來自這一步:

tempList[-1]+1

重現這種情況的方法是:

'1' + 1
TypeError: must be str, not int

您需要添加類似的類型。 您可以通過執行int(input())將字符串類型轉換為 int 來修復它。

range也會在str arguments 上引發錯誤:

range('1', '3')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer

所以確保你給它 integer arguments。

@Cory Kramer 使用set symmetric difference回答的另一個變體:

def find_missing(number, data):
    return (set(data) ^ set(range(1, number + 1))).pop()

find_missing(5, [2, 3, 1, 5])

>> 4

查看官方文檔以獲取更多信息。

暫無
暫無

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

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