Computer Science

Predict the output of following code if the input is :

(i) 12, 3, 4, 5, 7, 12, 8, 23, 12

(ii) 8, 9, 2, 3, 7, 8

Code :

s = eval(input("Enter a list : "))
n = len(s)
t = s[1:n-1]
print(s[0] == s[n-1] and
t.count(s[0]) == 0)

Python

Linear Lists

2 Likes

Answer

Enter a list : [12, 3, 4, 5, 7, 12, 8, 23, 12]
False
Enter a list : [8, 9, 2, 3, 7, 8]
True

Working

  1. s = eval(input("Enter a list : ")) — This line prompts the user to enter a list.
  2. n = len(s) — This line finds the length of the list s.
  3. t = s[1:n-1] — This line slices the list s starting from index 1 up to index n-1, which effectively removes the first and last elements from the list s and stores it in list t.
  4. print(s[0] == s[n-1] and t.count(s[0]) == 0) — The condition s[0] == s[n-1] and t.count(s[0]) == 0 checks if the first and the last element of the list s are same [s[0] == s[n-1]] and that element does not appear anywhere else in list s apart from the first and last position [t.count(s[0]) == 0]. For case (i), 12 is the first and the last element of list but as it also occurs at the 5th index hence the output is False. For case (ii), 8 is the first and the last element of list and it doesn't appear anywhere else hence the output is True.

Answered By

2 Likes


Related Questions