Refining Algorithms – Q&A

Question 1[3 marks]
Somjay has created the following program in his computer science lesson. The aim of this program is to generate and display five random “lucky” numbers every time this program is executed.

Here is his Python code:
print("Your five lucky numbers are...")

number = random.randint(1,100)
print(number)
number = random.randint(1,100)
print(number)
number = random.randint(1,100)
print(number)
number = random.randint(1,100)
print(number)
number = random.randint(1,100)
print(number)


Somjay has received feedback from his teacher who asked him to rewrite his code using iteration. Rewrite this code to take into consideration the feedback Somjay received from his teacher.
Question 2[3 marks]
Somjay is investigating a method to save all the numbers from a list into a text file, one number per line. He has typed the following code to do so:
list = [4, 6, 12, 98, 57, 32, 31, 6]
for i in range (0,len(list)):
       file = open("stats.txt","a")   # "a" -> append mode
       file.write(list[i])
       file.close()

His teacher believes this code is not as efficient as it could be, especially if the list of numbers was to increase. He believes this code could easily be refined to minimise the number of times the text file is opened and closed when the code is run. Rewrite this code to improve its efficiency based on this feedback.
Question 3[4 marks]

Somjay is now focusing on a piece of code that should ask the user to enter a star rating (a value between 0 and 5) and display an error message if the star rating is invalid.

Here is Somjay’s code:
rating = int(input("Enter a rating between 1 and 5"))

if rating < 0:
  print("This rating is to low...")
elif rating > 5:
  print("This rating is too high!")
else:
  print("This rating is valid!")

Somjay would like to refine this code so that the computer keeps asking the user to enter a rating until a valid rating is being entered. He believes this could be done using a while loop.

Refine this code to meet Somjay’s requirement.
Save / Share Answers as a link
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 3.3 / 5. Vote count: 27

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!