Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 list of odd numbers
#1
I need to write a function that generates a list of n odd numbers, starting at 1. For example, if the input is 12, the output would be
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]. I just started to learn python like 3 days ago and I have no idea where to start.

I was able to solve the similar question:

"Write a function that generates the first n natural numbers, starting at 1. The natural numbers are 1, 2, 3, 4, 5, ... You will need to create an empty list, add the numbers one by one, and return the list." with below code

def natural(n):
    L = list(range(n+1))
    L = [num for num in L if num] 
    return L


I think the solution for this problem would be similar to this code, but I have no idea where to fix.
scidam wrote Jul-12-2019, 11:44 AM:
Please post all code, output and errors (in it's entirety) between their respective tags. I did it for you this time, Here are instructions on how to do it yourself next time.
Quote
#2
Read the documentation of built-in function range.
Hint 1: Use step 2
Hint 2: If even or odd depends where you start.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Quote
#3
One good practice is to take advantage Python built-in help.

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
 |  
 |  Methods defined here:
/.../
To exit help press 'q'.

If you read this it's quite obvious that you can optimize you solution. Add start to range, convert to list and return:

>>> def natural(n):
...     return list(range(1, n+1))
... 
>>> natural(5)
[1, 2, 3, 4, 5]
However, your assignment states: 'You will need to create an empty list, add the numbers one by one, and return the list'. I have no idea, is it just a hint or requirement. To be in compliance with this you should start with empty list and then add numbers to that list:

def natural(n):
    nums = list()
    # code to add numbers
    return nums
In solving this task you can try next built-in feature. You have list and you want to do something with it. To find out what can be done with lists:

>>> list.    # two times tab
list.append(   list.copy(     list.extend(   list.insert(   list.pop(      list.reverse(  
list.clear(    list.count(    list.index(    list.mro(      list.remove(   list.sort(  


There is append which seems promising name. Using help let's find out what it does:

>>> help(list.append)
Help on method_descriptor:

append(self, object, /)
    Append object to the end of the list.
(END)
You can use this to append nums to list. But how to do it? You have to loop through all numbers in range and add it one by one. You should have some prior information what to look for and you have answer at your fintertips (built-in):

>>> help('for')
The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and continues
with the next item, or with the "else" clause if there is no next
item.

The for-loop makes assignments to the variables(s) in the target list.
This overwrites all previous assignments to those variables including
those made in the suite of the for-loop:
for i in range(10):
       print(i)
       i = 5             # this will not affect the for-loop
                         # because i will be overwritten with the next
                         # index in the range

Names in the target list are not deleted when the loop is finished,
but if the sequence is empty, they will not have been assigned to at
all by the loop.  Hint: the built-in function "range()" returns an
iterator of integers suitable to emulate the effect of Pascal’s "for i
:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".

Note: There is a subtlety when the sequence is being modified by the
  loop (this can only occur for mutable sequences, e.g. lists).  An
  internal counter is used to keep track of which item is used next,
  and this is incremented on each iteration.  When this counter has
  reached the length of the sequence the loop terminates.  This means
  that if the suite deletes the current (or a previous) item from the
  sequence, the next item will be skipped (since it gets the index of
  the current item which has already been treated).  Likewise, if the
  suite inserts an item in the sequence before the current item, the
  current item will be treated again the next time through the loop.
  This can lead to nasty bugs that can be avoided by making a
  temporary copy using a slice of the whole sequence, e.g.,

     for x in a[:]:
         if x < 0: a.remove(x)

Related help topics: break, continue, while
(END)
All information is available inside Python. You just need to learn to use it.

Your compliant code could look like:

def natural(n):
    nums = list()
    for i in range(1, n + 1):
        nums.append(i)
    return nums
As for your second task you could think about this feature decribed in range help: "When step is given, it specifies the increment (or decrement)"
nilamo, Larz60+, jefsummers like this post
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Question about Sorting a List with Negative and Positive Numbers Than999 2 107 Nov-14-2019, 02:44 AM
Last Post: jefsummers
  CODE for Bubble sorting an unsorted list of 5 numbers. SIJAN 1 488 Dec-19-2018, 06:22 PM
Last Post: ichabod801
  Regular Expressions in Files (find all phone numbers and credit card numbers) Amirsalar 2 1,461 Dec-05-2017, 09:48 AM
Last Post: DeaD_EyE
  List with Random Numbers AnjyilLee 5 2,862 Oct-14-2017, 09:22 PM
Last Post: buran

Forum Jump:


Users browsing this thread: 1 Guest(s)