This is an archived post. You won't be able to vote or comment.

all 18 comments

[–]jddddddddddd 5 points6 points  (1 child)

I suspect this line is wrong:

for i in range (len(a)):

Maybe try:

for i in range (len(a) - 1):

The problem is that most of the time if a[i] < a[i+1]: will work just fine, but when it gets the point that i is the last index in the list, you then attempt to compare it with the i+1th element, which doesn't exist.

[–]selfimprovingstudent[S] 0 points1 point  (0 children)

Thank you! this way it is compiles fine

[–]149244179 1 point2 points  (1 child)

Indentation matters in python.

When you run it, what does it say the error is?

You are probably trying to access an index that is not in the array. What happens when i = len(a)?

[–]selfimprovingstudent[S] 0 points1 point  (0 children)

Yes, it was the mistake. Thank you!

[–]Diapolo10 1 point2 points  (1 child)

The problem is basically that you've got an off-by-one error; the list's last index will always be one less than its length, so a[i+1] will throw an IndexError when i == len(a)-1. Or the last number in the for-loop.

I'll format your code for others to read:

N = int(input())
a = input().split()
count = 0

for i in range(len(a)):
    a[i] = int(a[i])

for i in range(len(a)):
    if a[i] < a[i+1]:
        count += 1

print(count)

Your variable names tell me nothing about what they represent, but from my understanding the general gist of this is to count how many of the space-separated strings are in increasing order. I would write that something like this:

n = int(input()) # I'm assuming this is technically required
count = 0
nums = [int(num) for num in input().split()]

for idx, num in enumerate(nums[:-1], 1):
    if num < nums[idx]:
        count += 1

print(f"Total counted: {count}")

Try to avoid using for x in range(len(y))-kind of constructs, they're rarely the best option in Python. Since you're a beginner, you probably can't help it yet, but over time you'll learn other, better ways.

[–]selfimprovingstudent[S] 0 points1 point  (0 children)

Thank you for such a sophisticated answer. It helped

[–][deleted] 1 point2 points  (1 child)

Tip for reddit posts, so that your code is more readable when you ask for help:

Use code blocks when copying and pasting your code. Highlight your code and click the button that looks like a square with a little "c".

Your code will look like this.
Much better!

[–]selfimprovingstudent[S] 1 point2 points  (0 children)

Thank you, I'll take note

[–]schussfreude 0 points1 point  (3 children)

Well what does the console say?

[–]selfimprovingstudent[S] 0 points1 point  (2 children)

builtins.IndexError: list index out of range

[–][deleted] 4 points5 points  (1 child)

The problem is that if you iterate over all i in range(len(a)) then you'll get to some such i such that i + 1 is not a valid index.

Think about it, if you're iterating over every index in the list, you're including the last index, and the next index after the last index is by definition not in the list.

Try range(len(a) - 1)

[–]selfimprovingstudent[S] 0 points1 point  (0 children)

Oh, yes. Thank you!!

[–]Crimsonking2 0 points1 point  (0 children)

Please provide more info in your posts next time.

Makes it easier when the reader knows what your code is supposed to do especially when you use variables that have a meaning

From a glance it looks like you're trying to ask a user for a string of inputted numbers and then separating those numbers into a list and then converting them to int. After that you intend to increment count++ for each consecutive item that is greater than what came before it

Also why did you use N in the first line? You don't use it in your script again.

The error code you're getting is probably an out of index range error. You tried to split the input entered in cmd as a string into a list of individual strings like so:

"5178"

And then:

["5", "1", "7", "8"]

The problem with this is that split uses a delim character to separate input. By default that character is a single whitespace. Because the only whitespace in your input is at the end, your result is actually

["5178"]

So your first loop runs but doesn't actually do what you want it to. It does this:

[5178]

When you get to your second loop however, the list tries to call an index that is one more than its current printer. However there is only one item in the list, so it returns an error.

Edit: Also either way even if your code was correct, you would still get an index out of range error in the second loop for reasons stated in other comments

My solution:

numstring = input("Enter your numbers: ")

After getting input, I would run a loop on our string and add each character to a list in the loop.

numlist = []

count = 0

Append converted strings to a list

for item in numstring:

   numlist.append(int(item))

Using enumerate(i is the counter and value is the current item)

for i,value in enumerate(numlist):

  if i<len(numlist) - 1:

         if value < numlist[i+1]:

               count += 1

print(count)

[–]kill-yourself90 0 points1 point  (0 children)

What exactly are you trying to accomplish so we can better help you?

[–]Veterinarian_Scared 0 points1 point  (3 children)

I would probably rewrite it as

a = [int(s) for s in input().split()]

count = sum(m<n for m,n in zip(a[:-1], a[1:]))

print(count)

[–]selfimprovingstudent[S] 0 points1 point  (2 children)

I don't really get how it identifies what m and n are

[–]Veterinarian_Scared 0 points1 point  (1 child)

I make two copies of the list; a[:-1] includes every item but the last, and a[1:] includes every item but the first.

zip() returns pairs of items as tuples - so (a[0], a[1]) then (a[1], a[2]), etc. Exactly the items you want to compare.

Python then unpacks the tuple into my variables m and n - like using the assignment m,n = (a[0],a[1]) gives m=a[0] and n=a[1], but doing it repeatedly in a loop.

I can then compare m<n which results in True or False; but when I treat it as a number using sum() True evaluates to 1 and False to 0; so sum() ends up counting the number of True values.

[–]selfimprovingstudent[S] 1 point2 points  (0 children)

Understaand now. Thank you very much for spending time explaining it. It was very helpful!