Assigning a input on a line to its line number?

2024/10/5 21:17:08

I was having a go at the following problem from the AIO (Australian Informatics Olympiad) Training Problems Site (Question in Italics and specifics in bold, my attempt below):

The Problem

Encyclopaedia

Input File: encyin.txt

Output File: encyout.txt

Time Limit: 1 second

Once again it is quiz night at the My Very First Encyclopedia Appreciation Society. For week after week, you have turned up to these quizzes, deftly answering question after question about zoo animals and days of the week, only for someone else to answer all the obscure bonus-round questions at the end, snatching first place and leaving you with nothing but a 'Nice Try!' sticker.

Dejected and disheartened, you are sitting at home musing upon your past failures, when a thought occurs to you. Could it be...? Riffling through months of angrily scribbled notes, you confirm your sneaking suspicion - the bonus questions follow a super-simple pattern! Your heart skips a beat. Every question in every bonus round of every quiz you've sat through has been phrased in the form: "How many words are there on page x of the My Very First Encyclopedia?" Normally you would consider that a little unlikely, even contrived, but not today - today you have a Mars bar to win.

With infinite care you compile a list of page numbers and their corresponding word counts. Others in your place might try to memorise the list, but no, your plan is far more hi-tech: first, you will write a program that can answer these questions for you; then, you will sneak your trusty laptop into the quiz, and proceed to blitz the competition.

All that's left is for you to actually write the program. The task seems simple: it has to take your list of numbers and tonight's bonus questions, and - quietly - print out the correct answers for you.

Input

The first line of the input will be of the form n q, where n is the number of pages in the encyclopedia, and q is the number of questions to be answered. (1 <= n, q <= 10,000)

Following this will be n lines, each describing a single page. The ith of these lines will contain the single integer pi, the number of words on page i. (0 <= pi <= 2,000,000,000)

Following this will be q lines, each describing a single question. Each of these lines will contain a single integer x, representing the question, "How many words are there on page x?" (1 <= x <= n)

Output

For each question, your program should write a single line of output. This line should contain a single integer, the number of words on the requested page.

My Attempt

I was able to write up the start of the code easily enough:

file = open("encyin.txt", "r")
pages, questions = file.readline().split()
pages = int(pages)
questions = int(questions)
for i in range (0, int(pages)):words = int(file.readline())

But I'm not sure what to do next. How do I assign each number given to a line? For example, the ith line has an integer describing the number of words on page i, so how would I assign this value to page i?

Thanks - I am writing in python.

Answer

The first thing I notice is that you are iterating through i in range(0, int(pages)), however, the pages only start on line 1 (line 0 consists of n & q).

So your for loop should like more like (you also want to do +1 because you want to count the last page, otherwise python only goes 'uptil but not including'):

for i in range (1, pages + 1):words = int(file.readline().strip())

Here, we are putting the .strip() function so that we don't get an error while converting this to an int. By default, text files have \n (enter characters) at the end of each line and python doesn't understand the meaning of int("5\n"). The strip() function helps get rid of the enter character and any trailing 'whitespaces'.

Now, you would want to store the number of words per line somewhere, and for this you can either use a dictionary (https://www.w3schools.com/python/python_dictionaries.asp), or a list.

List indices start at 0, but the line with the number of words per page starts at 1 and even though you could get away with using lists, dictionaries would be more intuitive.

words_per_page = {}

You can look at the link I have provided to understand how these work. We can then add the words to the dictionary:

for i in range (1, int(pages) + 1):number_of_words = int(file.readline().strip())words_per_page[i] = number_of_words

Then, you can iterate through each line with the questions. Here, we start the for loop at the line just after the line where the number of words per page ends:

all_questions = []
for question_index in range(pages + 2, 1 + pages + questions):all_questions.append(file.readline().strip())

From this, you will get 1 dictionary of the page number as the key and words per page as the value and a list with all the questions. Then you could iterate through these and get the number of words in the pages:

for page_number in all_questions:no_of_words = words_per_page[int(page_number)]# You can then store this variable somewhere or write to a text file

Now, I haven't tested any of this code, but the idea behind everything is the same. If you do get any errors, make sure to leave a comment.

https://en.xdnf.cn/q/119538.html

Related Q&A

Create a new list according to item value

I have a list like below. [T46, T43, R45, R44, B46, B43, L45, L44, C46, C45]where I want to group according to int value:[id][ , , , , ] # AREA PATTERN [Top, Right, Bottom, Left, Center][46][1,0,1…

Concatenating many time and date columns

I have many date and time column pairs (around 15 each) that share the same prefix, ie. SH or DEL. The columns are all of dtype object, ie. string. All the columns belong to the same Dataframe. Here is…

Python with ICS files and CSV [duplicate]

This question already has answers here:Parsing files (ics/ icalendar) using Python(6 answers)Closed 5 years ago.one friend ask me some help on a personnal project, but I have to admit my skills in Pyth…

loading my data in numpy genfromtxt get errors

I have my data file contain 7500 lines with :Y1C 1.53 -0.06 0.58 0.52 0.42 0.16 0.79 -0.6 -0.3 -0.78 -0.14 0.38 0.34 0.23 0.26 -1.8 -0.1 -0.17 0.3…

Install dlib with cuda support ubuntu 18.04

I have CUDA 9.0 and CUDNN 7.1 installed on Ubuntu 18.04(Linux mint 19). Tensorflow-gpu works fine on GPU(GTX 1080ti).Now i am trying to build dlib with CUDA support:sudo python3 setup.py install --yes …

View 3 dimensional Numpy array in Matplotlib and taking arguments from Keyboard or mouse

I have 3 dimensional data say (5,100,100). Now I would like to see them slice by slice upon hitting the down arrow button.

python default argument syntax error

I just wrote a small text class in python for a game written using pygame and for some reason my default arguments arent working. I tried looking at the python documentation to see if that might give m…

Variable not defined (Python)

FlightType=input("Which flight would you like to fly? Type 2 Seater, 4 Seater, or Historic.") # No validation included for the inputFlightLen=input("Would you like to book the 30 minu…

PyGame: draw.rect() has invalid parameters

Im trying to learn mouse events with PyGame, and Im trying to draw a box wherever the user clicks. Im setting a variable equal to pygame.mouse.get_pos(), and calling individual tuple members according …

Cant press enter in selenium2library

Im trying to make a test that will open Facebook, log in and search something. However Im having trouble getting Facebook to search. Selenium types whatever it needs in the search bar, but I cant find …