0

Can someone have a look at my code and tell me if its okay? Did I answer the prompt?

In the main part of your program, generate a random number between 1 and 10 and store it in variable k; prompt the user to enter k integers and store them in a list. Write a function called is_sorted that accepts a list of numbers as a parameter and returns True if the list is in sorted (nondecreasing) order and False otherwise. For example, if lists named list1 and list2 store [4, 23, 33, 10, 50, 60, 77, 90] and [20, 30, 100], respectively, the calls is_sorted(list1) and is_sorted(list2) should return False and True, respectively. Assume the list has at least one element. A one-element list is considered to be sorted. My code: https://code.sololearn.com/cf6s8x90s2Z0/#py def is_sorted(lis): isSorted = True for i in range(len(lis) - 1): if lis[i] > lis[i + 1]: return False return isSorted import random k = random.randrange(1,10) print("Enter",k,"values:") lis = [ ] for i in range(k): n = input("Enter value "+ str(i+1)+": ") lis.append(int(n)) isSorted = True isSorted = is_sorted(lis) print("original list:", lis) if isSorted: print("the list is sorted") else: print("the list is not sorted")

12th Oct 2020, 3:11 PM
...
... - avatar
4 odpowiedzi
+ 8
... , did you try your code? Is the result like it should be? This is easy to check by yourself. If both questions from me can be answered with YES, there is no need to post it here. If you just want to present the code, please do it in your personal feed. Thanks! And please do not duplicate your post here, if it takes some minutes until you get a response.
12th Oct 2020, 3:23 PM
Lothar
Lothar - avatar
+ 4
ok - there is a small issue in the function: def is_sorted(lis): isSorted = True for i in range(len(lis) - 1): if lis[i] > lis[i + 1]: return False return isSorted # <<< unindent this line one level , same as for ... the last line will be executed when the if statement gives False. the funtion will return isSorted and be terminated, even if there are more numbers in the list. so if you unindent the last line one level it should work.
12th Oct 2020, 4:10 PM
Lothar
Lothar - avatar
+ 2
I apologize, I tried my code but I didn't feel like I answered the question.. when it asked 'list1 and list2 store [4, 23, 33, 10, 50, 60, 77, 90] and [20, 30, 100], respectively, the calls is_sorted(list1) and is_sorted(list2) should return False and True' I input this information into Python SHELL and both resulted in True when once should be false...
12th Oct 2020, 3:39 PM
...
... - avatar
+ 1
Thank you Lothar!
12th Oct 2020, 5:09 PM
...
... - avatar