dividing list of numbers in to groups

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • meggahertz
    New Member
    • Feb 2008
    • 2

    dividing list of numbers in to groups

    Hello Everyone!

    I need help with dividing a list of numbers in to groups of numbers that have constant difference between them. This constant number does not change it remains the same . e.g. 1000 in the following example:

    Thank you in advance.

    The list is:

    List = [ 40000, 41000, 42000, 43000, 54000, 55000, 56000, 90000]

    the routine i need should give me:

    grp1 = [40000, 41000, 42000, 43000]
    grp2 = [54000, 55000, 56000]
    grp3 = [90000]
  • hidrkannan
    New Member
    • Feb 2007
    • 32

    #2
    Below code might work...but may not be a natural one...

    [CODE=Python]
    import os
    import sys

    aList = [10,12,14,16]

    const = 7

    aList.sort()

    minVal = min(aList)
    maxVal = max(aList)

    agroupDict = {}
    count = 1
    agroupDict[count] = [minVal]
    aList.remove(mi nVal)
    value = minVal + const



    while value <= maxVal:
    if value in aList:
    agroupDict[count].append(value)
    aList.remove(va lue)
    value = value + const
    else:
    count = count + 1
    agroupDict[count] = []
    value = min(aList)

    if value > maxVal:
    for tempVal in aList:
    count = count + 1
    agroupDict[count] = [tempVal]
    print agroupDict
    [/CODE]

    SKN

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      [code=Python]def group_nums(numl ist, diff=1000):
      resultDict = {}
      idx = 0
      for i, num in enumerate(numli st):
      if i:
      if num - numlist[i-1] != diff:
      idx += 1
      resultDict.setd efault(idx, []).append(num)
      else:
      resultDict[idx] = [num, ]
      return resultDict

      numlist = [40000, 41000, 42000, 43000, 54000, 55000, 56000, 90000]
      dd = group_nums(numl ist)
      print dd.values()
      dd = group_nums(numl ist, 11000)
      print dd.values()[/code]Output:
      >>> [[40000, 41000, 42000, 43000], [54000, 55000, 56000], [90000]]
      [[40000], [41000], [42000], [43000, 54000], [55000], [56000], [90000]]
      >>>

      Comment

      Working...