List of odd natural numbers (3 ways)

Discussion on programming using the language Python. Discussion on different topics related to Python.
  • Advertisement

List of odd natural numbers (3 ways)

Postby Ethel » Tue May 01, 2012 8:27 am

Good afternoon. Could not be used to help me with one example (three ways) as the visibility. Other functions for example to try to alter.
In general, this is what I need to
define a function that takes as input an integer n and returns a list containing n elements, arranged in ascending order: List of even natural numbers 1) using the recursive definition 2) Using the cycles of 3) by using ( applying) the standard higher-order functions of Python.
User avatar
Ethel
Guest
Guest
 

Advertisement

Re: List of odd natural numbers (3 ways)

Postby Evelyn » Tue May 01, 2012 8:28 am

Code: Select all
>>>  def iterate ( Fun , init ) :
...      x  = init
...      while  True :
...              yield x
...              x  = Fun ( x )
...
>>>  from  itertools  import islice
>>>  # even natural numbers = {2, 4, ..., 2n, 2n +2, ...}
...
>>>  def even_nats ( count ) :
...      # return an iterator
...      return islice ( iterate ( lambda x: x + 2 ,  2 ) , count )
...
>>>  list ( even_nats ( 10 ) )
[ 2 ,  4 ,  6 ,  8 ,  10 ,  12 ,  14 ,  16 ,  18 ,  20 ]
>>>
User avatar
Evelyn
Guest
Guest
 

Re: List of odd natural numbers (3 ways)

Postby Flora » Tue May 01, 2012 8:29 am

A way

Code: Select all
[ QUOTE = Nameless One ; 2827569 ] [ PYTHON ] >>>  def iterate ( Fun , init ) :
...      x  = init
...      while  True :
...              yield x
...              x  = Fun ( x )
...


2 way

Code: Select all
>>>  from  itertools  import islice
>>>  # even natural numbers = {2, 4, ..., 2n, 2n 2, ...}
...


3 Way

Code: Select all
>>>  def even_nats ( count ) :
...      # return an iterator
...      return islice ( iterate ( lambda x: x + 2 ,  2 ) , count )
...
>>>  list ( even_nats ( 10 ) )
[ 2 ,  4 ,  6 ,  8 ,  10 ,  12 ,  14 ,  16 ,  18 ,  20 ]
>>>
User avatar
Flora
Guest
Guest
 


List of odd natural numbers (3 ways)

Return to Python


Link to: List of odd natural numbers (3 ways)
URL:
BBCODE:
HTML:

 


  • Related topics
    Replies
    Views
    Last post

Who is online

Users browsing this forum: No registered users and 0 guests

 ® PcLayer.com 2009-2012 ©   All Rights Reserved