2

1I'm looping over a series of numbers looking for range of numbers (e.g. <100).

E.g.: list = [1, 2, 3, 125, 7, 8, 9, 200]. I want to get in a file: 1-3, 7-9. The problem I faced is that the outer loop will reiterate over items in an inner loop, so the output I get is: 1-3, 2-3, 3, 7-9, 8-9, 9.

My current strategy which works:

counter = 1

for i in range(len(list)):  # outer loop
    if counter > 1: # prevents the outer loop from iterating the numbers iterated in inner loop
        counter -= 1
        continue
    elif counter <=1:
        while list[i] < 100:
            i +=1
            counter +=1
            if list[i] > 100:
                print list[i-counter], '-', list[i]
                break

I'm wondering if there is a more pythonic way to get the outer loop to skip over items that have been iterated in the inner loop, instead of using an additional counter (like I did above). Thanks.

Edit: There have been few replies that focused on consecutive numbers. My mistake, the number don't have to be consecutive. I just need the first and last number in that range E.g. list = [1,4,8, 12, 57, 200, 4,34, 300]. Output: 1 - 57, 4 - 34. The list and criteria is dependent on user. The criteria will always be a number with comparison operator '<'. Thanks.

3 Answers 3

4

You don't need two loops. One is sufficient:

def ranges(seq):
  it = iter(seq)
  start = end = next(it)
  for val in it:
    if val == end + 1:
      end = val
    else:
      if end - start > 1:
        yield start, end
      start = end = next(it)

for start, end in ranges([1, 2, 3, 125, 7, 8, 9, 200]):
  print('%d-%d' % (start, end))

The logic is slightly different to yours: it looks for subsequences that consist of consecutive numbers (1 2 3 and 7 8 9 in your example). If you need to, it's easy to change the logic to also break the sequences at any number >= 100.

2
  • Thanks for your reply, I'm still trying to figure it out. I've also added additional information on my problem, will your suggestion still work?
    – jonoave
    Jan 31, 2013 at 17:49
  • 1
    I tried this method and it works very well with what I need. A second question, I need the positions of the items as well in the list. Is there a quick way to get the index values of 'start' and 'end' as well? Thanks
    – jonoave
    Feb 1, 2013 at 10:43
2

an alternative approach, based on while loops:

def print_ranges(given_list, limit):
    while given_list:
        start = end = given_list.pop(0)
        if start < limit:
            while given_list and (given_list[0] < limit):
                end = given_list.pop(0)
            if (end != start):
                print "%d-%d"%(start,end)  # or save it in another list

some tests:

>>> print_ranges([1,4,8, 200, 4,34, 72, 300], 100)
1-8
34-72

>>> print_ranges([1, 4, 8, 12, 57, 200, 4, 34, 300], 100)
1-57
4-34

>>> print_ranges([1, 4, 8, 12, 57, 200, 4, 34, 300], 250)
1-34
11
  • Sorry sorting is not an option. I failed to mention in my original post that the positions of the items in the list is important as well and will be outputted. Actually I'm not too clear whether your suggestion is in line with what I need. The criteria (e.g. <100) and list are actually dependent on user input.
    – jonoave
    Jan 31, 2013 at 17:32
  • ok, nevermind, it's really optional... I've added it for completeness and for future readers. :)
    – furins
    Jan 31, 2013 at 17:33
  • @jonoave I've edited my answer and added the constraint that end < 100. Obviously given_list will be provided by user input, I just defined it as in your question to provide a working example.
    – furins
    Jan 31, 2013 at 17:43
  • Thanks, your changes make a bit more sense now and I will try to see it fits with what I need.
    – jonoave
    Jan 31, 2013 at 17:52
  • @jonoave now it's more clear so I've changed the code a little bit to fit your second example. If you wish you can replace 100 with a variable (provided by the user)
    – furins
    Jan 31, 2013 at 17:54
0

using zip():

zip(lis,lis[1:]) returns something like:

 [(0, 1),
 (1, 2),
 (2, 3),
 (3, 5),
 (5, 6),...]

now you can iterate over this list to check if the difference is 1 or not.

code:

In [103]: def ranges(lis):
    ans=[]
    z=zip(lis,lis[1:])
    for x,y in z:
        if y-x==1:
            ans.extend([x,y])
        else:    
            if ans:
                yield "{0}-{1}".format(min(ans),max(ans))
                ans=[]
    if ans:        
          yield "{0}-{1}".format(min(ans),max(ans))
   .....:         

In [104]: lis=[0,1,2,3,5,6,7,8,10,11,2,3,4]

In [105]: list(ranges(lis))
Out[105]: ['0-3', '5-8', '10-11', '2-4']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.