Home > database >  Check repeating number in every four numbers
Check repeating number in every four numbers

Time:11-09

I would like to find out how to find repeated numbers after every 4 numbers.

This is what I have.

arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]
  
size = len(arr)
  
for i in range(0,size,4):
  
    if arr[i] == arr[i   4] and arr[i   4] == arr[i   8] and arr[i   8] == arr[i   12 :
  

        print(arr[i])

The output should be 5.

CodePudding user response:

arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8]

for i in range(0, len(arr)):
    try:
        # checking the conditions
        if arr[i] == arr[i 4] and arr[i] == arr[i 8] and arr[i] == arr[i 12] :
            print(arr[i])
    except IndexError as e:
        # when you catch this exception, you can no longer find a number that match what you are looking for, so you break the loop.
        print(e)
        break

CodePudding user response:

This is a more general use case that gives you the count of EACH of the numbers (values, not index) in your arr that repeat every repeat index offset since there are multiple implementations and your question needs clarification (are you asking to return the index or the value, what if the streak stops, what is the first search index e.g. with 1 in your example do we only search starting with index 3 or restart another search with index 4, etc.):

arr = [4, 5, 2, 1, 1, 5 , 1, 8, 3, 5 ,0, 7, 2 , 5 ,6 , 5, 8] # Input
d = {each:0 for each in range(max(arr)   1)} # Blank dictionary with counts
repeat = 4 # Every _ indexes

for each in d.keys():
  first = arr.index(each) # Find first instance
  idxs = range(first,len(arr), repeat) # Indexes to search
  for every in idxs:
    if arr[every] == each:
      d[each]  = 1
    # Do you want to break if the streak stops?
    #else:
    #  break

Which outputs:

{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 4, 6: 1, 7: 1, 8: 1}

So for d[5] = 4, the number 5 only repeats four times not five (every fourth index) in arr. If you need the most repeated number {val:key for key,val in d.items()}.get(max(d.values())). d could also be a list since we used a sequential range and would make this last lookup easier by using d.index(max(d)). Also, this is not the best solution for a huge data set.

  • Related