I was solving a question from Hackerrank on Nested Lists. I don't how to continue my code.
This is my algorithm
- create a list for names and marks
- create a list for marks
- then sort them in ascending order
- then remove the duplicates
- now the second element in the list is the second lowest mark
- now from the list where names and marks are included at the start, remove the duplicates
- then create a new list which contains only the names of the students who got second lowest marks
- sort them in alphabetical order
- then print the list that contains the names of the students
This is my code
if __name__ == '__main__':
for _ in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
student_score.append([name, score])
marks.append([score])
marks.sort()
res = []
for score in marks:
if score not in res:
res.append(score)
for score in res:
second_mark = res[2]
for elements in student_score = res[2]:
new.append(name,score)
for i in new:
if i not in new:
new_names.append(name)
print(sorted(new_names))
CodePudding user response:
You can't work with separate lists for the marks and names - there has to be some kind of relationship. A dictionary will help.
Each key in the dictionary can be a score. Each associated value is a list of names (with the same score).
Once you've built the dictionary, remove the key with the lowest value.
That means that the lowest remaining key is actually the second lowest score.
Sort the associated list and print.
if __name__ == '__main__':
data = dict()
for _ in range(int(input())):
name = input()
score = float(input())
data.setdefault(score, []).append(name)
del data[min(data)]
for name in sorted(data[min(data)]):
print(name)
Note:
Python 3
CodePudding user response:
You can use seperate lists if you prefer. One major problem with your code is most of the arrays you reference don't exist. You also have some syntax errors and you are doing more operations than are necessary to achieve the solution.
Here is a solution where I tried to make as few changes as possible so you can directly compare your attempt and see the differences:
if __name__ == '__main__':
student_score, marks = [], []
for _ in range(int(raw_input())):
name = raw_input()
score = float(raw_input())
student_score.append([name, score])
marks.append(score)
marks.sort()
second_mark = marks[1] # indices start at 0... second lowest would be index 1
new = []
for elements in student_score:
name, score = elements
if score == second_mark:
new.append(name)
for i in sorted(new):
print i # Pypy2 and python2
# print(i) # Pypy3 and python3