Python data structures and algorithms-object-oriented

Source: Internet
Author: User
Tags gcd greatest common divisor

As already mentioned, Python is an object-oriented programming language. The most important feature of an object-oriented programming language is that it allows programmers to create classes to build data models to solve problems.

We have previously used the logic provided by the abstract data type to describe the data object (its state) and its functions (its methods). By building classes to implement abstract data types, a programmer can take advantage of abstract processing while providing detailed, realistic information to solve the problem. When we want to implement an abstract data type, we will build a new class.

This article address: http://www.cnblogs.com/archimedes/p/python-datastruct-algorithm-class.html, reprint please indicate source address.

A fractional class

Here is a very common example of a user-defined class that implements an abstract data type: Fraction (fractional). We already know that Python provides us with a large number of classes. There are a number of data objects that can be properly built to help us build a fraction type.

A score such as 3/5 contains two parts . A molecule, which can be any integer. The denominator, which can be any integer other than 0.

Fractionthe method of the class should allow the object to be Fraction evaluated like other values. We need to be able to perform fractions between the addition, subtraction, multiplication, and subtraction operations. Further, all methods should return the simplest fraction.

In Python, we define a class name and some methods, similar to defining a function, for example,

class Fraction:    # The methods go here

Provides a framework for defining a method. The first method is the constructor that all classes provide. The constructor defines how the class is created. To create 分数对象 , we need to provide two parts of the data: numerator and denominator. In Python, the constructor is surrounded with __init__ (two underscores init ), as follows:

Listing 2

class Fraction:     def __init__ (self,top,bottom):         = top        = Bottom

Notice that the parameter list contains three parameters: ( self , top , bottom ). self is a special parameter that refers to the object itself. It is usually used as the first parameter; however, it never passes a value at the time of the call. As already mentioned, the score consists of two parts (numerator and denominator). Mark is defined in the constructor as an fraction object that has an num internal data object called. Similarly, it self.den is a similar purpose.

To implement Fraction a class, we need to call the constructor. Then pass the parameter through the class name (notice that we never call directly __init__ ). For example:

Myfraction = fraction (3,5)

Creates a fractional object that myfraction represents the score 3/5 .


the next thing to do is to give the abstract data type implementation method. First, realize that when we want to output a Fraction object.

>>> MYF = fraction (3,5)print(MYF)<__main__. Fraction instance at 0x409b1acc>

fractionObject, myf and does not know how to respond to the output operation. The print function requires the object to be converted to an output string format in order to output. The only option myf must be to display the variable's actual address reference (its own address). That's not what we want.

There are two ways to solve the problem. One is to define a show method called, which can Fraction print an object as a string. We can achieve this as shown in Listing 3 . If we were to create the object as we said earlier, Fraction we could let it output itself, in other words, print itself according to The appropriate format. Unfortunately, this usually does not work. To make the output work, we must tell Fraction the class how to convert itself to a string format.

Listing 3

def Show (self):      Print (Self.num,"/", Self.den)>>> MYF = fraction (3,5)>>> myf.show () 3/5 Print (MYF) <__main__. Fraction instance at 0x40bce9ac>

In Python, all classes provide, but are not, standard methods that are applicable. One of these __str__ is a method of converting an object to a string. The default implementation of this method is to return the address of the class instance in string format. We have to provide a "better" implementation for this approach. We say this new method overloads the front, Or redefine the behavior of the method.

To achieve this, we simply define a named __str__ method and give implementations such as Listing 4. This definition does not require additional information in addition to the use of special parameters self以外 . Note the different implementations in the function.

Listing 4

def __str__(self):returnSTR (self.num) +"/"+Str (self.den)>>> MYF = fraction (3,5)>>>Print(MYF)3/5>>>Print("I ate", MYF,"Of the pizza") I ate3/5Of the pizza>>> MYF.__str__()'3/5'>>>Str (MYF)'3/5'>>>

We can Fraction cover many other methods for our new class. Some of the most important are some basic arithmetic operations. We can create two kinds of Fraction objects and add them together using the "+" symbol. At this point, if we add two fractions, we get:

>>> f1 = fraction (1,4)>>> F2 = fraction (all)>>> f1+f2Traceback ( Most recent call last):  ' <pyshell#173> ', line 1, in-toplevel-    f1+f2typeerror: Unsupported operand type (s) for +:          ' instance ' and ' instance '

If you look closely at the error message, you will notice that the "+" operator does not understand the Fraction operation.

We can do this by giving Fraction the class an overloaded addition function. In Python, this method __add__ is called two parameters at a time. The first argument, self the second argument, is the other operand. For example,

F1. __add__ (F2)

When Fraction f1 add Fraction f2 . Can be written in the form of a standard: f1+f2 .

Two fractions must have the same denominator to add directly. The simplest way to make them the same denominator is-pass:, specifically implemented as Listing 5. The addition function returns a new Fraction object.

Listing 5

def __add__ (self,otherfraction):      = Self.num * Otherfraction.den + self.den*otherfraction.num     = Self.den * otherfraction.den      return Fraction (Newnum,newden)
>>> f1=fraction (1,4)>>> f2=fraction (all)>>> f3=f1+F2 Print (F3) 6/8>>>

The addition function above seems to achieve what we expect, but it can be more perfect. Note that 6/8 is the correct result, but it is not presented in the form of "minimalist". The best expression is 3/4. In order to make our results the simplest form, We need an auxiliary function to simplify fractions. This function can be used to find out greatest common divisor, or called GCD. The goal of simplifying fractions can be achieved by greatest common divisor of numerator and denominator.

Calculation greatest common divisor most famous algorithm to number Euclid algorithm, the principle I do not specify in detail, very simple. The implementation is as follows:

 >>> def   gcd (m, N):  while  m% n!= 0:OLDM  = M OLDN  /span>= N m  = oldn n  = oldm% oldn  return   n  >>> print  gcd (10)  10  

So that we can simplify any score, the code is as follows: (Listing 6).

Listing 6

def __add__ (self,otherfraction):     = Self.num*otherfraction.den + self.den*otherfraction.num    = Self.den * Otherfraction.den    = gcd (newnum,newden)    return fraction (Newnum//common,newden//common)
>>> f1=fraction (1,4)>>> f2=fraction (all)>>> f3=f1+f2  Print(F3)3/4

Our Fraction object now has two very important methods, as shown in. Some of the new ways to improve our instance classes Fraction are to allow two fractions to be compared. If we have two Fraction objects, f1 and f2 . f1==f2 will get True if they mean To the same object. Even though the numerator denominator is the same, the conditions that are not satisfied will remain unequal. This is known as shallow equality (e.g.).

We can create deep equality (such as) – judged by value equality, unlike references – by overriding __eq__ methods. __eq__is another standard method that exists in all classes. __eq__ The method compares two objects when the value is equal and returns True otherwise False .

In the Fraction class, we implemented a __eq__ method to compare fractions by a conventional comparison method (see Listing 7). It's worth noting that there are other ways to override this. For example, the __le__ method provides less than equals functionality.

Listing 7

def __eq__ (self, Other):     = Self.num * other.den    = other.num * self.den    return firstnum = = Secondnum

The Fraction code for the complete class is as follows:

defgcd (m,n): whilem%n! =0:OLDM=m OLDN=N M=oldn N= oldm%oldnreturnNclassFraction:def __init__(self,top,bottom): Self.num=Top Self.den=Bottomdef __str__(self):returnSTR (self.num) +"/"+Str (self.den)defShow (self):Print(Self.num,"/", Self.den)def __add__(self,otherfraction): Newnum= Self.num*otherfraction.den +Self.den*Otherfraction.num Newden= Self.den *Otherfraction.den Common=gcd (Newnum,newden)returnFraction (newnum//common,newden//Common)def __eq__(self, Other): Firstnum= Self.num *Other.den Secondnum= Other.num *Self.denreturnFirstnum = =secondnumx= Fraction () y= Fraction (2,3)Print(x+y)Print(x = = y)

Operation Result:

7/6
False

Python data structures and algorithms-object-oriented

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.