Python Itertools permutations only letters and numbers

后端 未结 6 1093
無奈伤痛
無奈伤痛 2021-01-13 12:42

I need to get only the permutations that have letters and numbers (The permutation can not be. \"A, B, C, D\" I need it like this: \"A, B, C, 1\")

In short, the perm

6条回答
  •  悲&欢浪女
    2021-01-13 13:17

    mylist=[]
    for x in permutations([0,1,2,"a","b","c"],4):
        print (x)
        mylist.append(x)
    for t in permutations([3,4,"c","d"]):
        print (t)
        mylist.append(t)
    

    I split them 3 digit-3letter, 2digit-2letter. So compile t and x is your answer.First for loop cant contain only numbers or only letters because its permutations 4. Second one cant also same reason.So compile the results in a list, means your answer.

    How to calculate the time;

    import time
    mylist=[]
    start=time.time()
    for x in permutations([0,1,2,"a","b","c"],4):
        print (x)
        mylist.append(x)
    for t in permutations([3,4,"c","d"]):
        print (t)
        mylist.append(t)
    end=time.time()
    diff=end-start
    print ("It took",diff,"seconds")
    

    Output:

    ...
    ...
    ...
    ('c', 4, 'd', 3)
    ('c', 'd', 3, 4)
    ('c', 'd', 4, 3)
    ('d', 3, 4, 'c')
    ('d', 3, 'c', 4)
    ('d', 4, 3, 'c')
    ('d', 4, 'c', 3)
    ('d', 'c', 3, 4)
    ('d', 'c', 4, 3)
    It took 0.5800008773803711 seconds
    >>> 
    

    Edit for how much permutations are there:

    from itertools import permutations
    import time
    mylist=[]
    start=time.time()
    for x in permutations([0,1,2,"a","b","c"],4):
        print (x)
        mylist.append(x)
    for t in permutations([3,4,"c","d"]):
        print (t)
        mylist.append(t)
    end=time.time()
    diff=end-start
    print ("There is {} permutations.".format(len(mylist)))
    print ("It took",diff,"seconds")
    

    Output:

    ...
    ...
    ...
    ('d', 3, 4, 'c')
    ('d', 3, 'c', 4)
    ('d', 4, 3, 'c')
    ('d', 4, 'c', 3)
    ('d', 'c', 3, 4)
    ('d', 'c', 4, 3)
    There is 384 permutations.
    It took 0.5120010375976562 seconds
    >>> 
    

提交回复
热议问题