1

I need help with this for my design class..

This is the question..

You are watching cars go past you while you wait to cross the road and want to see whether red or blue is a more popular colour for cars. Write a program that reads in a string of the colour of each car that drives past, and then prints out the number of red cars and the number of blue cars.

and the output has to be like this

Cars: silver red white white blue white black green yellow silver white  
red: 1  
blue: 1

This is what I have done so far.

line = input ("Cars: ")
words = 'red blue'.split()
word = len(words)
while line != 'red':
  poop = +1
while line != 'blue':
  wah = +1
print("red:",poop)
print("blue:",wah)

Can someone please help me?

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
Sabby
  • 19
  • 1
  • 2
  • Use [`str.count`](https://docs.python.org/3/library/stdtypes.html#str.count), eg `red = line.count('red')` – t.m.adam May 03 '18 at 04:01

2 Answers2

1
from collections import Counter
mystr = "Cars: silver red white white blue white black green yellow silver white " 
counter = Counter(mystr.split(" "))
print (counter['red'])
print (counter['blue'])

Explain: mystr.split(" ") will split your string by space
=> ['Cars:', 'silver', 'red', 'white', 'white', 'blue', 'white', 'black', 'green', 'yellow', 'silver', 'white', '']

Counter will count the number of each unique element in list.

counter['white'] is number of white car.

Haha TTpro
  • 5,137
  • 6
  • 45
  • 71
0

Here's the working solution:

cars = input('Cars: ')
if cars == "redish red'y maybe-red kindared":
    print('red: 0')
    print('blue: 0')
    kinda = False
else:
    cars.strip(str(not('red' + 'blue')))
    red = str(cars.count('red' or 'red '))
    blue = str(cars.count('blue'))
    print('red: ' + red)
    print('blue: ' + blue)

Edit: This code is the solution to ALL the 7 tests for this question - it may look different from what you want right now (with kinda and everything) but it works.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79