2

I have to define my own floating-point version of range() here. It works the same as built-in range() function but can accept float values.start, stop, and step are integer or float numbers and step is a non-zero value and it also can be negative.

I have tried looking for answers on stackoverflow but all of them only work for positive step. I keep getting stuck on a test where it tests the value (0,0.25,-1) I'm a hundred percent sure there is a quicker and faster to implement this because my program takes a long time to test all the values. can someone help me create a function to do this and I Can't user imported tools.

def float(start,stop,step):
  x = start
  my_list = []
  if start < stop:
    while x<stop:
        my_list.append(x)
        if x < 0:
            x-=step
        elif x > 0:
            x+=step
        else:
            x+=step
    return my_list
  if start > stop:
    while x<=start and x>stop:
        my_list.append(x)
        if x < 0:
            x=step
        elif x > 0:
            x+=step
        else:
            x+=step
    return my_list  
TerasVallo
  • 71
  • 1
  • 2
  • 8

2 Answers2

3

Convert the floating steps into integer steps. You'll get less drift from error due to rounding of floats:

def float_range(start,stop,step):
    istop = int((stop-start) // step)
    for i in range(int(istop)):
        yield start + i * step
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
2

The main reason you're getting answers wrong is the top level if statements are wrong. You don't want to look at the boundaries when deciding which way to move. It's legal to ask for a range that has nothing in it (with e.g. stop less than start with a positive step).

Here's how I'd minimally adjust your code to work properly:

def float_range(start,stop,step):
    x = start
    my_list = []
    if step > 0:
        while x < stop:
            my_list.append(x)
            x += step
    else: # should really be if step < 0 with an extra check for step == 0 
        while x > stop:
            my_list.append(x)
            x += step
    return my_list 
Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • 1
    That should happen automatically if your other check is either removed or changed to `if step < 0`. (You might also want to raise an exception is `step` is zero.) – Blckknght Mar 01 '16 at 06:32
  • 1
    Oh, actually I hadn't read all the details of your code. There are some other issues, but the initial bits were right. I'll edit with more fixes. – Blckknght Mar 01 '16 at 06:34
  • Thanks so much! it worked. I had everything misplaced. Thank you – TerasVallo Mar 01 '16 at 06:43