Iterating over multiple indices with i > j ( > k) in a pythonic way

后端 未结 5 1772
心在旅途
心在旅途 2021-01-04 03:21

i need to iterate over a tuple of indices. all indices must be in the range [0, N) with the condition i > j. The toy example I present here deal

5条回答
  •  清酒与你
    2021-01-04 04:05

    You could solve this generally as follows:

    def indices(N, length=1):
        """Generate [length]-tuples of indices.
    
        Each tuple t = (i, j, ..., [x]) satisfies the conditions 
        len(t) == length, 0 <= i < N  and i > j > ... > [x].
    
        Arguments:
          N (int): The limit of the first index in each tuple.
          length (int, optional): The length of each tuple (defaults to 1).
    
        Yields:
          tuple: The next tuple of indices.
    
        """
        if length == 1:
           for x in range(N):
               yield (x,)
        else:
           for x in range(1, N):
                for t in indices(x, length - 1):
                    yield (x,) + t
    

    In use:

    >>> list(indices(5, 2))
    [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3)]
    >>> list(indices(5, 3))
    [(2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1), (4, 1, 0), (4, 2, 0), (4, 2, 1), (4, 3, 0), (4, 3, 1), (4, 3, 2)]
    

提交回复
热议问题