1

I've seen other more in-depth solutions to this but as I'm still learning python I want to understand my mistakes.

My code as of now is:

carlist = []
colour = []
while colour != '':
  colour = input("Car: ")
  if colour != '':
    carlist.append(colour)
carlist.sort()
for i in carlist:
  print("Cars that are", i + ":", carlist.count(i))

and outputs:

Car: red
Car: white
Car: blue
Car: green
Car: white
Car: silver
Car:
Cars that are blue: 1
Cars that are green: 1
Cars that are red: 1
Cars that are silver: 1
Cars that are white: 2
Cars that are white: 2

I understand the basics of the problem that I have 2 'white' in my dictionary but where/ how can I fix this?

(also I understand I should format all answers lowercase)

splatters_
  • 13
  • 2
  • you can create a dictionary for counting. Or you can create a `set` of `carlist[]` which remove the duplicates and than run the for loop. Note In 2nd method It is not ordered. or to make ordered after set you can `sort()` as you done. – Yash Mehta Apr 06 '23 at 04:47
  • What are you trying to fix? Duplicate output? – Unmitigated Apr 06 '23 at 04:49

2 Answers2

0

Code: By dictionary()

carlist=[]
colour=[]
while colour != '':
  colour = input("Car: ")
  if colour != '':
    carlist.append(colour)

#Creating a dictionary
color_counts = {}
for color in carlist:
    color_counts[color]=color_counts.get(color,0)+1
  
for color,count in sorted(color_counts.items()): #Sorted dictionary on the basis of key.
  print("Cars that are", color + ":", count)

Code: By set()

carlist=[]
colour=[]
while colour != '':
  colour = input("Car: ")
  if colour != '':
    carlist.append(colour)

for car in sorted(set(carlist)): #firstly set() will remove duplicates and than it will sort.
  print("Cars that are", car + ":", carlist.count(car))

Output: [Both Codes]

Car: red
Car: white
Car: blue
Car: green
Car: white
Car: silver
Car: 
Cars that are blue: 1
Cars that are green: 1
Cars that are red: 1
Cars that are silver: 1
Cars that are white: 2
Yash Mehta
  • 2,025
  • 3
  • 9
  • 20
0

You could use collections.Counter to get the frequency of each color, then iterate over all the entries in the Counter for printing.

from collections import Counter
# use Counter(sorted(carlist)) if you want the output to be sorted order
for color, count in Counter(carlist).items():
    print(f'Cars that are {color}: {count}')
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • [See it working here](https://tio.run/##VY2xDsIwDET3foW3NFLFwlaJqZ@BGEJxqKUkrhwXhFC/PaQVDNxyJz/deX7pxOlYyugkUFY4wdkI3kwH5jmR4hauYdn9Lojpj2QKDxRzabxwhJFDwFGJUwaKM4vCwEtSlMazbJilq1ZPQOnH2u9re6ijMbe2b6BqFkraejM4yaCTU3CC8N5H1n4Ltb0aW8oH) – Unmitigated Apr 06 '23 at 05:04