如何在Python中生成带90%同值转移概率的24长度[30,170]随机数组
Implementing State-Dependent Random Array in Python
Got it, let's adjust your code to meet the state transition probability requirements! The core idea here is to use a Markov chain—each element depends only on the previous one, instead of picking values entirely at random every time.
Step-by-Step Breakdown
First, let's restate your rules clearly to make sure we're aligned:
- If the current element is
30, there's a 90% chance the next element stays30, 10% chance it switches to170 - If the current element is
170, there's a 90% chance the next element stays170, 10% chance it switches to30 - Final array length needs to be 24
Basic, Easy-to-Read Implementation
Here's a straightforward version that directly maps your rules into code:
import random seq = [30, 170] target_length = 24 # Start with a random initial element (you can hardcode this to 30/170 if needed) random_array = [random.choice(seq)] # Generate the remaining 23 elements using the transition rules for _ in range(target_length - 1): current_val = random_array[-1] if current_val == 30: # 90% to stay, 10% to switch next_val = 30 if random.random() < 0.9 else 170 else: # current_val is 170 next_val = 170 if random.random() < 0.9 else 30 random_array.append(next_val) print(random_array)
Scalable Alternative (For Future Changes)
If you ever need to add more states or tweak probabilities easily, using a transition dictionary is a cleaner approach:
import random seq = [30, 170] target_length = 24 # Define state transitions in a dictionary for flexibility transition_rules = { 30: {"states": [30, 170], "weights": [0.9, 0.1]}, 170: {"states": [170, 30], "weights": [0.9, 0.1]} } random_array = [random.choice(seq)] for _ in range(target_length - 1): current_val = random_array[-1] # Use weighted random selection for the next state next_val = random.choices( transition_rules[current_val]["states"], weights=transition_rules[current_val]["weights"], k=1 )[0] random_array.append(next_val) print(random_array)
How It Works
- Both versions start with a random initial element (replace
random.choice(seq)with a fixed value like30if you want a deterministic start) - For each subsequent element:
- The basic version uses
random.random()(which returns a float between 0 and 1) to check if we stay or switch based on your 90/10 rule. - The scalable version uses
random.choices()with weights, which makes it trivial to add new states or adjust probabilities later without rewriting conditional logic.
- The basic version uses
内容的提问来源于stack exchange,提问作者Hello3456
相关产品推荐
相关产品推荐

