您可能已经看到一条横穿道路的电缆,DOT每天都会用它来计数通过该道路的车辆。它会将每次压力变化都计为轴。小型(汽车),中型(皮卡车)和大型(卡车)车辆具有不同的车轴模式,因此DOT可以区分经过的车辆种类。
编写一个将模拟此汽车计数器的程序。对于此程序,将有一个连续的字符字符串(分成10行,每行50个字符),其中“ x”代表凸点之间的空间,“ o”代表轴的“凸点”。小型车辆的模式“ oo”被任意多个x包围。中型车辆的模式“ oxo”被x包围。大型车辆将具有“ oxoxxooo”模式。为了简化操作,将不会在不同的数据行之间划分车辆。例如,以下代表2辆小型车辆,其次是2辆中型车辆,最后是一辆大型车辆:xooxxxxooxxxxoxoxxxxoxoxxxxxxxoxoxxoooxxxxxxxxxxxx
输入:
有10行数据,每行50个字符。
第1行=“ xooxxxxooxxxxoxoxxxxxxxoxoxxxxxxxoxoxxoooxxxxxxxxxxxx”
第2行=“ ooxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
第3行=“ oxoxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
第4行=“ oxoxxoooxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
第5行=“ xxxoxoxxxoooxxxxxxoxoxxoooxxxxxxxxoxoxxoooxxxxxxxxx”
line6 =“ xoxoxxoooxxxxxooxxxooxxooxxooxxxxxooxxxxooxxxxooxx”
line7 =“ oxoxxoxoxoxxoxoxxoxoxxoxoxxxxxxxoxoxxxxxoxoxxxxxoxox”
line8 =“ xooxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoo”
第9行=“ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
line10 =“ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoxoxxooo”
输出:
12个小
11中
7大
这是到目前为止,我无法打印所需的输出:
lines = [line1, line2, line3, line4, line5, line6, line7, line8, line9, line10]
for line in lines:
scount = line.count('xoox')
mcount = line.count('xoxox')
lcount = line.count('oxoxxooo')
print scount,"small"
print mcount,"medium"
print lcount,"large"
我这里有一些格式问题,输入和输出中的所有行都应以单行隔开。
答案 0 :(得分:0)
这将是正则表达式的良好应用。另外,收集模块中的Counter对象将有助于理清提示:
import re
from collections import Counter
size = {"oo":"Small", "oxo":"Medium", "oxoxxooo":"Large"}
pattern = re.compile("(oxoxxooo|oxo|oo)")
def countVehicules(bumps): return Counter(size[p] for p in pattern.findall(bumps))
lines = [line1, line2, line3, line4, line5, line6, line7, line8, line9, line10]
for vehicule,count in countVehicules(".".join(lines)).items():
print(count,vehicule)
由于这是一项家庭作业,我将让您了解其工作原理:)
[EDIT]这是不使用导入模块的更基本的实现:
lines = [line1, line2, line3, line4, line5, line6, line7, line8, line9, line10]
small = 0
medium = 0
large = 0
for line in lines:
firstAxle = 0
while firstAxle < len(line):
if line[firstAxle:].startswith("oxoxxooo"):
large += 1
firstAxle += 7
elif line[firstAxle:].startswith("oxo"):
medium += 1
firstAxle += 2
elif line[firstAxle:].startswith("oo"):
small += 1
firstAxle += 1
print(small,"small")
print(medium,"medium")
print(large,"large")