Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

I'm taking this online Python course and trying to solve the following problem called Coding Exercise: It's Natural:

Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.

Do I even need a for loop to create a list? Here's my code (which doesn't work obviously). Keep in mind, they have not taught list comprehension. I found this concept on stackoverflow.

def naturalNumbers(n):
   list = [n+1 for i in n]
   return list

Should I take another approach where I create multiple lists of 1,2,3...n and concatenate them all together like [1] + [2] + [3]....

like image 651
StacyM Avatar asked Sep 11 '13 22:09

StacyM


People also ask

How do I make a list from 1 to N?

To create a list of numbers from 1 to N: Use the range() class to create a range object from 1 to N. Use the list() class to convert the range object to a list. The new list will contain the numbers in the specified range.

How do you declare a positive integer in Python?

The abs() function is used to get the absolute (positive) value of a given number. The argument may be an integer or a floating point number.

How do you find the N number in a list in Python?

In Python, the built-in function len() is used to get the length (the number of items) of a list. This article describes the following contents. See the following article for the usage of len() for objects of other types. You can get the total number of elements with len() .


3 Answers

There are two problems with your attempt.

First, you've used n+1 instead of i+1, so you're going to return something like [5, 5, 5, 5] instead of [1, 2, 3, 4].

Second, you can't for-loop over a number like n, you need to loop over some kind of sequence, like range(n).

So:

def naturalNumbers(n):
    return [i+1 for i in range(n)]

But if you already have the range function, you don't need this at all; you can just return range(1, n+1), as arshaji showed.

So, how would you build this yourself? You don't have a sequence to loop over, so instead of for, you have to build it yourself with while:

def naturalNumbers(n):
    results = []
    i = 1
    while i <= n:
        results.append(i)
        i += 1
    return results

Of course in real-life code, you should always use for with a range, instead of doing things manually. In fact, even for this exercise, it might be better to write your own range function first, just to use it for naturalNumbers. (It's already pretty close.)


There is one more option, if you want to get clever.

If you have a list, you can slice it. For example, the first 5 elements of my_list are my_list[:5]. So, if you had an infinitely-long list starting with 1, that would be easy. Unfortunately, you can't have an infinitely-long list… but you can have an iterator that simulates one very easily, either by using count or by writing your own 2-liner equivalent. And, while you can't slice an iterator, you can do the equivalent with islice. So:

from itertools import count, islice
def naturalNumbers(n):
    return list(islice(count(1), n))
like image 145
abarnert Avatar answered Oct 24 '22 05:10

abarnert


Do I even need a for loop to create a list?

No, you can (and in general circumstances should) use the built-in function range():

>>> range(1,5)
[1, 2, 3, 4]

i.e.

def naturalNumbers(n):
    return range(1, n + 1)

Python 3's range() is slightly different in that it returns a range object and not a list, so if you're using 3.x wrap it all in list(): list(range(1, n + 1)).

like image 4
arshajii Avatar answered Oct 24 '22 05:10

arshajii


Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

like image 3
Harry Han Avatar answered Oct 24 '22 04:10

Harry Han