lundi 19 décembre 2022

How to prevent duplicates in random selection?

I wrote small program to populate my game with NPCs named by random selections from first name and last name lists. It worked but sometimes there are duplicate names selected. How can I prevent duplicates?

I could use dict but I prefer list. Is this big disadvantage? The commented block in adding_male_NPC is my attempt to solve this problem.

import random

women_names = ["Jennifer", "Jenna", "Judith", "Becky", "Kelly"]
man_names = ["Adam", "John", "Jack", "Jim", ]
surnames =["Salzinger", "Jefferson", "Blunt", "Jigsaw", "Elem"]
marriage_status = ["Single", "In couple", "Engaged", "Married", "Divorced", "Widow"]
male_NPCs = []
list = []


def clr_list(list):
    del list


def randomizer(list):
    random_choice = random.choice(list)
    clr_list(list)
    return random_choice


def random_male():
    male_surname = randomizer(surnames)
    male_name = randomizer(man_names)
    male_NPC = male_name + " " + male_surname
    return (male_NPC)


def add_one_man():
    male_NPCs.append(random_male())
    return


def addding_male_NPC(count_of_NPC_males):
    while count_of_NPC_males > 1:
        add_one_man()
        # for m in male_NPCs:
        #     unique_count = male_NPCs.count(m)
        #     if unique_count > 1:
        #         male_NPCs.pop(unique)
        #         count_of_NPC_males +=1
        #     else:
        count_of_NPC_males -= 1


count_of_NPC_males = int(input("How many males should create?: "))
addding_male_NPC(count_of_NPC_males)

print(male_NPCs)
print(len(male_NPCs))

So i tried this but its impossible to count strings or somehow don't use well .count what is most possible. Get idea to take indexes before creating sum of stings and use it to check double but i feel that i make circles. I understand that provided list of names and surnames are not guarantee make doubles with high numbers but you got the point of this.

def addding_male_NPC(count_of_NPC_males):
    while count_of_NPC_males > 1:
        add_one_man()
         for m in male_NPCs:
             unique_count = male_NPCs.count(m)
             if unique_count > 1:
                 male_NPCs.pop(unique)
                 count_of_NPC_males +=1
             else:
                  count_of_NPC_males -= 1

Edit This is so sad :(

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
print(mylist)

But anyway it will cut planned and needed numbers of item. So question is still active. This answer is quite half answer. I wait for better one.




Aucun commentaire:

Enregistrer un commentaire