0

Thanks in advance. I have a string:

A = 'asdfghjklmn'

How can I get a substring having a maximum length which is a multiple of three?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • You must elaborate what "multiple of three" means. Some examples would be useful. – Adam Matan Oct 14 '09 at 16:56
  • the question is rather vague. Are you looking for a substring that's as long as possible while satisfying the restraint or simply any substring which is a multiple of 3? – AlbertoPL Oct 14 '09 at 16:57

5 Answers5

4

You can use slice notation and integer arithmetic.

>>> a = 'asdfghjklmn'
>>> a[:len(a)//3*3]
'asdfghjkl'   
>>> len(a)
11
>>> len(a[:len(a)//3*3])
9

In general, n//k*k will yield the largest multiple of k less than or equal to n.

Community
  • 1
  • 1
Stephan202
  • 59,965
  • 13
  • 127
  • 133
1

It seems like you're looking for something like this:

>>> A = 'asdfghjklmn'
>>> mult, _ = divmod(len(A), 3)
>>> A[:mult*3]
'asdfghjkl'

here resulting string will have length which is multiple of three and it will be the longest possible substring of A with such length.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
1

Yet another example:

>>> A = '12345678'
>>> A[:len(A) - len(A)%3]
'123456'
>>> 
Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
0

Is this what you want?

A = 'asdfghjklmn'
A[0:(len(A)/3)*3]
'asdfghjkl'
Lance Rushing
  • 7,540
  • 4
  • 29
  • 34
  • does not run on python3: Traceback (most recent call last): File "", line 1, in TypeError: slice indices must be integers or None or have an index method. You should have used floor division (just as Stephan202 did). See http://python.org/dev/peps/pep-0238 – Oren S Oct 14 '09 at 17:33
0

With the foreword that it will never be as efficient as the ones that actually use math to find the longest multiple-of-3-substring, here's a way to do it using regular expressions:

>>> re.findall("^(?:.{3})*", "asdfghjklmn")[0]
'asdfghjkl'

Changing the 3 quantifier will allow you to get different multiples.

Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398