Python Forum
A function that checks if the list is sorted - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: A function that checks if the list is sorted (/thread-19176.html)

Pages: 1 2


A function that checks if the list is sorted - pooyan89 - Jun-16-2019

The task is :


Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in ascending order and False otherwise. For example:

>>> is_sorted([1, 2, 2])
True
>>> is_sorted(['b', 'a'])
False


My code is :
def is_sorted(a):
    for i in range(len(a)-1):
        if a[i]<=a[i+1]:
            return True
    return False
When I try:
is_sorted([1,2,3,4,0,5,6])
the answer is True which is not correct! Why?
We see a[3]=4 and a[4]=0 which is not True. So why it gives me True?


RE: A function that checks if the list is sorted - Yoriz - Jun-16-2019

The first check for comparison it does is, 1 is equal to or less than 2 which is true so it stops.
You need to learn to add print statements to see whats happening in yours code.
def is_sorted(a):
    for i in range(len(a)-1):
        print(a[i], a[i+1])
        if a[i]<=a[i+1]:
            return True
    return False

print(is_sorted([1,2,3,4,0,5,6]))
Output:
1 2 True



RE: A function that checks if the list is sorted - pooyan89 - Jun-16-2019

(Jun-16-2019, 05:21 PM)Yoriz Wrote: The first check for comparison it does is, 1 is equal to or less than 2 which is true so it stops.

But doesn't it go through the whole loop?


RE: A function that checks if the list is sorted - Yoriz - Jun-16-2019

It wont, your code says as soon as it finds a[i]<=a[i+1] return True


RE: A function that checks if the list is sorted - pooyan89 - Jun-16-2019

(Jun-16-2019, 05:28 PM)Yoriz Wrote: It wont, your code says as soon as it finds a[i]<=a[i+1] return True

So I see if I write:

def is_sorted(l):
    for i in range(len(l)-1):
        print(l[i],l[i+1])
        if l[i]>l[i+1]:
            return False
    return True
It works ! and it will go through the whole loop!


RE: A function that checks if the list is sorted - noisefloor - Jun-16-2019

Hi,

@ppoyan89: iterating over an iterable with for x in range(len(iterable)) is still a bad anti-pattern. Don't you have any motivation to use what you learned before?

Except this, this is solvable without iteration but by the build-in function sorted:

def is_sorted(iterable):
    return iterable == sorted(iterable)
Regards, noisefloor


RE: A function that checks if the list is sorted - pooyan89 - Jun-16-2019

(Jun-16-2019, 05:42 PM)noisefloor Wrote: Hi,

@ppoyan89: iterating over an iterable with for x in range(len(iterable)) is still a bad anti-pattern. Don't you have any motivation to use what you learned before?

Except this, this is solvable without iteration but by the build-in function sorted:

def is_sorted(iterable):
    return iterable == sorted(iterable)
Regards, noisefloor

Hi!
I am not a very good programmer and had not a very good teacher! but at all cost I am trying to learn the base of programming... that is because I use this. It seems much more easier for me to write for example:
for i in range(len(a))
But you say it is a bad pattern for looping through a list ?


RE: A function that checks if the list is sorted - noisefloor - Jun-16-2019

Hi,

Quote: But you say it is a bad pattern for looping through a list ?
Because it's a useless anti-pattern. Python can iterate directly over iterables. I explained that to you earlier (I think yesterday?) in another one of your "need help on homework" thrads in detail. So have a look there, I will not repeat here again.

In case you want to learn proper Python: work yourself through the official tutorial at docs.python.org

Regards, noisefloor


RE: A function that checks if the list is sorted - DeaD_EyE - Jun-16-2019

from itertools import tee


def last_current(iterable):
    """
    Takes any kind of iterable and
    returns a interator which yields
    last and current element
    """
    last, current = tee(iterable)
    next(current)
    return zip(last, current)
    

def is_sorted(sequence):
    """
    Consumes any kind of sequences, also
    Generators, which can be consumed only one time
    and do not have index access.
    """
    for last, current in last_current(sequence):
        if last > current:
            return False
    return True



RE: A function that checks if the list is sorted - perfringo - Jun-16-2019

(Jun-16-2019, 05:52 PM)pooyan89 Wrote: I am not a very good programmer and had not a very good teacher! but at all cost I am trying to learn the base of programming... that is because I use this. It seems much more easier for me to write for example:
for i in range(len(a))
But you say it is a bad pattern for looping through a list ?

One of the reasons why for i in range(len(a)) is considered antipattern is that integer is usually used to access list elements by index. You don't need to do it in Python, as noisefloor pointed out you can iterate directly over list element without need to mess with access by indices. However, if you need integer then you should use enumerate.

If you want to learn fundamentals then you should not go for 'more easier for me to write' but 'what are the best practices' and 'why are they considered best practices'

One easy to understand and well presented material is Ned Batchelder Loop Like a Native