题目:
Here you have a flight schedule by which you need to find out whether all flights are really necessary.
For example: If from the point A to point C you can fly directly for $ 100, but you can also go through the point B (from A to B, and then from B to C) for $ 90, then connection A – C isn’t really needed. But if the price from A to C is $ 90 or less, then this connection remains on the schedule.
Input: An array of all possible connections. Each element in the array is also an array of 3 elements: the first city, second city and flight price.
Output: An array of the unnecessary flight indices.
Example:
useless_flight([[‘A’, ‘B’, 50],
[‘B’, ‘C’, 40],
[‘A’, ‘C’, 100]]) == [2]
useless_flight([[‘A’, ‘B’, 50],
[‘B’, ‘C’, 40],
[‘A’, ‘C’, 90]]) == []
链接:
https://py.checkio.org/en/mission/useless-flights/
效率不高的代码:
from typing import List
def useless_flight(schedule: List) -> List:
v = schedule
def pick(a, start, end, jihe, ss, num):
for j in a:
if (j[0] == end and j[1] == start) or (j[0] == start and j[1] == end):
num.append(j[2])
a.remove(j)
x = []
for i in range(0, len(a)-1):
for j in range(i+1, len(a)):
if a[i][0] == a[j][1]:
x.append([a[i][1], a[j][0], a[i][2]+a[j][2]])
elif a[i][1] == a[j][0]:
x.append([a[i][0], a[j][1], a[i][2]+a[j][2]])
elif a[i][1] == a[j][1]:
x.append([a[i][0], a[j][0], a[i][2]+a[j][2]])
elif a[i][0] == a[j][0]:
x.append([a[i][1], a[j][1], a[i][2]+a[j][2]])
for j in x:
if (j[0] == end and j[1] == start) or (j[0] == start and j[1] == end):
num.append(j[2])
x.remove(j)
for i in a:
for j in x:
if (j[0] == i[0] and j[1] == i[1] and j[2] >= i[2]) or (j[0] == i[1] and j[1] == i[0] and j[2] >= i[2]):
x.remove(j)
for j in x:
a.append(j)
x =[]
ss += 1
if ss < len(jihe)-1:
return pick(a, start, end, jihe, ss, num)
elif ss == len(jihe)-1:
xxx = sorted(num)
if xxx != 0:
return xxx[0]
else:
return 0
rr = []
for i in v:
ss= 0
num = []
m = []
start = i[0]
end = i[1]
for j in v:
if j!= i:
m.append(j)
jihe = []
for k in m:
if k[0] not in jihe:
jihe.append(k[0])
if k[1] not in jihe:
jihe.append(k[1])
pp = pick(m, start, end, jihe, ss, num)
if pp < i[2]:
r = v.index(i)
if r not in rr:
rr.append(r)
return rr