Home > Back-end >  What does ":" in front of a variable in For loop do do (Python)
What does ":" in front of a variable in For loop do do (Python)

Time:01-25

So, I was in HackerRank, trying to learn some pyhton, like any other begginer, and then I come to the question of "Introduction to Sets"

The task require to do seemed pretty simple to me... at first:

Computer inputs N, wich is a integer and arr, wich is a list, and your job is to write a code that takes the numbers of arr, to be divided by N. Simple right? Not for me, apparently

I would like to know: what the hell does ":" in front of a variable do like in :

if array[:_ 1].count(array[_]) == 1:

And why does make the count method work, i searched and found nothing, and I heard this is a good place to ask, sooo, any ideias?

I tried sum all numbers in a online calculator, but it would only give me the result i would get with my own code.

After some try and error of coding i came up to this:

    if len(array) != n:
        print (array)
        del array[len(array)]
        print (array)
        arr = sum(array)
        print (arr)
        array = arr / n
        print (array)
        return ('%.3f') %array
    else:
        print (array)
        array = sum(array)
        print (array)
        print (array)
        return ('%.3f') %(array/n)

(Yeah, i know its bad)

But apparently, that wasnt enough because, it was always giving me a wrong answer, so i decided to find something in the discussion tab, and I found this:

def average(array):
    sum_ = 0; count = 0
    for _ in range(len(array)):
      if array[:_ 1].count(array[_]) == 1:
        sum_  = array[_]
        count  = 1
    return '%.3f' % (sum_/count,)


I try it and, surprise surprise, it worked !!!

Like... in the first try

And the the difference its like... OUTSTANDING!!

0.775, a difference of 0.775

my code give me 168.600; this other code gives 169.375

why

if that's relevant, i use Visual Studio Code

I also changed '_' to 'a' to see if changes anytthing, and no

Input Numbers:

n = 10
arr = [161, 182, 161 ,154 ,176, 170, 167, 171, 170 ,174]
result = average(arr)
print(result)

srry for bad engrish

CodePudding user response:

array[2:4] gives you the elements 2 and 3 from the array. Generally,

array[start:end] will give you a slice of the array beginning with index start and stopping one before index end (that means, slice ranges are left-inclusive and right-exclusive).

Now, there's a few shortcuts. If you leave out start, the slice will just start at the beginning of the array: array[:end] is the same as array[0:end]. If you leave out the end, the slice will just run to the end of the array.

So array[:_ 1] will give you a slice of the array starting at index 0 and running up to index _ 1 exclusive, i.e. up to index _ inclusive.

  • Related