简体   繁体   中英

Histogram Program

I am working on a Lab program that asks to create a program that asks to print inputted scores (separated by commas) and adds an asterisk for every time the score is listed. The program I have listed is short and seems like it should work, but I am just having trouble in the sense if I am making this question too simple than what it really is. Can anyone help with a few ideas why this is not working and an idea of what to do here?

test_scores = input("Enter test scores: ").split(",")

for num in range(0,101):
    count = test_scores.count(num)
    if count > 0:
      print(num)

Completed Program:

test_scores = input("Enter test scores: ").split(",")

a_set = sorted(set(test_scores))
test_scores.sort()

for score in a_set:
    x = test_scores.count(score)
    print(score,('*'*x))

Since this is an assignment and I don't want to code your lab for you I'll outline an approach you can implement. This is the simplest way (imo) given your comment you said histogram but listed score(asterisks = num appearances) ...

If you want an actual histogram put to the OS with axes where the scores are vertically aligned with the "bars" which would be asterisks of height = num occurences then that will require additional work. So, I'll outline the approach for what you listed in your comment.

  1. Your first line is fine for getting the list of scores and splitting them into a list (assuming the user input is fine)

  2. You're iterating over 1-100 which is all possible scores. Redundant imo, why not just sort the list and then print out the number with the number of asterisks required?

Hint: sort is handy here and you can iterate and print items in a list by doing (for example)

for element in aSortedList: 
    #do something with "element"
  1. For each score you want a number of asterisks equal to the number of occurrences in the list displayed next to the score.

For strings recall you can do (string) * (num) for a string that repeats itself num times.

Hint: As you are you can get the number of occurences in the list with count . Then use (string) * (num) .

There you go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM