from random import shuffle


def k_fold_split(X, Y, k=10, shuffleDataset=True):
    """
    Split both list X and Y into k folds
    random will shuffle the data before, so two calls would not return the same folds

    ex: print(k_fold_split(["A", "B", "C", "D", "E", "F", "G"], ["a", "b", "c", "d", "e", "f", "g"], k=3, shuffleDataset=0))
    [[('A', 'a'), ('B', 'b')], [('C', 'c'), ('D', 'd')], [('E', 'e'), ('F', 'f'), ('G', 'g')]]
    """

    assert len(X) == len(Y) and k <= len(X)

    def chunkIt(seq, num):
        avg = len(seq) / float(num)
        out = []
        last = 0.0

        while last < len(seq):
            out.append(seq[int(last):int(last + avg)])
            last += avg

        return out

    indexes = list(range(len(X)))
    if shuffleDataset:
        shuffle(indexes)

    foldsIndexes = chunkIt(indexes, k)
    folds = [[(X[i], Y[i]) for i in foldIndexes] for foldIndexes in foldsIndexes]
    return folds