mustaphos
mustaphos

Reputation: 21

Shortest path within a list in Python

Suppose i have list as the following:

a = [0,1,2,3,4,5,6,7,8,9]

And suppose i have the following requirements to choose the path:

starting_index = 3
ending_index = 7

Which means that get the items those starting from 3 to 7 which results:

first_path = [3,4,5,6,7]

Suppose that this is a circular list and this path can also be as:

second_path = [7,8,9,0,1,2,3]

In this case the following can solve the problem (shortest path):

shortest_path = a[3:7]

But for the requirements as follows:

starting_index = 1
ending_index = 8

From index 1 to 8 results:

first_path = [1,2,3,4,5,6,7,8]

But on the other hand:

second_path = [8,9,0,1]

So in this case:

shortest_path = a[1:8]

Does not solve the problem. How can i automatize this problem? Thanks...

Upvotes: 2

Views: 135

Answers (2)

Jab
Jab

Reputation: 27485

You can use the built-in slice method and slices are comparable so you can use min on them:

shortest_path = (a+a)[min(slice(start, end+1), slice(end, len(a)+start+1))]

This is equivalent to:

start_to_end = slice(start, end+1)
end_to_start = slice(end, len(a)+start+1)

if start_to_end > end_to_start:
    shortest_path = (a+a)[start_to_end]
else:
    shortest_path = (a+a)[end_to_start]

Upvotes: 1

abc
abc

Reputation: 11929

if len(a) - e_ind + s_ind > e_ind - s_ind:
    sp = a[s_ind:e_ind+1]
else:
    sp = a[e_ind:] + a[:s_ind+1]

Or more concise:

sp = a[s_ind:e_ind+1] if len(a) - e_ind + s_ind > e_ind - s_ind else a[e_ind:] + a[:s_ind+1]

Example:

>>> s_ind, e_ind = 3, 7
>>> sp
[3, 4, 5, 6, 7]

s_ind, e_ind = 1, 8
>>> sp
[8, 9, 0, 1]

Upvotes: 1

Related Questions