gpt4 book ai didi

python - 解决方案适用于样本数据,但在线判断给出错误?

转载 作者:太空狗 更新时间:2023-10-29 20:51:35 26 4
gpt4 key购买 nike

这是我要解决的问题:

B: The Foxen's Treasure

There are N (1 ≤ N ≤ 4) Foxen guarding a certain valuable treasure, which you'd love to get your hands on. The problem is, the Foxen certainly aren't about to allow that - at least, not while they're awake.

Fortunately, through careful observation, you've seen that each Fox has a regular sleep cycle. In particular, the ith Fox stays awake for Ai (1 ≤ Ai ≤ 23) hours, then sleeps for Si (1 ≤ Si ≤ 23) hours, repeating this pattern indefinitely (2 ≤ Ai + Si ≤ 24). At the start of your treasure-nabbing attempt, the ith Fox is exactly Oi (0 ≤ Oi < Ai + Si) hours into its cycle.

There are T (1 ≤ T ≤ 20) scenarios as described above. For each one, you'd like to determine how soon all of the Foxen will be simultaneously asleep, allowing you to grab their treasure, or if this will simply never happen.

Input

Line 1: 1 integer, T
For each scenario:
Line 1: 1 integer, N
Next N lines: 3 integers, Ai, Si, and Oi, for i = 1..N

Output

For each scenario:
Line 1: 1 integer, the minimum number of hours after the start to
wait until all of the Foxen are asleep during the same hour. If this
will never happen, output the string "Foxen are too powerful" (without
quotes) instead.

Sample Input

2
2
2 1 2
2 2 1
3
1 1 0
1 1 0
1 1 1

Sample Output

6
Foxen are too powerful

当我输入给定的示例案例并获得预期的输出时,我的解决方案按预期工作。但是当我将代码提交给在线判断时,它给出了截断错误。现在没有错误的详细信息,因此很难找到问题所在。

以下是我目前使用的解决方案:

# ai is awake hours
# si is sleep hours.
# ai + si <= 24.

# False == sleep. True == awake.

datasets = int(raw_input());
foxen = [];
number_of_foxen = 0;
foxes = [];

class fox:
def __init__(self, a, s, i):
self.awake = a;
self.sleep = s;
self.current = i;
awake = 0;
sleep = 0;
current = 0;

def next(self):
if ( self.sleep + self.awake-1 > self.current ) :
self.current = self.current+1;
else:
self.current = 0;
return self.current;

def check(self):
if(self.current>=self.awake):
return False;
return True;

def printdata(self):
print "awake="+str(self.awake)+" sleep="+str(self.sleep)+" current="+str(self.current);
#return "awake="+str(self.awake)+" sleep="+str(self.sleep)+" current="+str(self.current);


for i in range(0, datasets):
number_of_foxen = int(raw_input());

for j in range(0, number_of_foxen):
foxen.append(raw_input());
x = foxen[j].split();
a = fox(int(x[0]), int(x[1]), int(x[2]));
foxes.append(a);

solution = False;
for j in range(0, 48):
#print "hour number = " + str(j);

#for k in range(0, len(foxes)):
#print "fox number="+ str(k)+" "+ foxes[k].printdata()+str(foxes[k].check());

count = 0 ;
for k in range(0, len(foxes)):
if(foxes[k].check()==False):
count+=1;
#print "count = "+str(count);
#print len(foxes);
if( (int(count) == int(len(foxes))) and (solution == False) ):
#print "this runs now *************";
solution = True;
number = j;

for k in range(0, len(foxes)):
foxes[k].next();

if(solution==True):
print number;
else:
print "Foxen are too powerful";

#print "Foxen are too powerful";
foxen = [];
number_of_foxen = 0;
foxes = [];

最佳答案

您的代码最大的问题是它不可读。事实上,它看起来像是在对 Python 的优势一无所知的情况下编写的。这是我的建议:

#!/usr/bin/env python3

"""
The Foxen's Treasure puzzle from http://wcipeg.com/problem/acmtryouts1b
"""

from sys import stdin
from itertools import cycle

from euclid import lcm

debug = True # set to False before submission to mechanical judge

class Fox:
"""A Fox cointains its defining integers and other derived
bindings such as its cycle and schedule."""
def __init__(self, trio):
(self.awake_count, self.sleep_count, self.skip_count) = trio
self.cycle = 'a' * self.awake_count + 's' * self.sleep_count
self.schedule = cycle(self.cycle)
if debug: print('<Fox: {}> cycle {}'.format(trio, self.cycle))

# handle skips by discarding the first elements
for _ in range(self.skip_count):
next(self.schedule)


def find_all_sleeping(foxes):
"""Return an hour number if all foxes are sleeping at that hour."""
# only examine the LCM of all fox periods. If not there it will never be.
lcm_period = 1
for fox in foxes:
lcm_period = lcm(lcm_period, len(fox.cycle))

for hour in range(lcm_period):
states = [next(fox.schedule) for fox in foxes]
if debug: print('{:2d} {}'.format(hour, ' '.join(states)))
if 'a' not in states:
return hour
return None


def read_trials(fp):
"""Reads the entire input at once. Returns a list of trials.
Each trial is a list of Fox."""
trials = list()
trial_count = int(fp.readline())
for trial in range(trial_count):
if debug: print('--Read trial {}'.format(trial))
foxes = list()
fox_count = int(fp.readline())
for _ in range(fox_count):
fox = Fox([int(x) for x in fp.readline().split()])
foxes.append(fox)
trials.append(foxes)
return trials


for trial, foxes in enumerate(read_trials(stdin)):
if debug: print('--Run trial {}'.format(trial))
hour = find_all_sleeping(foxes)
if hour is None:
print('Foxen are too powerful')
else:
print(hour)

我怀疑第一个问题是它看起来比 OP 长得多;的确如此,但是如果你去掉显示事情发生的调试代码,以及解释它为什么做事的文档字符串,它实际上比 OP 短了几行。

如果不进行大量研究,OP 的主循环太长难以理解,而且一大堆糟糕的变量名使理解变得更加困难。相比之下,这里有些地方为值赋予名称只是为了让代码更明确地说明输入行的含义。你会发现一些

for _ in range(trial)

表示没有使用循环值。在处理固定格式输入时,这是一个常见的习惯用法。

Fox 表示将内部工作原理保留在问题空间中。如练习页所述,将事物视为序列之间的并发更有意义:

--Read trial 0
<Fox: [2, 1, 2]> cycle aas
<Fox: [2, 2, 1]> cycle aass

此处未显示偏移量skip_count,但在试运行中已清楚。

来自数据文件的输入全部保存在 read_trials() 中,而不是分散在代码中。这将困惑限制在一个地方,而不是通过代码分发。我们从拼图说明中知道数据文件不会大到需要关心的程度。 read_trials(fp) 还接受一个类文件对象,允许它从实际文件、StringIO 缓冲区或标准输入中读取。

一旦 Fox 计划生成器被初始化,itertools.cycle 将无休止地提供序列中的下一个字母;它为您完成环绕。

值得注意的是,主要数据结构 trials 是一个普通的旧列表,因为它不需要任何其他东西。

我已经有点厌倦了用更糟糕的代码来回答糟糕的代码。当然,这可以被认为远远超过仅输出重要的电子法官的需求。相反,我仍然对 (solution == False) 这样的位感到困惑,这是一个 42 行长的主循环,在文件的顶部和底部之间拆分,变量如 ij 没有传达任何意图,False == awake 的内存负担(或者我把它们搞混了吗?),死代码,无操作代码, `range(0, n) 和一大堆神奇的数字。

当然,您可以像代码一样编写代码并不重要,但如果您正在自学编写代码,那么好好练习是件好事。是的,您可能永远不会再看这段代码,但如果您现在不打算学习它,那么什么时候可以?

如果你觉得导入 lcm() 是作弊,没有理由再写一遍,所以我引用了一个自制程序包,其中相关行是:

def gcd(a, b):
"""Return the Greatest Common Divisor of a and b."""
while b:
a, b = b, a % b
return a

def lcm(a, b):
"""Return the Least Common Multiple of a and b."""
return abs(a * b) // gcd(a, b)

关于python - 解决方案适用于样本数据,但在线判断给出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32284449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com