+ 11

Simpler way? [SOLVED]

I just completed a code coach problem but I feel like I am over complicating it. Is there a simpler way to accomplish the task than how I have? PROBLEM: You have been asked to make a special book categorization program, which assigns each book a special code based on its title. The code is equal to the first letter of the book, followed by the number of characters in the title. For example, for the book "Harry Potter", the code would be: H12, as it contains 12 characters (including the space). You are provided a books.txt file, which includes the book titles, each one written on a separate line. Read the title one by one and output the code for each book on a separate line. For example, if the books.txt file contains: Some book Another book Your program should output: S9 A12 Recall the readlines() method, which returns a list containing the lines of the file. Also, remember that all lines, except the last one, contain a \n at the end, which should not be included in the character count. MY SOLUTION: file = open("/usercode/files/books.txt", "r") #your code goes here fileLines = [] for lines in file: fileLines.append(lines) length = 1 for n in fileLines: if length == len(fileLines): print(n[0] + str(len(n))) else: print(n[0] + str(len(n)-1)) length += 1 file.close() I am using len(n) - 1 because there is an extra space (“ “) on all of the lines except for the last line. I opted not to use the readlines() method, but maybe I should have? Thank you for the help!

27th Oct 2020, 7:36 PM
Richard Villarreal
Richard Villarreal - avatar
74 ответов
+ 45
A short way to do it is like this: file = open("/usercode/files/books.txt", "r") for line in file.readlines(): print(f'{line[0]}{len(line.strip())}') file.close()
27th Oct 2020, 8:56 PM
Lothar
Lothar - avatar
+ 21
Yup I did this way ,just used readlines() similar to what your fileLines list holds after looping over lines in file, and then checked if last character in line contains "\n" or not , for lines in file.readlines(): if lines[-1]=="\n": print(lines[0]+str(len(lines)-1)) else: print(lines[0]+str(len(lines)))
27th Oct 2020, 7:58 PM
Abhay
Abhay - avatar
+ 21
file = open("/usercode/files/books.txt", "r") for x in file.readlines(): x = x.strip('\n') a = len(x) b = x[0] print(str(b) + str(a)) file.close()
19th Jan 2021, 6:31 PM
Chris Wiseman
Chris Wiseman - avatar
+ 10
Instead of dealing with \n we can simply remove it with the help of strip() file = open("/usercode/files/books.txt", "r") #your code goes here books = file.readlines() books = [x.strip() for x in books] for book in books: print(book[0]+str(len(book))) file.close() Hope It Helps You 😊
27th Oct 2020, 8:06 PM
Hacker Badshah
Hacker Badshah - avatar
+ 10
Tharyabha Manek - you are kidding us, right? sorry for my comment. the code you did is working. but only exactly for the file as it is. As soon as we have moore books or less books it will crash. this is called hard-coded. I am real sure that you are able to do it in a way, that is working for all number of books in the file.
20th Dec 2020, 6:28 PM
Lothar
Lothar - avatar
+ 7
Usually there are many ways to solve a single problem. Simpler way doesn't always mean more clear. Choose the one that works for you ✌️
29th Oct 2020, 2:20 PM
Dual Core
Dual Core - avatar
+ 7
here is my attempt for this exercise: for line in open("/usercode/files/books.txt", "r"): print(f'{line[0]}{len(line.strip())}')
6th Aug 2021, 9:26 AM
Lothar
Lothar - avatar
+ 6
Richard Villarreal strip function just remove trailing and leading characters. Like "hello World".strip("hed") >>>llo Worl #h,e,d are removed from starting and ending By default strip function remove whitespace which includes \n(newline) "Harry Potter\n".strip() >>>Harry Potter Hope It Helps You 😊
27th Oct 2020, 8:18 PM
Hacker Badshah
Hacker Badshah - avatar
+ 5
file = open("/usercode/files/books.txt", "r") for line in file: line = line.strip("\n") print(line[0] + str(len(line))) file.close() This one is the easiest
27th Feb 2021, 8:25 AM
Ananya Sarkar
Ananya Sarkar - avatar
27th Oct 2020, 8:05 PM
Abhay
Abhay - avatar
+ 4
Here was my solution, for posterity ;) file = open("/usercode/files/books.txt", "r") #your code goes here listed = file.readlines() relisted = [] for element in listed: relisted.append(element.strip()) for line in relisted: print(line[0] + str(len(line))) file.close()
16th Jan 2021, 7:02 PM
Alex
+ 3
file = open("/usercode/files/books.txt", "r") #your code goes here for line in file: print(line[0]+ str(len(line.strip('\n')))) file.close()
2nd Mar 2021, 11:58 AM
Godwin Emerald
Godwin Emerald - avatar
+ 3
file = open("/usercode/files/books.txt", "r") for line in file: ti=line.replace('\n','') count=len(title) if t in line: print(f'{title[0]}{count}') file.close()
3rd Aug 2021, 7:56 AM
Peyman Daei Rezaei
Peyman Daei Rezaei - avatar
+ 3
Виктор Дмитриевич , sorry, i should have given more descriptions to my code snippet. the new-line sequence is not stripped by default. we are reading the content of the file in a for loop line by line, and store this data temporarly in a variable `line`. this variable is used inside the print() statement together with the method strip(). the result of this expression is the current line, but without any trailing new-line sequences. this is now used as argument for getting the length of the string.
20th Jul 2022, 8:38 PM
Lothar
Lothar - avatar
+ 2
Awesome! Thank you for the reply. I have not seen a negative number in the brackets before and just want to make sure I understand. lines[-1] checks the last character of the current line?
27th Oct 2020, 8:04 PM
Richard Villarreal
Richard Villarreal - avatar
+ 2
# here input - for the task not needed xw = ["The Joy of JavaScript\n","Building Native Web Components\n","Practical Machine Learning in JavaScript"] #input can also be read in with the keyboard as follows #xw = [] #while True: #try: #xw.append(input()+'\n') #except: #xw[len(xw)-1] = xw[len(xw)-1][0:len(xw[len(xw)-1])-1] #break # writing the books.txt - for the task not needed file = open("/usercode/files/books.txt", "w") file.writelines(xw) file.close() # reading the books.txt file = open("/usercode/files/books.txt", "r") xr = file.readlines() print(xr) # prints the book's array - for the task not needed # Coding of them titlels: # for example, for the book "Some book", # the code would be: S9, # as it contains 9 characters (including the space). for i in range(len(xr)-1): print(xr[i][0]+str(len(xr[i])-1)) print(xr[len(xr)-1][0]+str(len(xr[len(xr)-1]))) file.close()
27th Oct 2020, 9:21 PM
JaScript
JaScript - avatar
+ 2
file = open("/usercode/files/books.txt", "r") f=file.readlines() for i in f: if "\n" in i: print(i[0]+str(len(i)-1)) else: print(i[0]+str(len(i))) file.close() it can also coded as above
3rd May 2022, 12:02 PM
Kamarthi Varsha
Kamarthi Varsha - avatar
+ 2
file = open("/usercode/files/books.txt", "r") #your code goes here for book in file: print(book[0].upper()+str(len(book.strip()))) file.close()
13th Jan 2023, 2:55 PM
dhinesh Kumar
dhinesh Kumar - avatar
+ 2
Fill in the blanks to iterate over the string "str" and output each character.
4th Feb 2023, 4:10 AM
Siddharth B
Siddharth B - avatar
+ 1
VB s kbkzb. Kgs pzvso l. Dk bsbvs nviz qox dkhnz kz nnj ???????
28th Oct 2020, 1:58 PM
Vishal Boymusical
Vishal Boymusical - avatar