Home > Back-end >  Data Structure is returning None type
Data Structure is returning None type

Time:07-18

I am trying to find the minimum and maximum from an array. I have first defined a data structure which will store the minimum and maximum.

class pair:
  def __init__(self):
    self.min = 0
    self.max= 0

Here is the UDF function:

def getminmax(arr: list, n: int) -> pair:
  minmax = pair()

  #if there's only one element return it as the min max
  if n == 1:
    minmax.min = arr[0] 
    minmax.max = arr[0]

  #if there's more than one element initialize minmax
  if arr[0] > arr[1]:
    minmax.min = arr[1]
    minmax.max = arr[0]

  else:
    minmax.min = arr[0]
    minmax.max = arr[1]

#updating the min & max values through iterations

  for i in range(2, n):
    if arr[i] > minmax.max:
      minmax.max = arr[i]
    
    elif arr[i] < minmax.min:
      minmax.min = arr[i]

Upon running the code, the minmax obtained is of none type and there is a AttributeError

arr = [1000, 11, 445, 1, 330, 3000]
arr_size = 6
minmax = getminmax(arr, arr_size)
print('Minimum', minmax.min)

Error:

AttributeError                            Traceback (most recent call last)
<ipython-input-13-3364680840b5> in <module>()
----> 1 print('Minimum', minmax.min)

AttributeError: 'NoneType' object has no attribute 'min'

The code seems right to me in the the UDF,I believe the problem with the code has to be in the class pair. Please help me out here as I have just started with Data Structures. GfG

CodePudding user response:

You need to return your variable minmax inside your function:

return minmax

Example:

def getminmax(arr: list, n: int) -> pair:
  minmax = pair()

  #if there's only one element return it as the min max
  if n == 1:
    minmax.min = arr[0] 
    minmax.max = arr[0]

  #if there's more than one element initialize minmax
  if arr[0] > arr[1]:
    minmax.min = arr[1]
    minmax.max = arr[0]

  else:
    minmax.min = arr[0]
    minmax.max = arr[1]

#updating the min & max values through iterations

  for i in range(2, n):
    if arr[i] > minmax.max:
      minmax.max = arr[i]
    
    elif arr[i] < minmax.min:
      minmax.min = arr[i]

  return minmax

Take a look: enter image description here

  • Related