python fourth edition chapter 7 problem 3

Cause of python fourth edition chapter 7 problem 3

This problem is from a book of python fourth edition chapter 7 problem 3. In this question, one must systematically maintain a list of all the ten players in an ordered way. The list must contain the name of the player as well the score of that player. One of the approaches that most programmers try is the use of dictionaries which is not suitable as they are harder to sort. The code for the same is:

 

high_scores = []

 

The high_scores file contains the list of the players along with their scores. The data in the file is stored in the format.

Player_1   Score_1

Player_2   Score_2

The same goes for other players as well. 

This code is for storing the dictionary. Now to update the dictionary the code is as follows:

 

new_score = {score: player}

# opening the file
f = open("high_Scores.txt", "rb")
score_list = high_scores
f.close()

#appending scores in the list 
score_list.append(new_score)
score_list = score_list[:10] 

#writing the scores in the new file 
f = open("high_scores.txt", "wb")
pickle.dump(score_list, f)
f.close()

The problem in this code is that it is typical to sort the dictionary as compared to the list.

Solution

Multiple elements can be kept in a single variable by using lists. The code for the list declaration is:

l  = [“Study”, “Experts”]

One of the four built-in data types in Python for storing data collections is the list; the other three are the tuple, set, and dictionary, each of which has a unique purpose. The syntax for the same are:

Tuple: (“Study”, “Experts”)

Set: {4,6,3,2,1}

Dictionary: {1: “Study”, 2: “Experts”}

One of the solutions to this cause is to create a list in python instead of the dictionary. In the python list, one can make the nested tuple to store the name of the player as well as his score. It is easier to sort the list as compared to the dictionary. The code for the same can be: 

 

# to arrange the elements of list in descending order 
high_scores = [("Player_1", 76), ("Player_2", 87), ("Player_3", 99)]
high_scores.sort(reverse = True)
print(high_scores)

 

Output 

One can also use append, remove, pop, and other commands like that to only keep the needful data in the list. 

 

Also Read: show-doc not working in ruby pry

 

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *