i was on the site pyschools working through the exercises, but i dont understand why it wont accept the code i input.
http://www.pyschools.com/quiz/view_question/s4-q2

Create a function generateNumbers(start, end, step) that takes in three numbers as arguments and returns a list of numbers ranging from start to the end number (inclusive)and skipping numbers based on the step specified in the arguments. Note: The function range(x, y, z) can takes in 3 arguments. For example, range(1, 11, 2) will return a list of numbers [1,3,5,7,9].

Examples

>>> generateNumber(2, 10, 2)
    [2, 4, 6, 8, 10]
    >>> generateNumber(10, 10, 1)
    [10]
    >>> generateNumber(20, 0, -3)
    [20, 17, 14, 11, 8, 5, 2]

so i used the code;

def generateNumber(start, end, step):
    return [i for i in range(start, end+1, step)]

but it says its not right, whats wrong with it?

Recommended Answers

All 10 Replies

but it says its not right, whats wrong with it?

The code works,python always give you Traceback.
Post Traceback next time.

Run of code.

>>> generateNumber(0,10,2)
[0, 2, 4, 6, 8, 10]
>>> generateNumber(20,0,-3)
[20, 17, 14, 11, 8, 5, 2]
>>>

The code works,python always give you Traceback.
Post Traceback next time.

Run of code.

>>> generateNumber(0,10,2)
[0, 2, 4, 6, 8, 10]
>>> generateNumber(20,0,-3)
[20, 17, 14, 11, 8, 5, 2]
>>>

sorry, i know it works, but for the exercise in the link and the result of my solution isnt passing, i dont know why.

You got to let us know why it isn't passing?

The question itself is not clear

from start to the end number (inclusive)

but the results do not include the end number

range(1, 11, 2) will return a list of numbers [1,3,5,7,9]

.

if i knew why it wasn't passing, i wouldn't be stuck.

def generateNumber(start, end, step):
    if step > 0:
        return [i for i in range(start, end+1, step)]
    else:
        return [i for i in range(start, end, step)]

this should do the job, its all about the step being negative / positive

your code should work
could be the website you're using.

def generateNumber(start,end,step):
    if step>0:
        return(list(range(start,end+1,step)))
    else:
        return(list(range(start,end-1,step)))

After 7 years, I solved this question using a for loop:

            def generateNumber(x,y,z):
                li = []
                if z>0:
                    for i in range(x, y+z, z):
                        li.append(i)
                else:
                    for e in range(x, y-1, z):
                        li.append(e)
                return li

The problem with learning a new language is that you tend to thing in your previous language. In this case you used 8 lines when you should be thinking in Python and using

list(range(start,stop+1,step))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.