-4

Given a set of integers, return True if the set is continuous (it only contains sequential integers.)

set1 = {1, 2, 3, 5}
set2 = {9, 8, 7, 10, 11, 12}

print (continuous_set(set1)) #returns False
print (continuous_set(set2)) #returns True
  • What have you tried so far? – Russ J Nov 08 '20 at 05:42
  • 1
    Does this answer your question? [Identify groups of continuous numbers in a list](https://stackoverflow.com/questions/2154249/identify-groups-of-continuous-numbers-in-a-list) – Russ J Nov 08 '20 at 05:43
  • Can you think of a mathematical rule that tells you how many elements should be in the set if it has this property, in terms of the minimum and maximum values? – Karl Knechtel Nov 08 '20 at 06:16
  • 1
    I'm glad to hear that you want to write a function, but this is a question and answer site. – TigerhawkT3 Nov 08 '20 at 06:28

2 Answers2

0

You can use the min and max functions

set1 = {1, 2, 3, 5}
set2 = {9, 8, 7, 10, 11, 12}

x1 = len(set1) == max(set1)-min(set1)+1  # False
x2 = len(set2) == max(set2)-min(set2)+1  # True
Mike67
  • 11,175
  • 2
  • 7
  • 15
0

numpy has a function that calculates the difference of values in an array. Sort the set so that closest numbers are closest, take the difference and see if they are all 1.

>>> import numpy as np
>>> 
>>> def continuous_set(s):
...     arr = np.array(sorted(s))
...     return (np.diff(arr)==1).all()
... 
>>> set1 = {1, 2, 3, 5}
>>> set2 = {9, 8, 7, 10, 11, 12}
>>> 
>>> print (continuous_set(set1)) #returns False
False
>>> print (continuous_set(set2)) #returns True
True
tdelaney
  • 73,364
  • 6
  • 83
  • 116