Problem Set 4(ID Plants)

ID PLANTS
Q.A gardener has the practice of assigning ID to the plants during plantation. One day, he makes a note of the heights of plants in his garden. He writes the height of the plant against the ID of the plant. He then instructs his employee to keep the plants, in ascending order of its height. Design an algorithm and write the Python code to display the list of ID numbers of plants in ascending order of their height. IDs are also numbers. Check for boundary conditions and print 'Invalid input' for wrong input. For example, if there are three trees with IDs as 175, 160, 120 and height as 47, 73 and 23 then the output should be [120, 175, 160].
Input Format:
First line contains the number of plants, n
Next line contains the ID of the plant-1
Next line contains the height of plant-1
. . .
Next line contains the ID of the plant-n
Next line contains the height of plant-n
Output Format:
IDs sorted according to height. Print one id in one line
Boundary Conditions:
All inputs >=0

Input:
Number of plants, id’s on n plants, height of n plants

Processing:
id_height = {}
for i in range(number):
    ids = int(input())
    height = int(input())
    if ids not in id_height:
        id_height.setdefault(height,ids)
heights_sorted = sorted(list(id_height.keys()))
ids_sorted = []
for i in heights_sorted:
    ids_sorted.insert(i,id_height[i])

Output:
Display Ids based on the sorted heights.
Algorithm:
Step1. Get the number as input
Step2. Initialize id_height as an empty dictionary
Step3. If number is less than display invalid input else proceed step4
Step4. Initialize i as 0 repeat till i is less than number
Step4.1 get the ID of the ith plant
Step4.2 get the Height of the ith plant
Step4.3 if the ID of the ith plant is not in id_height then insert height and let the key of height be ids
Step5. Let heights_sorted be the sorted list of keys of id_height
Step6. Initialize ids_sorted as an empty list
Step7. Let i move through the heights_sorted list
Step7.1 display the ith key of id_height with respect height_sorted.
Step8. End

Program:
number = int(input())
id_height = {}
if number < 1:
    print('Invalid Input')
else:
    for i in range(number):
        ids = int(input())
        height = int(input())
        if ids not in id_height:
            id_height.setdefault(height,ids)
    heights_sorted = sorted(list(id_height.keys()))
    for i in heights_sorted:

        print(id_height[i])

Flowchart:
To edit this flowchart click on this

No comments:

Post a Comment

Bonus Practice Problems(GMT To IST)

IST (Indian Standard Time) is 5 hours 30 minutes ahead of GMT(Greenwich Mean Time). Develop an algorithm and write the Python code to find...