Start by writing a function that takes two arguments, a list and a
position, and iterates over that list starting at that position so long
as the items are consecutive. It should return the count of consecutive
items starting from that position. Here is some test data you can run to
ensure your function gives the correct results:
def count_consecutive(alist, index):
# write some code here
# Test data
alist = [4, 6, 7, 8, 12, 13, 14, 15, 19, 20]
assert count_consecutive(alist, 0) == 1
assert count_consecutive(alist, 1) == 3
assert count_consecutive(alist, 2) == 2
assert count_consecutive(alist, 3) == 1
assert count_consecutive(alist, 4) == 4
assert count_consecutive(alist, 5) == 3
assert count_consecutive(alist, 6) == 2
assert count_consecutive(alist, 7) == 1
assert count_consecutive(alist, 8) == 2
assert count_consecutive(alist, 9) == 1
If you have trouble writing count_consecutive, start by doing the
process using pencil and paper. How would you count the consecutive
items? Now imagine you have to explain it to a simpleton, step by step,
so you have to explain every baby step needed.
Python is that simpleton. Start by a description of the steps in
ordinary English (or whatever your native language is), and then change
that to Python. We can help with that if you get stuck.
Once you have that count_consecutive function, you can use that to walk
through the list.
def get_consecutive_counts(alist):
# Start at the beginning.
index = 0
# Get the number at that index.
num = alist[index]
# Count the consecutive items.
count = count_consecutive(alist, index)
# Print the desired values.
print(num, count)
# Jump to the next non-consecutive item.
index = index + count
# and so on...
Once you have that working correctly (hint: you will need a while loop)
change the code to accumulate the (num, count) pairs into a list instead
of printing them.