Truth = False
list = [1, 2, 3, 6, 4]
for i in range(0,3):
if list[i] < list[i +1]:
Truth = True
else :
Truth = False
if Truth == True:
print('nums increase ')
else:
print('not increasing')
Asked
Active
Viewed 472 times
-1

OneCricketeer
- 179,855
- 19
- 132
- 245

Mark
- 1
-
1Please don't use `list` as a variable name as you're overriding the Python keyword of the same name. If your list is called `a` you can just check `if a == sorted(a)`. – David Buck Mar 04 '22 at 17:06
-
You current code effectively compares only the last two elements. All the others are irrelevant as `Truth` is reset on every iteration. – JonSG Mar 04 '22 at 17:07
-
@DavidBuck It's not a keyword. – Kelly Bundy Mar 04 '22 at 17:27
-
2While @KellyBundy is correct that technically `list` is a rather important class name rather than a reserved keyword, the advice remains valid. "Don't use `list` as a variable name` :-) – JonSG Mar 04 '22 at 17:33
3 Answers
1
You can use all()
function to check this
lst = [ ... ]
is_sorted = all(lst[x] < lst[x + 1] for x in range(len(lst) - 1))

OneCricketeer
- 179,855
- 19
- 132
- 245
0
I'd rather do something a little bit different: you can start with Truth=true, than whenever you find an element like list[i] > list[i+1], then you make Truth=false and stop the iteration

Lorenzo Stigliano
- 24
- 3
-
This is a sound answer. If you add some code demonstrating how to do this, I will remove what is essentially this as the current 3rd part of my answer. – JonSG Mar 04 '22 at 17:24
-
`Var = [0, 1, 2] def Is_Order_Foo(list): for i in range(0,len(list) - 1 ): if list[i] > list[i +1]: return print('nums not increasing') return print('nums increase') Is_Order_Foo(Var)` You can do something like this: you can avoid to think the length of the list while you are writing the code and then assume that when you start the list is in order but whenever there's a number in the wrong position you stop check all the list. Maybe you do also some tricks with comprehension list and do all the stuff in just one line, but I did a more C like approach – Lorenzo Stigliano Mar 05 '22 at 10:11
0
Your logic looks fine. Not rewriting it. just changing the Truth=1 and Truth=Truth*1 or 0
Truth = 1
list = [1, 2, 3, 6, 4]
for i in range(len(list)-1):
if list[i] < list[i +1]:
Truth = Truth*1
else :
Truth = Truth*0
break
if Truth == 1:
print('nums increase ')
else:
print('not increasing')

Alex Rajan Samuel
- 144
- 3
-
1
-
It would be better to invert the condition and just remove the "else". There is no reason to multiply 1 by 1. – OneCricketeer Mar 04 '22 at 17:41