You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python掷骰子乘积频率统计:简化循环计数逻辑求助

Simplify Dice Product Frequency Counting with Dictionary Lookup

Your current code relies on a verbose chain of if-elif statements that’s inefficient and hard to maintain. The optimal fix is to use a dictionary to map product values to their indices in the frequency table, enabling O(1) lookup time. We can also structure the code into functions for clarity, as your friend suggested.

Here’s the improved code:

import random

def calculate_dice_product_frequencies(num_throws):
    possible_products = [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 30, 36]
    # Map each product to its index in the frequency list
    product_index_map = {product: idx for idx, product in enumerate(possible_products)}
    frequencies = [0] * len(possible_products)
    
    for _ in range(num_throws):
        dice1 = random.randint(1, 6)
        dice2 = random.randint(1, 6)
        product = dice1 * dice2
        # Use the dictionary to find the index and increment frequency
        frequencies[product_index_map[product]] += 1
    
    return possible_products, frequencies

def find_most_frequent_products(possible_products, frequencies):
    max_freq = max(frequencies)
    return [product for product, idx in enumerate(possible_products) if frequencies[idx] == max_freq], max_freq

def main():
    number_of_throws = int(input("How many times do you want to throw the dice? "))
    products, frequencies = calculate_dice_product_frequencies(number_of_throws)
    
    # Print product values
    print("The products")
    print("===========")
    for p in products:
        print(p)
    
    # Print frequencies
    print("\nThe frequency of the products")
    print("==============================")
    for freq in frequencies:
        print(freq)
    
    # Find and display most frequent product(s)
    most_frequent, max_freq = find_most_frequent_products(products, frequencies)
    print(f"\nMost frequent product(s): {most_frequent} (frequency: {max_freq})")

if __name__ == "__main__":
    main()

Key Improvements:

  1. Dictionary Mapping: Replaces all if-elif checks with a single dictionary lookup. This cuts down on redundant code and speeds up the loop—critical for large numbers of throws.
  2. Modular Functions:
    • calculate_dice_product_frequencies: Handles the core simulation and frequency counting, returning reusable results.
    • find_most_frequent_products: Isolates the logic for identifying the most common product(s), making the code easier to debug.
    • main: Manages user input, runs the simulation, and prints formatted results.
  3. Clean Initialization: frequencies = [0] * len(possible_products) automatically creates a zero-filled list matching the length of possible products, avoiding manual repetition.
  4. Concise Result Calculation: List comprehensions quickly find all products with the highest frequency, eliminating extra loops.

Why This Works Better:

  • Efficiency: Dictionary lookups take constant time, whereas the original if-elif chain took linear time per throw. This difference becomes significant with millions of simulations.
  • Maintainability: If you ever need to adjust the list of possible products, you only modify possible_products—the rest of the code adapts automatically.
  • Readability: Breaking the code into focused functions makes it easier to follow and modify later.

内容的提问来源于stack exchange,提问作者Allison Cranmer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:45:04