2

I am working on Google's OR-Tools for solving a simple VRP problem. I need to plot the solution. So, I parse print_solution() function to return a dictionary of tours. Now, I have got a string list like this

tour = [' 0 ->  14 ->  15 ->  19 ->  1 ->  13 ->  5 ->  10 ->  20 ->  3 ->  7 ->  6 ->  16 ->  4 ->  9 ->  2 ->  17 ->  11 ->  12 ->  8 ->  18 -> 0']

Could someone please help me to obtain only the integers from this list?

Navid
  • 37
  • 4

2 Answers2

1
x = tour.split('->')
int_list = [int(num.strip()) for num in x]
  • 1
    You can't call `split` on a list, so the first line of this answer will fail given the OPs definition of `tour`. Instead, `split` should be called on the single element of the provided list `tour`, like this: `x = tour[0].split('->')`. – CryptoFool Dec 29 '20 at 04:08
  • 1
    The function `int()` will strips spaces from the beginning and end of what it is passed, so the call to `strip()` is unnecessary here. The second line can be just: `int_list = [int(num) for num in x]` – CryptoFool Dec 29 '20 at 04:11
1

The first provided answer has some issues, but it does almost work. The idea behind it is sound. See the comments on the answer for an explanation of the issues I see.

I would do this differently, so that what the split results in is purely digits rather than digits with spaces on either side that then have to be dealt with separately. That is, I'd cause the spaces to been seen as being parts of the delimiters. So I'd do this instead:

import re

tour = [' 0 ->  14 ->  15 ->  19 ->  1 ->  13 -> 5 ->  10 ->  20 ->  3 ->  7 ->  6 ->  16 ->  4 ->  9 ->  2 ->  17 ->  11 ->  12 ->  8 ->  18 -> 0']

x = [int(digits) for digits in re.split(r'\s*->\s*', tour[0])]

print(x)

Result:

[0, 14, 15, 19, 1, 13, 5, 10, 20, 3, 7, 6, 16, 4, 9, 2, 17, 11, 12, 8, 18, 0]

This code will work regardless of if int() deals correctly with its argument being padded with spaces, since the spaces have already been stripped away.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44