Python Forum
Help interpreting code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help interpreting code
#1
I'm trying to understand the following code that sets up the three term recursion ui+1=a1u1+a0ui-1 as a class:

class Recursion3Term:
    def __init__ (self , a0 , a1 , u0 , u1 ):
        self.coeff = [a1 , a0]
        self.initial = [u1 , u0] 
    def __iter__ ( self ): 
        u1,u0 = self.initial
        yield u0
        yield u1 
        a1,a0=self.coeff
        while True: 
            u1 , u0 = a1*u1 + a0*u0 , u1 
            yield u1 
    def __getitem__ (self,k):
        for i, r in enumerate (self):
            if i == k:
                return r
I would deeply appreciate a short explanation about line 5 to 16. For example in the iterable method, why are the different yield statements necessary? What does the while-loop do? What is r?
Reply
#2
The first two yields provide the first two values in the sequence: these are provided when the instance is created, and are not calculated with the function. The third yield provides the rest of the values in the series, using the function. The while loop makes sure that __iter__ returns values for ever.

r is a value in the sequence. The enumerate returns tuples of the form (0, u0), (1, u1), (2, u2), ... So r is one of the u values, and i is the index, which is used to return the u matching the provided index k.

I don't think this is a very good implementation. The __iter__ method is not done in the standard way. Typically, __iter__ would return self, and __next__ would be responsible for generating the actual values. It is memory efficient for calculating large values, but it's slow if repeatedly calculating values in the same range.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Interpreting this code EmBeck87 4 1,473 Apr-10-2023, 12:40 PM
Last Post: EmBeck87
  Trouble interpreting prime number code ryfoa6 1 2,221 Mar-20-2020, 03:47 PM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020