1

I've noticed that in a lot of coding problems there is a need to compare x to x+1 in an array, although I've never found a good way to do it.

How can I do it? Is it even possible? Sorry if this seems like a noob question, I am not very good yet.

Here is what I usually try:

       for x in range(len(nums)):
                    if nums[x] > nums[x+1 < len(nums)]:
                        count +=1 
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • `for x in range(len(nums) - 1):` – 001 Dec 24 '19 at 00:49
  • Array? what arrays? Python has lists, not arrays. You have to a package like `numpy` to get arrays. Indexing of lists is quite restrictive (esp. compared to `numpy`). A boolean index (from the `<`) is just translated to `0/1`, so is rarely useful. – hpaulj Dec 24 '19 at 02:43

4 Answers4

1

No problem! we all start somewhere :) Here's one way to do it:

for x in range(len(nums) - 1):
   if nums[x] > nums[x+1]:
       #do something

1

len(nums) will return the number of values in an array, and when you are looping through an array, the first value in that array will be accessed using an index of 0, not 1.

for example:

nums = [1,3,5,7]
len(nums) == 4

if you run

for x in range(len(nums)):
   if nums[x] > nums[x+1]:
       #code here

you will get an error at nums[x+1] because on the last iteration, it becomes nums[3+1] which is nums[4], and that index is not in that array. Your last index is 3.

So what you really want is

for x in range(len(nums)-1):
   if nums[x] > nums[x+1]:
       #code here
Entroyp
  • 61
  • 1
  • 9
0

You could use reduce

For example, to get the max of a list, you could do the following

import functools 
arr = [1,2,3,4,5]
print(functools.reduce(lambda a,b : a if a > b else b, arr))

Output

5

This answer is great to refer to as well.

Rahul P
  • 2,493
  • 2
  • 17
  • 31
0

You could iterate through the adjacent pairs of any sequence with this helper function:

def pairwise(iterable):
    "s -> [[s0,s1], [s1,s2], [s2, s3], ...]"
    a, b = iter(iterable), iter(iterable)
    next(b, None)
    return zip(a, b)


nums = 1, 5, 3, 7
count = 0
for x, x1 in pairwise(nums):
    if x > x1:
        count += 1
martineau
  • 119,623
  • 25
  • 170
  • 301