所以我正在研究一种愚蠢的小算法 - 其中的一点非常沉闷。所有我想知道的是为什么我写这封信" D"连接到终端的输出。
当答案是1时,它会让我回到1D。当答案是2时,它会吐出2D等等。为什么?
我不认为它与代码有很大关系。如果您愿意,代码如下。这可能与我结束输入流的方式有关,即按Ctrl + D(mac)。它没有给我1 ^ D,它给了我1D。为什么呢?
if __name__ == '__main__':
input = sys.stdin.read()
n, *data = map(int, input.split())
segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
points = optimal_points(segments)
print(int(len(points)))
for p in points:
print(p, end=' ')
它基本上说,等等等等,从输入流/终端获取一个数字列表,如下所示:
3
1 3
2 5
3 6
并执行此操作:
def is_between(num_to_check, start, end):
return num_to_check >= start and num_to_check <= end
def optimal_points(segments):
end_first_segements = sorted(segments, key=attrgetter('end'))
count = 1
i = 1
current_end = end_first_segements[i -1 ].end
next_seg = end_first_segements[i]
end_points=[current_end]
while i <len(end_first_segements):
s = next_seg.start
e = next_seg.end
if(is_between(current_end, s, e)):
try:
i += 1
next_seg = end_first_segements[i]
except IndexError:
break;
else:
try:
count +=1
end_points.append(next_seg.end)
next_seg = end_first_segements[i+1]
current_end = next_seg.end
except IndexError:
break;
return end_points
请注意,代码中没有任何内容可以说明,&#34;嘿,您应该将字母D无意地附加到输出中&#34;。
我还在其他一些我已经完成的小程序中看到了这一点。所以我认为它与终端相关,我写的任何代码。想法?
整个.py文件:
# Uses python3
import sys
from collections import namedtuple
from operator import attrgetter
Segment = namedtuple('Segment', 'start end')
def is_between(num_to_check, start, end):
return num_to_check >= start and num_to_check <= end
def optimal_points(segments):
end_first_segements = sorted(segments, key=attrgetter('end'))
count = 1
i = 1
current_end = end_first_segements[i -1 ].end
next_seg = end_first_segements[i]
end_points=[current_end]
while i <len(end_first_segements):
s = next_seg.start
e = next_seg.end
if(is_between(current_end, s, e)):
try:
i += 1
next_seg = end_first_segements[i]
except IndexError:
break;
else:
try:
count +=1
end_points.append(next_seg.end)
next_seg = end_first_segements[i+1]
current_end = next_seg.end
except IndexError:
break;
return end_points
if __name__ == '__main__':
input = sys.stdin.read()
n, *data = map(int, input.split())
segments = list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2])))
points = optimal_points(segments)
print(int(len(points)))
for p in points:
print(p, end=' ')
答案 0 :(得分:0)
我无法完全重现您的确切问题,但我确实看到一些奇怪的地方,最后一行输出以linux中的%符号结尾。
所以重现这种行为的最小工作示例就是:
print('1 2', end=' ')
如果我在程序末尾添加一个空的print语句,则会删除行为,即在最后添加print()
。