数组的长度为20,由应用程序使用。当应用程序启动时,数组为空,但是当用户开始填充它时,我需要找到所有未使用的数字和第一个未使用的数字。
将其视为一个停车场,20个点数为1至20。随着人们开始停放汽车,空间就会充满。人们可能不一定按顺序停车,有两个人可能停在1号和16号地点,所以我需要找到所有的缺点和第一个未使用的停车位。
以停车车为例,帮助您了解我正在尝试传达的内容。数组将始终为整数,并将保存从1到20的值。
以下代码应该如何执行
启动时,myArray为空:
myarray = []所以第一个缺少的数字应该是1(即第一个停车)
missingNumbers = [1,2,3,....... 20] firstMissingNoInMyArray = 1由于数组中的空格已填充,数组将如下所示:
myarray = [1,5,15]所以首先缺少的数字和缺少的数字是: / p>
missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14, 16,17,18,19,20-。 firstMissingNoInMyArray = 2我需要看到两个丢失的数字列表和第一个缺少的数字,任何人都可以帮助Python代码,我只限于使用Python 2.7.3;如果您在Python 3中有解决方案,请写入它,这可能有助于Python 3用户。
非常感谢。
解决方案您可以使用设置 s,那么您可以简单地减去集合。 为了看到第一个丢失的数字,您可以在结果集中执行 min :
all_nums = set(xrange(1,21)) arr = set(xrange(5,10)) print all_nums - arr print min(all_nums - arr)#注意集是无序的>> {1,2,3,4,10,11,12,13,14,15,16,17,18,19,20} 1这个应该用于Python 2.7.3,但是你应该考虑升级。 Python 2.7.3是7岁。
I'm new to python and I need help in trying to find all unused and the first unused/missing number in an array (in python 2.7.3)?
The array is of length 20 and is used by an application. When the application is launched, the array is empty, but as users begin to populate it, I need to find all unused numbers and first unused number.
Think of it as a car-park with 20 spots numbered 1 to 20. As people begin to park their cars, the spaces get filled. People may not necessarily park cars in a sequence, two people may park in spots 1 and 16, so i need to find all the missing spots and the first unused parking spot.
Parking cars is given as an example to help you understand what I'm trying to convey. Array will always be integer, and will hold values from 1 to 20.
Below is what the code should do
On Launch, myArray is empty:
myarray = []So the first missing number should be 1 (i.e. Park car in first spot)
missingNumbers = [1,2,3,.......20] firstMissingNoInMyArray = 1As spaces in the array are filled, the array will look like this
myarray = [1, 5, 15]So first missing number and missing numbers are:
missingNumbers = [2,3,4,6,7,8,9,10,11,12,13,14,16,17,18,19,20]. firstMissingNoInMyArray = 2I need to see both missing numbers list and the first missing number, can anyone help with Python code, I'm restricted to using Python 2.7.3; if you have a solution in Python 3, do write it, it may help Python 3 users.
Many thanks in advance.
解决方案You can use sets then you can simply subtract the sets. In order to see the first missing number you can take the min in the resulting set:
all_nums = set(xrange(1, 21)) arr = set(xrange(5, 10)) print all_nums - arr print min(all_nums - arr) # note that sets are unordered >> {1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} 1This should work on Python 2.7.3, but you should consider upgrading anyway. Python 2.7.3 is 7 years old.
更多推荐
如何在数组中找到所有未使用和缺少的数字(在Python中)?
发布评论