• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

describe

Write Python code that takes a string of data as template data and uses three generators to generate a specified number of pieces of data from the template data.

Please write the code to create the generator in solution.py, and we’ll run your code in main.py by importing it to see if it does this.

**

  • If the template data is not a multiple of 3, discard the last insufficient data and start the cycle from the first
  • If the number of template data is less than three, the template data is repeatedly generated as one data item

The sample

A sample:

When the input data is:

7,0,5,5,3,10,9,10,3,5,5,6,7,4,10,8,7,7,7 [1]Copy the code

The output data is:

(1, 0, 5] [5, 3, 10] [9, 10, 3], [5, 5, 6] [7, 4, 10] [8, 7, 7] [1, 0, 5]Copy the code

Example 2:

When the input data is:

10,2,5,10,3,3,0,7,2,1,5,6,6,5,1,6,9 [8]Copy the code

The output data is:

[8, 2, 5] [10, 3, 3] [0, 7, 2] [1, 5, 6] [6, 5, 1], [8, 2, 5] [10, 3, 3] [0, 7, 2] [1, 5, 6] [6, 5, 1)Copy the code

Answer key

If the template data is not a multiple of 3, discard the last insufficient data and start the cycle generation again from the first place. Here, calculate the remainder of 3 to determine whether it is a multiple of 3. If it is not directly discarded. If the number of template data is less than three, the template data is repeatedly generated as one data item. Here we define a variable, increment it by one each time it is generated, and then compare it with the input value to determine whether we need to exit.

class DataLoader:
    def __init__(self, data):
        # write your code here
        self.L1=[]
        for i in data:
            self.L1.append(i)
        for i in range(len(self.L1)%3):
            self.L1.pop()

    def get_data(self):
        # write your code here
        j = 0 
        while True:
            self.L=[]
            if j>=len(self.L1)-1:
                j = 0
            for i in range(3):
                self.L.append(self.L1[j])
                j+=1
            yield self.L
Copy the code