所以这里的任务是:你输入一个数字从1到N的卡片。然后你输入所有这些数字,除了一个。 您的程序应该打印丢失的卡号。 这是我的代码:
n = int(input())
lst = []
for i in range(n - 1):
lst.append(int(input()))
for i in range(1, n + 1):
if not i in lst:
print(i)
但我需要在不使用列表的情况下这样做。怎么可能?
答案 0 :(得分:1)
继续记下数字并添加它们。
a = 0
a = a+newNumber
然后当你完成输入。当你下次接受输入时, 开始减去:
a = a-newNumber
最后的a
是您下次未输入的数字。
答案 1 :(得分:1)
您可以使用set.difference
:
set(range(1, n + 1)).difference(lst)
答案 2 :(得分:0)
import random
n = 12
s = {x for x in range(n)}
print(s)
pick = random.sample(s,1 ).pop(0)
print(pick)
s.remove(pick)
print(s)
输出:
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
10
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11}
答案 3 :(得分:0)
以下方法不使用任何列表。它假设您可以使用ast
模块:
import ast
cards_1 = input("Enter your cards: ")
cards_2 = input("Enter the list again, with one missing: ")
total_cards_1 = ast.literal_eval(cards_1.replace(" ", "+"))
total_cards_2 = ast.literal_eval(cards_2.replace(" ", "+"))
print("{} is missing".format(total_cards_1 - total_cards_2))
为您提供以下可能的输出:
Enter your cards: 1 3 7 12
Enter the list again, with one missing: 12 3 1
7 is missing
如果您无法使用ast
,那么危险的替代方法是使用eval()
,如下所示:
cards_1 = input("Enter your cards: ")
cards_2 = input("Enter the list again, with one missing: ")
total_cards_1 = eval(cards_1.replace(" ", "+"))
total_cards_2 = eval(cards_2.replace(" ", "+"))
print("{} is missing".format(total_cards_1 - total_cards_2))
应尽可能避免 eval()
。