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
3 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
s = eval(input("Enter a list : "))
— This line prompts the user to enter a list.n = len(s)
— This line finds the length of the lists
.t = s[1:n-1]
— This line slices the lists
starting from index 1 up to index n-1, which effectively removes the first and last elements from the lists
and stores it in listt
.print(s[0] == s[n-1] and t.count(s[0]) == 0)
— The conditions[0] == s[n-1] and t.count(s[0]) == 0
checks if the first and the last element of the lists
are same [s[0] == s[n-1]
] and that element does not appear anywhere else in lists
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 isFalse
. For case (ii), 8 is the first and the last element of list and it doesn't appear anywhere else hence the output isTrue
.
Answered By
2 Likes
Related Questions
Write equivalent list comprehension for the following code :
target1 = [] for number in source: if number & 1: target1.append(number)
Write equivalent for loop for the following list comprehension :
gen = (i/2 for i in [0, 9, 21, 32]) print(gen)
Predict the output :
def h_t(NLst): from_back = NLst.pop() from_front = NLst.pop(0) NLst.append(from_front) NLst.insert(0, from_back) NLst1 = [[21, 12], 31] NLst3 = NLst1.copy() NLst2 = NLst1 NLst2[-1] = 5 NLst2.insert(1, 6) h_t(NLst1) print(NLst1[0], NLst1[-1], len(NLst1)) print(NLst2[0], NLst2[-1], len(NLst2)) print(NLst3[0], NLst3[-1], len(NLst3))
Predict the output :
ages = [11, 14, 15, 17, 13, 18, 25] print(ages) Elig = [x for x in ages if x in range(14, 18)] print(Elig)