我正在考虑进行Google Hash Code,但是在实践问题上遇到了一些问题!问题是订购了许多比萨饼而没有超过限制。输入为您提供每种类型的不同数量的切片。这是c_medium.in输入文件:
4500 50
7 12 12 13 14 28 29 29 30 32 32 34 41 45 46 56 61 61 62 63 65 68 76 77 77 92 93 94 97 103 113 114 114 120 135 145 145 149 156 157 160 169 172 179 184 185 189 194 195 195
为了确定尺寸选项,我正在使用此代码:
file = open('c_medium.in','r')
raw_pizza_types = file.readline(2)
pizza_types = raw_pizza_types.split()
print(pizza_types)
max = file.readline(1)
def solution() -> None:
#pizza_types = [int(i) for i in pizza_types] # will loop through strings and convert them to ints
pass
此代码应打印出包含不同饼图上的切片数量的列表,而仅打印出['45']
。谁能帮我解决这个问题?
readline()
中的参数表示要读取的大小,而不是要读取的行数。因此,您要告诉它只读取前两个字节,即45,然后停止。
您想做的是使用命令readlines()
,默认情况下,该命令以列表的形式读取所有行。然后,您只需要处理列表中的数据即可。我会推荐一些类似的东西:
file = open('filename', 'r')
raw_pizzas = file.readlines()
slices = []
for p in raw_pizzas:
for s in p.split():
slices.append(s)
print(slices)
请注意,这意味着更多的伪代码,我尚未进行测试以确保其能够正常工作。
readline
方法的参数为size
,并且不会读取第二行,我假设这是您要执行的操作。文件句柄是迭代器,除非您seek
,否则不能返回到上一行。因此,我将按它们在文件中出现的顺序读入您的变量:
# the with statement is the pythonic way to open files
# since you don't need to remember to close them
with open('c_medium.in','r') as fh:
# read the first line to max, but max itself is a function
# so we will name it something else
maximum_slices = [int(x) for x in next(fh).split()]
# this will split the second line on any whitespace character
pizza_types = next(fh).split()
此后,您的清单理解力就足够了。我还假设maximum_slices
也应该是整数列表