r/PythonLearning • • 5d 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

33 comments sorted by

View all comments

Show parent comment

1

u/Naive_Programmer_232 4d ago edited 4d ago

EDIT: Ignore this comment, see other reply for cumulative sum functions. this is not an example of that.


are you saying like this?

ex:

   def next_sums(arr: list[int]) -> list[int]:
       """
       ex: [1,2,3,4]
       e.g 1+2,2+3,3+4 ... {curr}+{next}
       """
       res=[]
       for i in range(len(arr)-1):
           res.append(arr[i]+arr[i+1])
       return res

   def prev_sums(arr: list[int]) -> list[int]:
       """
       ex: [1,2,3,4]
       e.g. 1+2,2+3,3+4 ... {prev}+{curr}
       """
       res=[]
       for j in range(1,len(arr)):
           res.append(arr[j-1]+arr[j])
       return res

Even though these are written different, they produce the same result. You can easier see these are the same by considering:

    next_sums addition:   arr[i]+arr[i+1]

                     let  j=i+1
                          j-1=i+1-1=i

                     thus,

    prev_sums addition:   arr[j-1]+arr[j]

here is a test to make sure they produce the same result:

   def run_all_tests() -> None:
       
       test_map = {
           "odd": [2,4,6,9,12],
           "even": [2,4,6,9,12,15],
           "empty": [],
           "single": [5],
           "duo": [5,10],
       }

       for test_name,arr in test_map.items():
           if next_sums(arr)==prev_sums(arr):
               print(f"passed {test_name} ✓")
           else:
               print(f"failed {test_name} X")
       

   run_all_tests()
   passed odd ✓
   passed even ✓
   passed empty ✓
   passed single ✓
   passed duo ✓