Steffi Keran Rani J
Steffi Keran Rani J

Reputation: 4103

Read the Elements of an List one-by-one in Python3

I am writing a program to find the rank of the sorted list in each pass. My program is here:

import sys

# No. of Students considered
n = int(input().strip())

# Scores of n students
scores = [int(scores_temp) for scores_temp in input().strip().split(' ')]

# No. of scores considered for alice
m = int(input().strip())

# Scores of Alice 
alice = [int(alice_temp) for alice_temp in input().strip().split(' ')]

for i in alice:
    #temp1 = sorted(alice, reverse = True)
    temp = alice
    print(temp)
    scores.extend(temp)
    temp2 = sorted(scores, reverse = True)
    unique = []
    [unique.append(item) for item in temp2 if item not in unique]
    print(unique.index(i)+1)

The input I gave for Alice's scores was:

>>> 45 87 23

My objective is to process 45 first, then after printing the rank, then proceed onto 87 and so on, but the problem is only after processing 45, 87 and 23, the ranks are printed, which results in wrong answer.

What should be done to get the correct answer. An example of the input and output is given here:

>>> n = 7
>>> scores = [100, 100, 50, 40, 40, 20, 10]
>>> m = 4
>>> alice = [5, 25, 50, 120]

Same scores are given the same rank in a way such that the largest score gets the first rank. Example 100 is the first rank The correct output is:

6
4
2
1

But I get some other wrong answer. (I need ranks for unique scores only) What should be done?

Upvotes: 1

Views: 2923

Answers (1)

Kir Chou
Kir Chou

Reputation: 3080

The root cause of your code is because of extend in loop, each loop's result is depended on others. extend add ALL scores of Alice in each loop.

  1. Original scores: [100, 100, 50, 40, 40, 20, 10]
  2. First loop: [120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
  3. Second loop: [120, 120, 100, 100, 50, 50, 50, 40, 40, 25, 25, 20, 10, 5, 5]

Instead of extend(alice), using append(i) is able to solve your case. Because append only add ONE scores of Alice in each loop.

for i in alice:
    scores.append(i)
    temp2 = sorted(scores, reverse = True)
    unique = []
    [unique.append(item) for item in temp2 if item not in unique]
    print(unique.index(i)+1)

> alice = [5, 25, 50, 120]

6 #temp2:  [100, 100, 50, 40, 40, 20, 10, 5]
4 #temp2:  [100, 100, 50, 40, 40, 25, 20, 10, 5]
2 #temp2:  [100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
1 #temp2:  [120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]

Note: because each loop is depended on others, difference input order will influence the result.

> alice = [120, 50, 25, 5]

1 #temp2:  [120, 100, 100, 50, 40, 40, 20, 10]
3 #temp2:  [120, 100, 100, 50, 50, 40, 40, 20, 10]
5 #temp2:  [120, 100, 100, 50, 50, 40, 40, 25, 20, 10]
8 #temp2:  [120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]

Upvotes: 1

Related Questions