Can you hell me with this problem? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can you hell me with this 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. file = open("/usercode/files/books.txt", "r") #your code goes here file.close()

26th Sep 2022, 6:03 PM
Ökkeş Sefa Coşkun
Ökkeş Sefa Coşkun - avatar
3 Answers
+ 2
Step 1: Objective You are looking to print out the first element + the length of the characters (spaces included). x[0] + str(len(x)). Turn num into string "H" + "12" Step 2: Identify Problem When you import a file, you read the text file using file.read() it appears that file is imported as a string. You can test this: print(type(file.read())) Now you see the string has unwanted \n inside the string. If you read about file handling, you would know that every enter button in the text file creates a "\n" when you import Step 3: Solve Problem Your options are limited but very easy. Lets use string split method. Because our file is a string we want to use a string function. Let's first name our string text = file.read() Now we split string. my_list = text.split("\n") Split turns str to list and removes unwanted characters as separator. Test by printing my_list Step 4: Complete Objective for i in my_list: print(i[0] + str(len(i))) Done. Read on string.replace() for more ways to solve problem!
27th Sep 2022, 12:21 AM
The Warlord
The Warlord - avatar
+ 3
Your first step should be to break down the big problem into smaller components. What information do you have? How can you manipulate it to get the result you want? What are the elements you want to extract or exclude? If you have a specific question about process, please ask that, but this is the general advice that will help with this and any other problem.
26th Sep 2022, 6:34 PM
Tyler McKechnie
+ 1
This formula helped me and will help you! Objective --> Problem --> Test --> Can Solve (Yes?) --> Solve Objective --> Problem --> Test --> Can Solve (No?) --> Research --> Solve
27th Sep 2022, 12:38 AM
The Warlord
The Warlord - avatar