Skip to content
Advertisement

What does “:” in front of a variable in For loop do do (Python)

I was in HackerRank, trying to learn some pyhton, like any other beginner, 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, which is a integer and arr, which 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, so, any ideas?

I tried to 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 it’s bad)

But apparently, that wasn’t 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 anything, and no

Input Numbers:

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

sorry for bad English

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement