G
G
Grigory Shurygin2021-12-06 23:24:35
Python
Grigory Shurygin, 2021-12-06 23:24:35

Why does my function always return "False"?

Can you please tell me why my function always outputs "False"?

def is_sorted(l):
    chek_list = l.sort()
    if chek_list == l:
        return "True"
    else:
        return "False"

The function input is a list, the task is to display "True" if the input parameter was originally sorted in ascending order.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-12-07
@avrio

The .sort() method of a list sorts the list in place, and returns None.
If you need a sorted copy of the list without changing the original, sorted() is the way to go.
In general, it can be even simpler. Is the list sorted in ascending order? Then you need to make sure that each next element is greater than the previous one.

def is_sorted(lst) -> bool:
  for i in range(0, len(lst)-1)
    if lst[i] > lst[i+1]: #нашли элементы в неправильном порядке
      return False #значит не отсортирован
  # если сюда дошли, то отсортирован
  return True

Or the same but shorter
def is_sorted(lst) -> bool:
  return all( lst[i] <= lst[i+1] for i in range(0, len(lst)-1) )

P
Pavel Shvedov, 2021-12-06
@mmmaaak

Print to the console what is obtained in check_list after sorting

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question