+ 1
Optimize code
Hi, I did and passed the book titles quiz within Python Core with this code below but I feel there should be a cleaner or more nicer way to solve it. Each line of the txt file contains a movie and I need to get the initial and the length of the movie. if you can find a nicer way. Perhaphs I shoud use readline()? thanks: file = open("/usercode/files/books.txt", "r") #your code goes here line=list(file) l=0 for w in line: if (w.find("\n")>0): l=len(w)-1 print(w[0]+str(l)) else: l=len(w) print(w[0]+str(l)) file.close()
9 Réponses
+ 9
Ruben, Mirielle,
when iterating over a file object (textIOwrapper) we dont need to call readlines(). see following sample.
this code has an improved readability:
with open('/usercode/files/books.txt', 'r') as file:
res = [f'{n[0]}{len(n.rstrip())}' for n in file]
print(*res,sep='\n')
an other approach is:
for item in open('/usercode/files/books.txt', 'r').read().split('\n'):
print(item[0], len(item), sep='')
since there is no explicitly difinition of a file object in this last sample, we can not explicitly close this file. i suppose this is done automatically after iteration is done or when the program is getting terminated.
https://code.sololearn.com/c34lASo3Xfa3/?ref=app
+ 3
You mean in any other way:
You can use replace method as
w = w.replace ("\n", "")
No need if part then.
+ 3
Another's way you can use strip() method.
w = w.strip()
also : w[-1] == "\n" instead of find()
You're welcome..
+ 2
Thanks again, yes, this strip() method is helpful too
+ 1
Sorry, I meant books instead of movies. I struggled with the last line of the txt file since it did not contain a new line character...
+ 1
Thanks a lot Mirielle, so helpful, you really optimized it indeed
+ 1
Thanks a lot Lothar! Very helpful
0
Thanks Jayakrishna, very helpful! I dont need the if part anymore using the replace()