'How overload < and [] operatot on Python
Recently OOP has moved from C++ to Python. I know the basics of the language more or less, but I had to work with OOP for the first time.
The task is as follows: "Create a class - real numbers, describe a field: a value of a real type. Define a constructor, functions for changing the field and getting its value, functions for dividing a number into integer and fractional parts, forming a real number from two integers corresponding to the integer and fractional parts ( in fixed-point format).Overload operations < (comparison of real numbers by the value of the integer part), [] (selection of the fractional part of the number).Sort the array of instances of the class of real numbers in descending order of the value of the integer part, programmatically check whether the numbers in the array will be ordered if fractional parts are taken into account.
Please, help me with the following points:
1)Overload operations < (comparison of real numbers by the value of the integer part), [] (selection of the fractional part of the number).
2)Sort the array of instances of the class of real numbers in descending order of the value of the integer part, programmatically check whether the numbers in the array will be ordered if fractional parts are taken into account
Thank you all in advance for your help.
Here is the code:
class Float(object):
def __init__(self, arg): #constructor
self.__arg = arg
self.a = arg
@property #getter
def getarg(self):
return self.__arg
def display_info(self): #output results
print(f"\nNumber: {self.__arg}")
def rozdel(self): #division into integer and fractional parts
self.a = int(self.__arg)
self.b = self.__arg - int(self.__arg)
print(f"\nInteger part: {self.a}, Fractional part: {self.b}")
self.c = self.a + self.b
print(f"\nПочаткове число: {self.c}")
def __lt__(self, other): #overloading <
return self.a < other.a
#------------------------------------------------------------------
def SortArr(arr):
for i in range(len(arr)):
min = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min]:
min = j
arr[i], arr[min] = arr[min], arr[i]
#------------------------------------------------------------------
if __name__ == '__main__':
size = int(input("Enter count of elements: "))
j = 0
arr = []
for i in range(size):
j += 1
print("---------------------")
print("Variant %d" %(j))
a = float(input("Enter rreal namber: "))
arr.append(Float(a))
arr[i].display_info()
arr[i].rozdel()
SortArr(arr)
print("\n-*-*-*-*-*-*-*-*-*-*-*-*-")
print("After sorting:")
for i in range(size):
print(str(arr[i]))
print("-*-*-*-*-*-*-*-*-*-*-*-*-\n")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|