【问题标题】:One car, Two car, Red car, Blue car in Grok [duplicate]Grok中的一辆车,两辆汽车,红色汽车,蓝色汽车[重复]
【发布时间】:2018-10-13 06:12:04
【问题描述】:

我的设计课需要这方面的帮助..

这是问题..

当您等待过马路时,您正在看着从您身边经过的汽车,想看看红色还是蓝色是更受欢迎的汽车颜色。编写一个程序,读取经过的每辆汽车的颜色字符串,然后打印出红色汽车的数量和蓝色汽车的数量。

而且输出必须是这样的

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

这是我目前所做的。

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)

有人可以帮帮我吗?

【问题讨论】:

  • 使用str.count,例如red = line.count('red')

标签: python


【解决方案1】:

这是有效的解决方案:

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)

编辑:此代码是该问题的所有 7 个测试的解决方案 - 它可能看起来与您现在想要的不同(使用 kinda 和所有内容)但它可以工作。

【讨论】:

    【解决方案2】:
    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'])
    

    说明: mystr.split(" ") 将按空格分割您的字符串
    => ['Cars:', 'silver', 'red', 'white', 'white', 'blue', 'white', 'black', 'green', 'yellow', 'silver', 'white', '']

    Counter 将计算列表中每个唯一元素的数量。

    counter['white']是白色车的号码。

    【讨论】:

    • 这个答案完全正确。投反对票的人可以与我们分享他/她这样做的原因。
    • @GaneshK 因为我没有解释(我想是这样)。在我编辑我的答案之前,他投了反对票。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多