15,879,095 members
1.00/5 (1 vote)
See more:
Given as input a list of integers nums and an integer k, return the maximum value of each sub-list of length k
Example: nums = [4, 8, 2, 4, 10, 12]
k = 2
Output = [8, 8, 4, 10, 12]
Your task is to create a class named SlidingWindow and implement the functions get_sublist and get_max.

**Function Description:**

The get_sublist function has the following parameter(s):

int nums[n]: array of n positive integers int k: the sliding window length

returns:

int list: the maximum values of each sub-list/sliding window

The get_max function has the following parameter(s):

int nums[n]: array of n positive integers int start: the starting index of the sub-list (included) int end: the end index of the sub-list (included)

returns:

int: the maximum value from the sub-list starting from start index till the end index

Note: The input has to be taken outside the SlidingWindow class and then a call is given to the get_sublist function present inside the class to obtain the desired result

**Input Format**

The first line contains two space-separated integers n and k, the number of elements in the array and length of each sublist/subarray. The second line contains n space-separated integers which specifies the elements of the array

What I have tried:

```class SlidingWindow :

def get_max(self,arr,start,end) :
list1 = []
for i in range(start,end + 1):
list1.append(arr[i])
return max(list1)

def get_sublist(self,arr,k) :
ans = []
n = len(arr)
for i in range(n-k+1):
a = self.get_max(arr,i,i+k-1)
ans.append(a)
return ans

if __name__ == '__main__':
n , k = map(int, input().split())
#arr = [4, 8, 2, 4, 10, 12]
#k=2
arr = []
for i in range(n):
x = int(input())
arr.append(x)
obj = SlidingWindow()
res = obj.get_sublist(arr,k)
for i in res:
print(i , end=" ")```

But getting this error :
```ValueError: invalid literal for int() with base 10
```
Posted
Richard MacCutchan 10-Sep-21 11:22am
I have no idea what that code is supposed to do but I just ran it and it produced no errors. You need to explain what values you entered and what line produced the error.
Priyanka Somani 10-Sep-21 11:30am
I'm getting error with this code -
for i in range(n):
x = int(input())
arr.append(x)
bcz when I comment this and uncomment value of arr and k which I've commented above then this gives no error and correct output as well.
Richard MacCutchan 10-Sep-21 12:23pm
The error message clearly tells you that you are trying to enter an invalid number. What exactly do you type in? It would also make more sense of you added a prompt to your input statements, something like:
```x = int(input('Enter the next number: '))
```