Cycle cycle



  • The language is not important, I'll explain the example of the Pyton language:

    myarray=['a', 'b', 'c']
    number=3
    def myfunc(myarray, number): #при number = 3
      newarray=[]
      for s1 in myarray
        for s2 in myarray
          for s3 in myarray
            newarray.append(s1+s2+s3)
      return newarray
    

    must return: aaaa, aab, aac, aba, abb, abc, et al. if number = 4, all four-digits that can be calculated, if 5, then five-digit, etc.

    How do you do that?



  • from itertools import product
    
    chars = 'abc'
    
    print(list(product(chars, repeat=3)))
    
    # [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ...
    

    Turn the output data into what you need.

    Here's the pseudo code of implementation. product() https://docs.python.org/3/library/itertools.html#itertools.product :

    def product(*args, repeat=1):
    
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)
    




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2