+ 2

How to create a MyRange function like the standard range in Python

I wrote the MyRange function that only has one argument https://code.sololearn.com/cK29IXNg439W/?ref=app What I want : def MyRange(stop): def MyRange(start, stop[, step]): Not this : def My range(**argument): I appreciate if anyone have any solution!!

28th Oct 2018, 8:32 AM
左其右
左其右 - avatar
7 ответов
+ 4
In case you don't like tuple unpacking, the following should work. (Also, your code doesn't seem to handle the case of negative steps so well.) def MyRange(x, y=None, step=1): if y is None: start, stop = 0, x else: start, stop = x, y # main code here while ((step > 0 and start < stop) or (step < 0 and start > stop)): yield start start += step It can be shortened, of course, by directly using start and stop instead of x and y. But I didn't want the names to be misleading when x is actually stop.
28th Oct 2018, 12:03 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
左其右 I think the way I coded it, you can use all the forms. # only stop # print integers from 0 to 10 for i in MyRange(11): print(i) # start and stop # print integers from 5 to 10 for i in MyRange(5, 11): print(i) # start, stop, and step # print integers from 2 to 10 in steps of 3 for i in MyRange(2, 11, 3): print(i)
28th Oct 2018, 2:13 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 3
左其右 that's just telling you what the arguments mean if you give different amount of arguments in python, functions don't have polymorphism, so it just override the previous one if you define it twice therefore, if you want to let your function accept different amout of arguments and have different order of meaning, the better method is using func(*args) and decide their usage in the function another method is using keywords, like this: def myRange(*noUse, start=0, end=None, step=1): if len(noUse) is 1: end = noUse[0] but it's pretty meaningless🤔
29th Oct 2018, 4:08 AM
Flandre Scarlet
Flandre Scarlet - avatar
+ 2
Kishalaya Saha your answer is good. But how to explain this https:/goo.gl/7hxDUc It says that range() constructor has two form. range(stop) range(start, stop[, step])
28th Oct 2018, 1:45 PM
左其右
左其右 - avatar
+ 2
Kishalaya Saha 👍👍👍 yes yours is better😆
29th Oct 2018, 9:42 AM
Gordon
Gordon - avatar
+ 1
左其右 好名好名👏👏👏
29th Oct 2018, 5:42 AM
Gordon
Gordon - avatar
0
Use a default argument for step... https://code.sololearn.com/cy61cLst0nDN/?ref=app
28th Oct 2018, 10:12 AM
TurtleShell
TurtleShell - avatar