Friday 15 January 2010

function - Python: yield vs print in a loop -


I have solved this particular problem, though it leaves me with some questions Def: fibsum (): result = [] a, b = 0, 1 while true: a, b = b, a + b print b if b & lt; 4000000 and B% 2 == 0: result.append (b) if B & gt; 4000000: Brake print amount (result) Fibusum ()

When I run it using PowerShell, first it prints me all the numbers (though it ends once ), And then prints this amount at the end:

  1 2 3 5 8 ... 3524578 5702887 & lt; - It's more than 4 million why is it here? 4613732 & lt; - The answer is   
  1. Is there any way that a loop can be prevented before reaching more than 4,000,000?

  2. To save space, is there any way that I can print all the formats in a list format ([,,,]) if I print Decide to use

  3. When I change the print with the original code or returns (for Variable B), the program will not print anything, even then

    Print amount (results)

    At the end of the function.

  4. Can I make it easier without defining the result and adding it without any other purpose? When values ​​are returned in the same format as the real result, then the amount () does not work.

    1. Simply move the second condition before printing < Code> b :

      while correct: a, b = b, a + b if b> 4000000: Brake Print B If B & L; 4000000 and B% 2 == 0: result.append (b)   

    2. Do not print b in the loop, rather print the result < / Code> You break out once. 3. Well, for the return, it is very clear that you come back from the function, so the following code in the function is not executed and therefore your list is not populated.

    yield is used to create generator functions, where the next values ​​of each function of your function come back, so, you have to call your function multiple times, Thus, the yield value must be added to the exiting list. And when you do not return anything, your function will break.

    Use the yield keyword to understand more clearly, take a look at this post:

    You can use this kind of yield to Edit your code (it has not been tested):

      def fibsum (): A, b = 0, 1 while correct: a, b = b, a + b B & gt; 4000000: Break Receipts b Results = [] For Falgos () in Fibs: If Val & lt; 4000000 and val% 2 == 0: result.append (val) print amount (results)   

    Then, for each loop, call fibsum () The function generates the next value, which you add to the list based on this condition.

No comments:

Post a Comment