如何实现支持用户自定义输入数量的Python 3x+1问题可视化程序?
Solution for Dynamic Collatz Conjecture Visualization
Hey there! Let's revamp your code to let users specify how many numbers they want to analyze, then process each one independently and plot all their 3x+1 paths clearly.
First, let's fix the core issue in your current code: the nested while loops are trying to handle all numbers at once in each iteration, which won't correctly compute the full path for each number. Instead, we should calculate each number's Collatz sequence separately.
Here's the refactored code that meets your requirements:
from matplotlib import pyplot as plt def collatz_path(n): """Compute the full Collatz path for a given number, starting with the number itself.""" path = [n] while n != 1: if n % 2 == 0: n = n // 2 # Use integer division to keep values as whole numbers else: n = 3 * n + 1 path.append(n) return path # Step 1: Get the number of inputs from the user num_count = int(input("How many numbers would you like to process? ")) # Step 2: Collect all user-specified numbers numbers = [] for i in range(num_count): num = int(input(f"Enter number {i+1}: ")) numbers.append(num) # Step 3: Calculate paths for each number all_paths = [] for num in numbers: path = collatz_path(num) all_paths.append(path) print(f"Path for {num}: {path}") # Step 4: Plot all paths with distinct styles colors = ['green', 'magenta', 'red', 'blue', 'orange', 'purple'] # Extend this list for more numbers markers = ['o', 's', '^', 'D', 'v', '*'] plt.figure(figsize=(10, 6)) for idx, path in enumerate(all_paths): # Cycle through colors/markers if there are more numbers than predefined styles color = colors[idx % len(colors)] marker = markers[idx % len(markers)] plt.plot(path, color=color, marker=marker, mfc='pink', label=f'Number {numbers[idx]}') plt.title("3x+1 Conjecture Paths") plt.xlabel("Step Number") plt.ylabel("Value") plt.legend() plt.grid(True) plt.show()
Key Improvements:
- Modular Function: The
collatz_pathfunction handles computing the sequence for a single number, making the code reusable and easier to debug. - Dynamic Input Flow: First asks how many numbers to process, then collects each one in a loop—no hardcoded input fields.
- Independent Path Calculation: Each number's sequence is computed fully before moving to the next, ensuring accurate results.
- Clearer Visualization: Adds a legend to distinguish each number's path, grid lines for readability, and cycles through styles if there are more numbers than predefined colors/markers.
- Integer Consistency: Uses
//instead of/to keep path values as integers (avoids floating-point results like 2.0 instead of 2).
This code will let users input any number of positive integers, compute their full 3x+1 paths, and display all sequences in a single, easy-to-read plot.
内容的提问来源于stack exchange,提问作者Samed Alizade
相关产品推荐
相关产品推荐

