-1

i have been working on converting a python code to java related to my research work, i have a query in Python len() object. my problem is in [::-1] as the code provided.

i have tried to do it in java by simply an incremental loop but it does not work. it gives array out of bound exception at temp_line.split('$target/')[1].

 for i in range(0, script_lines.__len__())[::-1]:
   temp_line = script_lines[i]
        if "$target/" in temp_line and "cp" in temp_line:
           Case_num = 1 + int(temp_line.split('$target/')[1].split('.txt')[0])
            return Case_num

i want to know what does [::-1] mean in the code so i can convert it to java.

Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • 5
    you want to convert code, of which you don't know what it does, to a different language? why? and how would you test it? first learn what it does, then think about converting it – Stultuske Sep 02 '19 at 06:05
  • Stultuske sir i have a code more than two thousand lines and i have have already converted it, trying to process the data, i am stuck there from so many days and cannot find the solution thats why asking here. i know what do my code do.. just some programming problems because i am a beginner in both java and python. – Sheeraz Abro Sep 02 '19 at 06:14
  • 1
    you stated you don't know what the original code does, how were you imagining to convert it (correctly)??? – Stultuske Sep 02 '19 at 06:15

2 Answers2

1

x[::-1] in Python means "all elements of the sequence x starting from the last one, ending with the first one). range(y) generates all numbers from 0 to y - 1. Thus, your line will produce indices starting with the last index of script_lines to 0.

It is not great Python code though - it creates a list where one is not needed. Using __len__ method is also frowned upon, as a plumbing method; rather use the porcelain len function. A better way to write it would have been

for i in range(len(script_lines) - 1, -1, -1):

(Start at length - 1, stop before reaching -1 while adding -1 each iteration.) But since i is actually never mentioned after fetching temp_line, the even better rewrite would be

for temp_line in reversed(script_lines):

Java doesn't have anything like reversed, so you'll have to use a loop over the indices:

for (int i = scriptLines.size() - 1; i >= 0; i--) {
Amadan
  • 191,408
  • 23
  • 240
  • 301
0

This is a python extended slice.

For example, you can extract the elements of a list that have even indexes:

>>> L = range(10)
>>> L[::2]
[0, 2, 4, 6, 8]

Negative values also work to make a copy of the same list in reverse order:

>>> L[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This also works for tuples, arrays, and strings:

>>> s='abcd'
>>> s[::2]
'ac'
>>> s[::-1]
'dcba'

See more details at https://www.pythoncentral.io/how-to-slice-listsarrays-and-tuples-in-python/

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134