Python 3: Getting TypeError: fragments must be integers ... But I believe

I am trying to write a function "average" that takes the average 3 digits of odd numbers or the average 4 digits of even numbers. If the number is less than 5 digits, it simply returns an integer. Here is my work:

def middle(x): mystring=str(x) length=len(mystring) if len(mystring)<=5: return(x) elif len(mystring)%2==0: return (mystring[((length/2)-1):((length/2)+3)]) else: return (mystring[(length//2):((length//2)+3)]) middle (1234567890) 

I keep getting "error like: slice indices must be integer or not or have parameter _index_and_method", and I don’t understand.

+4
source share
2 answers

You are using Python 3, I am sure. [And you - I noticed this tag for the second time.] length/2 will be float:

  return (mystring[((length/2)-1):((length/2)+3)]) 

use length//2 throughout.

Note that this will happen even if length is:

 >>> s = 'abcd' >>> len(s) 4 >>> len(s)/2 2.0 >>> s[len(s)/2:] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: slice indices must be integers or None or have an __index__ method >>> s[len(s)//2:] 'cd' 
+13
source

The // operator only returns int when the numerator is int, and it still returns float when the numerator is float.

 assert type(2//2) == int assert type(2.//2) == float 

To overcome this limitation in slices, you can use the following function:

 def intslice(*args, **kwargs): '''Return a slice object that has integer boundaries. Example: np.arange(10)[intslice(10/10,10/2)] ''' args = [int(arg) for arg in args] kwargs = {key: int(arg) for key, arg in kwargs.items()} return slice(*args, **kwargs) 

Now intslice(10/10,10/2) returns slice(1,5)

0
source

Source: https://habr.com/ru/post/1439717/


All Articles