试试这个,我清理了你的代码并删除了一堆错误,尽管我不完全理解。编辑:我添加了“全局”这可能是问题所在# Did you import sys?
import sys
# You don't need to pass 'strArr', what, you want to initialize it? You don't need to in python.
# I renamed your functions and variables lowercase - its python style to do that
def gas_station():
# IMPORTANT: you must first declare variables global to modify them
global tank, stations
f = open('Details.txt', 'r')
# you must first read the lines
# you don't need to loop over it and do that - readlines() returns a list, so you can assign it directly
strarr = f.readlines()
# Close your file!
# This can lead to memory leaks and make your application use more RAM (although python typically does this for you, you can't rely on that all the time.)
f.close()
amount, tank = int(strarr[0]), 0
stations = [amount.split(":") for i in (strarr[1:] + strarr[1:-1])]
# I don't understand "start". It was never initialized and I assume its just strarr[0]
# range(start, start+1) is the same as the tuple(start, start+1), you do not need range
for curr in (strarr[0], strarr[1]):
tank = tank + int(stations[curr][0]) - int(stations[curr][1])
if tank < 0:
# Don't do that! It's ugly and against PEP 8: https://www.python.org/dev/peps/pep-0008/
# Also don't exit - raise an exception
raise ValueError('Tank is less than 0')
elif tank >= 0:
return strarr[0] + 1
else:
tank = 0
# False is better and awesomer than just 'not', you can check it just like you can with 'not' and its more pythonic too.
return False
PEP 8非常重要-它可以让其他开发人员看到非PEP8格式的代码,就像Java中用小写字母命名变量一样,只是在python中它不是传统,而是规律。在
您还可以更改全局变量,而不是运行函数来返回新结果并将其分配给变量。在
我的代码:
^{pr2}$
我假设输入中没有新行。在
我不明白为什么你需要一个链表,因为它是一个复杂的CS结构,但是如果你指的是字典,那么就简单地做如下操作:dictionary_version = dict(nested_seperated)
# Output: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}