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

Python中用星号展示用户输入数字的柱状图实现问题

How to Calculate Proportional Asterisks for Your Bar Chart Homework

Hey Jess, let's work through this problem step by step—you’re way closer than you think, and pop() isn’t the tool you need here (that’s for removing list elements, not calculating proportions). Let’s break down the core logic and turn it into working code:

1. The Key Scaling Formula

The main idea is to normalize every input number against the largest value in your set. The formula for how many asterisks each number gets is:

star_count = (current_number / maximum_number) * 40

Since you can’t have a fraction of an asterisk, round this result to the nearest integer (or use integer truncation if your assignment prefers that—rounding is more accurate for small values).

2. Example Walkthrough

Let’s say your input numbers are [8, 20, 32, 40]:

  • Maximum number is 40
  • 8 → (8/40)*40 = 8 asterisks
  • 20 → (20/40)*40 = 20 asterisks
  • 32 → (32/40)*40 = 32 asterisks
  • 40 → (40/40)*40 = 40 asterisks

If your input is smaller, like [5, 15, 25]:

  • Maximum is 25
  • 5 → (5/25)*40 = 8 asterisks
  • 15 → (15/25)*40 = 24 asterisks
  • 25 → 40 asterisks

3. Practical Code Implementation (Python)

Here’s a complete script that collects user input, calculates the proportional asterisks, and prints the bar chart:

# Step 1: Collect user input (split space-separated numbers into a list of integers)
user_input = input("Enter your numbers separated by spaces: ")
numbers = list(map(int, user_input.split()))

# Step 2: Handle edge case (avoid division by zero if all numbers are 0)
if max(numbers) == 0:
    print("All numbers are zero—can't generate a bar chart!")
else:
    max_num = max(numbers)
    # Step 3: Generate and print each bar
    for num in numbers:
        # Round to nearest integer for clean asterisk counts
        star_count = round((num / max_num) * 40)
        # Format the output for readability
        print(f"{num:4d} | {'*' * star_count}")

4. Why pop() Wasn’t Working

The pop() method removes elements from a list, which has nothing to do with scaling values. You just need to iterate over every number in your input list, apply the scaling formula to each, and generate the corresponding asterisks.

Give this a test run—tweak the rounding or formatting if your assignment has specific rules, but this should hit all your requirements!

内容的提问来源于stack exchange,提问作者Jess L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:02:59