Saturday, March 25, 2023

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.

 



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 :

  1. 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 the int() constructor, and the resulting list of integers is assigned to the variable L.

  2. The second line creates a new list new_list containing (max(L) + 1) zeros, where max(L) is the largest element in L. This creates a list with enough space to store all the elements in L at their respective indices.

  3. The for loop iterates over each index i in the range from 0 to the length of new_list minus one, using the range() function.

  4. Inside the loop, the if statement checks if the value i is present in L. If it is, then the value at index i in new_list is updated to match i. This means that if the value x appears in L, then new_list[x] will be updated to x.

  5. Finally, the print() function is used to print the values in new_list in a single line, using the * operator to unpack the list and the end parameter to specify an empty string as the separator between values. This means that the values in new_list will 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