Need help understanding this | Sololearn: Learn to code for FREE!

+1

Need help understanding this

Hello there, so I've just solved this question but i got it wrong the first time so isit okay if u guys help me explain why my first code is wrong and why the second one works. Tom has done pull ups every day and recorded his results. He recorded each day's results in a new line, so that each line represents each day he has done pull ups. Create a program that takes n number as input and outputs the n-th days result (starting from 0). Sample Input 4 Sample Output Day 4, 9 pull ups #First code: file = open("/usercode/files/pull_ups.txt") n = int(input()) #your code goes here print(file.readlines(n)) file.close() #second code: file = open("/usercode/files/pull_ups.txt") n = int(input()) #your code goes here print(file.readlines()[n]) file.close()

4/12/2021 8:28:21 AM

Zhi Hong

2 Answers

New Answer

+3

Hi! file.readlines() put all lines from the file in a list. So in the second code you get the list value with index n. Some pseudo code (where >> means output and data_i means the lines in your file): myList = file.readlines() print(myList) >> [data_0, data_1, ...., data_k] print(myList[n]) >> data_n ... print(file.readlines()[n] >> data_n In your first code with file.readlines(n), you got a list where the number of characters n don’t exceeds the total number of characters in all the list values together. Suppose, continuing from the example above: len(myList[0]) = 5 len(myList[1] = 6 len(myList[2] = 4 Then: myList2 = file.readlies(8) print(myList2) >> [data0, data1] because: len(myList[0]) < 8 < len(myList[1] + 1

+1

Per Bratthammar ohh i get it now thank you so much