簡體   English   中英

如何在 Python 中定義自己的范圍 function

[英]How do I define my own range function in Python

下面我附上一道作業題。 到目前為止,我唯一的代碼是。

def myRange(start, stop=None, step=None):

    if stop == None:
        stop = start

    if step == None:
        step = 1

    while True:
        if step > 0 and start >= stop:
            break
        elif step < 0 and start <= stop:
            break
        yield ('%g' % start)
        start = start + step
        break

    lyst = myRange(start, stop=None, step=None)
    for num in lyst:
        print(num)

myRange(0, 10, 2)

我試圖擺脫 yield 和 '%g' 語句,如果有人知道如何做的話,用 return 語句替換它。 除此之外,我正在嘗試使其真正像 function 一樣工作,您可以將變量傳遞給它並將范圍作為列表獲取,但我也不確定該怎么做。 任何幫助,將不勝感激。 我對此很迷茫。

定義並測試 function myRange。 這個 function 的行為應該像 Python 的標准范圍 function,具有必需和可選的 arguments,但它應該返回一個列表。 不要在您的實現中使用范圍 function:(提示,研究 Python 的范圍幫助以確定名稱、位置以及如何處理函數的參數。對兩個可選參數使用默認值 None,如果這些參數都等於 None。那么 function 只用停止值調用,如果第三個參數等於 None。那么 function 也用起始值調用,因此,函數代碼的第一部分確定了什么值參數是或應該是。代碼的 rest 使用這些值通過向上或向下計數來構建列表。)

Python 允許您接受任意數量的 arguments 和關鍵字 arguments ,如下所示:

def myRange(*args, **kwargs):
    # do something

args 將是一個元組,而 kwargs 將是一個字典。 例如,調用 myRange(21, 'foo', name='shado') 將使 args 為 (21, 'foo') 而 kwargs 為 {'name': 'shado'}。 args 和 kwargs 在技術上不必是 args 和 kwargs,但按慣例命名它們。 使用這個我想你可以根據 args 的長度構造一些條件

def myRange(*args):
    if len(args) == 1:
        start, end, step = 0, args[0], 1
     # conditionals for other cases

另一種方法是這樣的:

def myRange(start, stop=None, step=None):
    if stop == None and step == None:
        start, stop, step = 0, start, 1
    # handle the other conditions

基本上只是分別處理每個案例

為了制作列表,我將使用 while 循環。

    myRange(start=None, stop=10, step=None):
  1. 處理stop=10

    您設置了一個默認值stop = 10 但是,您創建的對象被要求模仿內置范圍 function。 內置范圍沒有默認stop=10 因此,如果原始版本中沒有默認值,請不要在您的版本中設置默認值

  2. 需要的最小參數數

    您的myRange有 3 個默認 arguments。 你見過下面的代碼嗎?

     for x in range(): print(x)

    提示: range至少需要一個參數。

  3. 開始的默認值

    10是停止。 以下代碼打印的第一個數字是多少? 0嗎? 1嗎? 2 ? 5 ? 10 ? 它是什么?

     for x in range(10): print(x)
  4. print件放在myRange之外

    縮進的代碼塊不應包含任何打印語句

    def myRange(start=None, stop=10, step=None): lyst = (list(range(stop))) # print (lyst) Noooo! lyst = myRange() print(lyst) # YES!
  5. 你需要一個return聲明

如果 function 有 output 我們寫return output你應該返回一個list

這個 function 應該像 Python 的標准范圍 function 一樣,帶有必需和可選的 arguments,但它應該返回一個列表

    def myRange(start=None, stop=10, step=None):
        lyst = list(range(stop))
        # print (lyst) Noooo!
        return lyst # New feature! return the output:)

    lyst = myRange()
    print(lyst) # YES! 

編輯

我決定給你一個 function 簽名。 你仍然需要填寫正文。 不要擔心大部分代碼,不要管它。 只需在最后編寫代碼,替換print("start:", start, "stop:", stop, "step:", step)

is_none = lambda x:\
    x == None

count_non_none = lambda args, *, is_none=is_none: {\
    sum(1 for _ in filter(is_none, args))
}   

def myRange(_a1, _a2=None, _a3=None, *, start=None, stop=None, step=None):
    args_non_none   = count_non_none((_a1, _a2, _a3))
    kwargs_non_none = count_non_none((start, stop, step))
    total_non_none  = args_non_none + kwargs_non_none

    if total_non_none == 1:
        # the one arg represents `stop`
        assert(not start)
        assert(not step)
        stop = stop if stop else _a1            
    elif total_non_none == 2:
        if args_non_none == 2:
            start = _a1
            stop  = _a2
         else # at least one keyword argument
             assert(not (start and step))
             L = [_a1, _a2, _a3]
             while len(L) > 0:
                 if not start:
                     start = L.pop(0)
                 elif not stop:
                     stop = L.pop(0)
                 elif not step:
                     step = L.pop(0)
    elif total_non_none == 3:
        L = [_a1, _a2, _a3]
             while len(L) > 0:
                 if not start:
                     start = L.pop(0)
                 elif not stop:
                     stop = L.pop(0)
                 elif not step:
                     step = L.pop(0)                
    else:
        raise TypeError("more than 3 arguments were passed in")

    if start == None: 
        start = 0 
    if step == None: 
        step = 1 

    print("start:", start, "stop:", stop, "step:", step)         

使用范圍 function 定義的無/無范圍。

def myRange(*args):
    myList=[]
    if len(args) is 1:
        k=0
        if args[0] > 0:
            while k < args[0]:
                myList.append(k)
                k=k+1
        else:
            while k > args[0]:
                myList.append(k)
                k=k-1
    elif len(args) is 2:
        k = args[0]
        if args[0] < args[1]:
            while k < args[1]:
                myList.append(k)
                k=k+1
        else:
            while k > args[1]:
                myList.append(k)
                k=k-1
    else:
        k=args[0]
        if args[0] < args[1]:
            while k < args[1]:
                myList.append(k)
                k=k+args[2]
        else:
            while k > args[1]:
                myList.append(k)
                k=k+args[2]
    return myList    
def myRange(start, step=None, stop=None):
    if step == None and stop == None:
        start, step, stop = 0, 1, start
        while start < stop:
            yield start
            start += step
    elif stop == None:
        start, step, stop = start, 1, step
        while start < stop:
            yield start
            start += step
    while start < stop:
        yield start
        start += step


for i in myRange(1, 10, 100):
    print(i)

或者您也可以使用 args 實現。

def custome_range(*args):
    if len(args) == 1:
        start, step, stop = 0, 1, args[0]
        while start < stop:
            yield start
            start += step
    elif len(args) == 2:
        start, step, stop = args[0], 1, args[1]
        while start < stop:
            yield start
            start += step
    elif len(args) == 3:
        start, step, stop = args[0], args[1], args[2]
        while start < stop:
            yield start
            start += step


for i in custome_range(1, 10, 100):
    print(i)

可以專門寫成if語句,判斷調用function時給出的是哪個arguments,然后while語句根據每個參數傳遞range_list中的數字。

def myRange(a, b = None, step = None):

     range_list = []

     if b == None:
          b = 0

     if step == None:
         while a > b:
             range_list.append(b)
             b += 1
         while a < b:
             range_list.append(a)
             a += 1

     elif step > 0:
         while a < b:
             range_list.append(a)
             a += step

     elif step < 0:
         while a > b:
             range_list.append(a)
             a += step

     else:
         range_list = [a]

     return range_list

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM