Home > Mobile >  Perfect Squares Python
Perfect Squares Python

Time:11-20

I have been trying to write a code that is suppose to return perfect squares using object oriented programming from given values from a instance variable. Below is what I have written and still I was was not able to get perfect squares. Below is what I have written

# Write a class, PerfectSquares, that implements an iterator<br>
# This will return 1, 4, 9, 25, 36, 49, etc.

class PerfectSquares:
    def __init__(self, x):
        self.x = x
        
    def get_values(self):
        return self.x**2

values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in values:
    getter = values.get_values(i)
    print(getter)

CodePudding user response:

You should implement both __iter__ and __next__ methods.

Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__ and __next__.

  • The iter returns the iterator object and is implicitly called at the start of loops.

  • The next() method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating.

A good resource for iterators: https://www.ibm.com/developerworks/library/l-pycon/

class PerfectSquares:
    """Class to implement an iterator
    of perfect squares"""

    def __init__(self, k):
        self.k = k
        self.n = 0

    def __iter__(self):
        return self

    def __next__(self):
        self.n  = 1
        if self.n <= self.k:
            result = self.n ** 2
            return result
        else:
            raise StopIteration
v = PerfectSquares(10)
for i in v:
    print(i)

This will output:

1
4
9
16
25
36
49
64
81
100

CodePudding user response:

  1. First, You have to create an Object of the class and pass value. (obj = PerfectSquares(i))

  2. Second, Call the get_values method with that obj without passing any arguments, because get_values is not taking any.

  3. Third, print the variable.

Refer the code below:

class PerfectSquares:
    def __init__(self, x): # this constructor takes an argument 'x'.
        self.x = x
        
    def get_values(self): # this function takes no argument.
        return self.x**2

values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in values:
    obj = PerfectSquares(i) # 'i' variable is passed to 'x' in class.
    getter = obj.get_values() # returns the square of 'i' ('x' in class).
    print(getter)

Output:

1
4
9
16
25
36
49
64
81
100
  • Related