dimanche 7 mars 2021

Assigning random alphabets to variables, but each alphabet must appear either 2 or 4 times in python

How do I assign random alphabet to variables and ensure that each alphabet must be assigned either 2 or 4 times? I have no problem with assigning random alphabets, but I'm having great trouble with the later part.

Here is my current code, which definitely has something wrong but I don't know how to fix it:

import random
import string
def assign():
    alphabet = string.ascii_uppercase
    n1 = random.choice(alphabet)
    n2 = random.choice(alphabet)
    n3 = random.choice(alphabet)
    n4 = random.choice(alphabet)
    n5 = random.choice(alphabet)
    n6 = random.choice(alphabet)
    n7 = random.choice(alphabet)
    n8 = random.choice(alphabet)
    
alphabet = string.ascii_uppercase
n1 = random.choice(alphabet)
n2 = random.choice(alphabet)
n3 = random.choice(alphabet)
n4 = random.choice(alphabet)
n5 = random.choice(alphabet)
n6 = random.choice(alphabet)
n7 = random.choice(alphabet)
n8 = random.choice(alphabet)   

if ((n1+n2+n3+n4+n5+n6+n7+n8).count(random.choice(alphabet))) != 2 or 4:
    assign()
else:
    print(n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,n13,n14,n15,n16)

How do I fix it so that whatever randomly assigned alphabet gets assigned to another variable or 3 more? (Assigned alphabets appear either 2 or 4 times). Thanks.




Aucun commentaire:

Enregistrer un commentaire