r/PythonLearning • • 3d ago

i am stuck with the range function

sorry but i am gonna crash out because of the range function i cant understand it well to use it this is driving me crazy any one could give me a video explaining everything i dont mind it being an hour long

8 Upvotes

32 comments sorted by

View all comments

Show parent comment

2

u/Naive_Programmer_232 3d ago edited 3d ago

ahh i see ignore my other comment, you're talking about cumulative sums i believe.

from typing import TypeAlias, Any

Number: TypeAlias = int|float

# with 'range'  (iterative)
def rng_csum(arr: list[Number]) -> list[Number]:
    res=arr[:1]
    for i in range(1,len(arr)):
        res.append(res[-1]+arr[i])
    return res

# without range (iterative)
def reg_csum(arr: list[Number]) -> list[Number]:
    res=arr[:1]
    for n in arr[1:]:
        res.append(res[-1]+n)
    return res

# without range (recursive)
def rec_csum(arr: list[Number]) -> list[Number]:
    if len(arr)<=1:
       return arr
    res=rec_csum(arr[:-1])
    res.append(res[-1]+arr[-1])
    return res

# itertools.accumulate is another way 
from itertools import accumulate as proven_csum

# compares any number of position args for equivalency
def all_equal(*args: Any) -> bool:
    return all(args[0]==e for e in args)

def test() -> None:

    Ni=[2,4,6,9,12]

    # results
    r1=rng_csum(Ni)
    r2=reg_csum(Ni)
    r3=rec_csum(Ni)
    r4=list(proven_csum(Ni))

    assert all_equal(r1,r2,r3,r4), "failed test case"
    print("\npassed test case\n")
    print(f"Ni↑={r1})

test()

passed test case

Ni↑=[2, 6, 12, 21, 33]

hopefully that gives you some ways you could go about it. best of luck!