Given a list L write a program to make a new list and match the numbers inside list L to its respective index in the new list. Put 0 at remaining indexes. Also print the elements of the new list in the single line. (See explanation for more clarity.)
Input:
[1,5,6]
Output:
0 1 0 0 0 5 6
Explanation:
List L contains 1,5,9 so at 1,5,9, index of new list the respective values are put and rest are initialized as zero.
Python Program:
L=[int(i) for i in input().split()]
new_list = [0] *(max(L)+1)
for i in range(len(new_list)):
if i in L:
new_list[i] = i
print(*new_list,end="")
Explanation :
The first line takes input from the user using the
input()function, which is then split into a list of integers using a list comprehension. Each element in the input string is first converted to an integer using theint()constructor, and the resulting list of integers is assigned to the variableL.The second line creates a new list
new_listcontaining(max(L) + 1)zeros, wheremax(L)is the largest element inL. This creates a list with enough space to store all the elements inLat their respective indices.The
forloop iterates over each indexiin the range from0to the length ofnew_listminus one, using therange()function.Inside the loop, the
ifstatement checks if the valueiis present inL. If it is, then the value at indexiinnew_listis updated to matchi. This means that if the valuexappears inL, thennew_list[x]will be updated tox.Finally, the
print()function is used to print the values innew_listin a single line, using the*operator to unpack the list and theendparameter to specify an empty string as the separator between values. This means that the values innew_listwill be printed without any separators between them.
Overall, this code generates a new list new_list with the same length as L, where the values from L are placed at their respective indices in new_list. The remaining indices in new_list are filled with zeros. Finally, the values in new_list are printed in a single line.
No comments:
Post a Comment