强制“没有2个相同的连续元素"被强制执行.在随机列表生成中 [英] Enforcing "no 2 same contiguous elements" in random list generation

查看:62
本文介绍了强制“没有2个相同的连续元素"被强制执行.在随机列表生成中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组4个字符串,想要生成16个元素的列表,但是强制执行该规则(或获得与执行该规则相同的结果),以使结果中的两个连续位置永远不会重复相同的元素列表.

I have a set of 4 strings and want to generate a list of 16 elements, but with enforcing the rule (or obtaining the same result as enforcing such rule) to never have the same element repeated in two contiguous positions in the resulting list.

几乎是Python的新手,我去检查了随机库中的不同方法,发现了许多不同且有用的方法来做类似的事情(random.shuffle几乎可以解决问题),但是没有一个解决这个问题我的特殊需求.

Being almost a total newbie in Python I went to check the different methods in the random library and found many different and useful ways to do something similar (random.shuffle would almost do the trick), but no one of those addressed this my particular need.

我应该使用哪种数据格式和方法?

What data format and what methods should I use?

推荐答案

伪代码算法:

  1. 对于n中的i(n是所需元素的数量)
  2. 生成下一个元素
  3. 如果与上一个元素相同,请重复2

使用random.choice从元素列表中随机选择一个元素.

Use random.choice to pick an element from a list of elements randomly.

以下是概念证明Python代码:

Here's a proof of concept Python code:

import random
sources = ['a', 'b', 'c', 'd']      # you said 4 strings
result = [random.choice(sources)]

while len(result) < 16:             # you said you need 16 elements    
    elem = random.choice(sources)
    if elem != result[-1]:
        result.append(elem)

此代码经过优化,以提高清晰度,而不是简洁,聪明或快速.

This code is optimized for clarity, not succinctness, cleverness or speed.

这篇关于强制“没有2个相同的连续元素"被强制执行.在随机列表生成中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆