CodeMonkey - 1 year ago 125

Python Question

I'm new to Python, thus the question,

I'm trying to slice an array and find the sub array of the longest length that is less than a particular value. This is my code,

`def main():`

a = [1, 2, 3]

print(maxLength(a, 3))

def maxLength(a, k):

max = 0

currTotal = 0

for i in enumerate(a):

for j in enumerate(a):

temp = a[i:i+j:1]

currTotal += a[j]

if currTotal < k:

if len(temp) > max:

max = len(temp)

currTotal = 0

return max

if __name__ == '__main__':

main()

I'm getting the following error,

`TypeError: slice indices must be integers or None or have an __index__ method`

I'm not sure what am I doing wrong with the Slice, any help appreciated.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

When you use `enumerate`

, it gives you a sequence of tuples.

```
for i,x in enumerate(mylist):
# i is the index
# x is the item at that index
```

You are assigning that tuple to one variable:

```
for i in enumerate(a):
# i is a tuple of (index, item)
```

And then you are trying to use `i`

like it is an integer. It's not an integer.

If you want just an integer, use:

```
for i in range(len(a)):
for j in range(len(a)):
...
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**