snk
snk

Reputation: 91

how to refer to the next item in a list and compare it to the item before it?

I have a homework question where it asks to make an algorithm which would go through every element in the list and see if the number beside it is greater than the current number or not. If it is not greater than the current number, then the counter will go up by 1, if it is greater the counter will stay where it is. I got it to work but it only works if there are more than 3 items in the list.

Here's what I have so far:

def count(items):

if len(items) == 0:
    return 0



else:
    count = 0
    for i in items:
        count += 1
        items1 = items[i:]
        items2 = items[i+1:]

        if items1 > items2:
            return count - 1



print (count([42, 7, 12, 9, 2, 5])) #returns 4. works but does not work if len < 3
print (count([])) #returns 0. works
print (count(list(range(10**7))))  # supposed to print out 1 since it's only 1 number, but it just gets stuck and doesn't finish the rest of the program
print (count([99])) # prints out none  
print (count(list(range(10**7,0,-1))))# supposed to print out 10000000 but prints 1 instead 

Any kind of help or suggestions would be greatly appreciated.

Upvotes: 0

Views: 1197

Answers (2)

Samantha Atkins
Samantha Atkins

Reputation: 678

In general

def count_next_test(numbers, test_fn):
  count = 0
  last = len(numbers) - 1
  for i, n in enumerate(numbers):
    if i < last:
      if test_fn(n, numbers[i+1]):
        count += 1
  return count

In your case: count_next_test(numbers, lambda a, b: a < b)

You could also do something like

pairs = zip(numbers, numbers[1:])
len([(a,b) for a,b in pairs if a < b])

Upvotes: 0

palamunder
palamunder

Reputation: 2745

If you have 0 or 1 elements - return 0. You have to iterate over the length of the array, not over the elements themselves. There is a difference between: for i in array and for i in range(0,len(array))

Be careful with the range - open a console and type python. Check what range(10**2) prints. It is not one element. https://www.w3schools.com/python/ref_func_range.asp

def count(items):

    if len(items) == 0 or len(items) == 1:
        return 0
    else:
        count = 0
        for i in range(0,len(items)-1):
            items1 = items[i]
            items2 = items[i+1]

            if items1 > items2:
                count = count + 1
        return count

Upvotes: 1

Related Questions