创建一个包含4个字母的随机列表,每个字母出现15次,不要连续重复。

huangapple go评论58阅读模式
英文:

Creating a random list of 4 letters in which each letter appears 15 times and does not repeat twice in a row

问题

我想创建一个包含4个字母的随机列表,字母包括 'A'、'B'、'C' 和 'D',每个字母出现15次,且同一字母不连续重复出现。

我尝试了下面的代码,但结果中出现了连续两次重复的字母:

import random

def create_random_list():
    try:
        letters = ['A', 'B', 'C', 'D']
        freq = 15
        
        lst = []
        for letter in letters:
            lst += [letter] * freq
        
        random.shuffle(lst)
        
        # 检查没有字母连续重复出现
        for i in range(1, len(lst)):
            if lst[i] == lst[i-1]:

                # 如果有字母连续重复出现,重新洗牌列表
                random.shuffle(lst)
                break
        
        return lst
    except Exception as e:
        print(f"错误: {e}")
        return []

print(create_random_list())
英文:

I would like to create a random list of 4 letters, with the letters 'A', 'B', 'C' and 'D', where each letter appears 15 times and the same letter is not repeated twice in a row.

I tried the code below but the letters repeated twice in a row appear in the result:

import random

def create_random_list():
    try:
        letters = ['A', 'B', 'C', 'D']
        freq = 15
        
        lst = []
        for letter in letters:
            lst += [letter] * freq
        
        random.shuffle(lst)
        
        # Check that no letter appears twice in a row
        for i in range(1, len(lst)):
            if lst[i] == lst[i-1]:

                # If a letter appears twice in a row, shuffle the list again
                random.shuffle(lst)
                break
        
        return lst
    except Exception as e:
        print(f"Error: {e}")
        return []

print(create_random_list())

答案1

得分: 0

原则上,您可以像这样修复您的代码。您不知道第一次重洗是否会产生正确的结果。因此,您需要保持不断洗牌:

shuffle = True
while shuffle:
    random.shuffle(lst)
    
    # 检查是否有字母连续出现两次
    for i in range(1, len(lst)):
        if lst[i] == lst[i-1]:
            break
    else:  # 是的:这是正确的。请注意 Python 中的 for-else
        shuffle = False

但我猜想,考虑到您的参数,这可能会花费很长时间。可能只有极小部分可能的排列没有重复。因此,您可能需要一些生成方法,最有可能是一些基于前一元素选择随机下一个元素的回溯算法。

英文:

In principle, you can fix your code like this. You don't know that the first reshuffle will produce a correct result. So you need to keep shuffling:

shuffle = True
while shuffle:
    random.shuffle(lst)
    
    # Check that no letter appears twice in a row
    for i in range(1, len(lst)):
        if lst[i] == lst[i-1]:
            break
    else:  # yes: this is correct. Check for-else in Python
        shuffle = False

But my guess is that this might take forever given your parameters. Probably only a tiny fraction of possible permutations has no repetitions. So you probably need some generative approach, most likely some backtracking algorithm that picks random next elements based on the previous ones.

答案2

得分: 0

你目前代码的问题在于,在对列表进行洗牌后,你检查的是连续相同的字母,但并没有保证初始洗牌后的列表满足这个条件。要解决这个问题,你可以按如下方式修改你的代码:

import random

def create_random_list():
    try:
        letters = ['A', 'B', 'C', 'D']
        freq = 15

        lst = []
        for letter in letters:
            lst += [letter] * freq

        while True:
            random.shuffle(lst)
        
            # 检查没有字母连续出现两次
            for i in range(1, len(lst)):
                if lst[i] == lst[i-1]:
                    break
            else:
                # 没有连续的字母出现,因此列表是有效的
                return lst
    
    except Exception as e:
        print(f"错误: {e}")
        return []

print(create_random_list())

这个修改后的代码使用一个 while 循环来不断洗牌列表,直到找到一个没有连续相同字母的有效排列。for 循环用于检查连续的字母,如果发现任何连续的字母,它会跳出循环然后重新洗牌列表。如果循环完成而没有找到连续的字母,就表示列表是有效的,然后返回该列表。

英文:

The issue with your current code is that you're checking for consecutive letters that are the same after shuffling the list, but you're not guaranteeing that the initial shuffled list satisfies the condition. To solve this, you can modify your code as follows:

import random

def create_random_list():
    try:
        letters = ['A', 'B', 'C', 'D']
        freq = 15
    
        lst = []
        for letter in letters:
            lst += [letter] * freq
    
        while True:
            random.shuffle(lst)
        
        # Check that no letter appears twice in a row
            for i in range(1, len(lst)):
                if lst[i] == lst[i-1]:
                    break
            else:
                # No consecutive letters found, so the list is valid
                return lst
    
    except Exception as e:
        print(f"Error: {e}")
        return []

print(create_random_list())

This modified code uses a while loop to keep shuffling the list until a valid arrangement is found where no letter appears twice in a row. The for loop checks for consecutive letters, and if it finds any, it breaks out of the loop and shuffles the list again. If the loop completes without finding any consecutive letters, it means the list is valid, and it is returned

答案3

得分: 0

你需要一个字母池,并从中随机选取一个字母。如果它与上次选取的字母不同,然后将其添加到结果中。如果相同,那么将字母重新添加到池中。

但是,你必须确保池中的字母永远不会多于其他字母的数量加1(例如,count(A)=15,但count(BCD)=13),否则你将陷入无限循环。

英文:

You'd need a pool of letters and take a random letter from this pool. If it is different than the last taken letter, then add it to the result. If it is the same, then re-add the letter back to the pool.

You have to make sure though, that never there's a letter that's more than a number of other letters + 1 in the pool (e.g., count(A)=15, but count(BCD)=13), or you will get an infinite loop.

huangapple
  • 本文由 发表于 2023年7月18日 05:29:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定