Search code examples
pythonnumbersincrement

Python create groups of incremented numbers


In python, I'm trying to generate groups of numbers with defined increments for:

  • each group and the next
  • first and last numbers in each group (i.e. between the first and second numbers and also between the last and the last but one)
  • the remaining numbers of each group

Example: (groups containing 6 numbers each)

[0, 1, 6, 11, 16, 17], [20, 21, 26, 31, 36, 37], [40, 41, 46, 51, 56, 57], ... 

Increments in this example:

  • between groups: 3
  • first and last number in each group: 1
  • the remaining numbers: 5

Here's what I have tried so far:

import numpy as np
n = 5     #increment size of remaining numbers in each group
m = 3     #increment size between groups

main = 0.0

for j in np.arange(0, 3):         #the number of generated groups
  for i in np.arange(0, 6):       #how many numbers in each group
    print("{:#.3g}".format(main)) #sig figs
    main += n
    
  main += m - n
  print()

Result:

0.00
5.00
10.0
15.0
20.0
25.0

28.0
33.0
38.0
43.0
48.0
53.0

56.0
61.0
66.0
71.0
76.0
81.0

Question: How to put an extra increment for the first and last number in each group?


Solution

  • we can store the value of the number you want to print in a variable called main. As we loop through the group you want to print, we check if it is the first or last number, if so, increment main by 1, otherwise, increment main by n. Add m to main after a group and print out main every time

    n = 5 # increment size of remaining numbers in each group
    m = 3 # increment size between groups
    l = 6 # numbers in a group, in your case 6
    main = 0 # the number that we print and increases with iterations
    for _ in range(10): # this runs for 10 iterations, use while(true) to run forever
        for j in range(l): # loops as many times as numbers in a group
            print("{:#.3g}".format(main)) # print main with sig figs
            if j == 0 or j == l - 2: # if first in group or last, only increase main by 1
                main += 1
            else: # otherwise, increase main by n
                main += n
        print('') # print a new line
        main += m - n # add m to main. n is subtracted because an extra n was added at the end of a group