+ 3
How to solve the problem below?
A telephone directory has N lines on each page and each page has exactly C columns. An entry in any column has a name with the corresponding telephone number. On which page, column, and line is the Xth entry (name and number) present? (Assume that page, line, column numbers, and X all start from 1.) Without using loop
6 Respuestas
+ 3
Each page have N*C columns entries...
To know at wich page is the Xth entry, you need to do:
posP = X//(N*C)
and to know on wich position on this page:
pageX = X%(N*C)
well, now for the line and column:
posL = pageX//C
posC = pageX%C
That's with assuming page, line and column count all starts from 0... just add one to each at end for assuming all starts from 1:
posP++
posL++
posC++
+ 2
visph Thanks you but there is one more problem. Example a page has 16 entries( N*C = 16) and user input X=16 so posP = 1. Then it will be incremented so posP = 2. Actually, 16th is in page 1.🤔
+ 1
hint.
1. how many lines per page?
2. use // (floor division) and % (modulus).
+ 1
You should decrease user entry by one, as computation is more logical with indexes starting at zero (that's the reason why array/lists start from 0 index ^^)...
+ 1
Wow that's it! Before I decreased the entries 16 to 15 and it is wrong. I haven't think I can decrease the user entry. Such a good experience! Thanks you very much visph!😁
+ 1
x_int = int(input("which record to locate?: "))
#lines_int = int(input("lines per page?: "))
#column_int = int(input("columns per page?: "))
lines_int = 4 # line and column numbers are assigned here but can
column_int = 3 # also be assigned by input with the codes above
#finding the page that the record is on
record_page_int = ( (x_int - 1 ) // (lines_int*column_int) ) + 1
# converting x_int (record to locate) into a smaller number than the records number on
# one page for easier calculation
x_page_reduced = x_int - (record_page_int-1)*lines_int*column_int
pos_line = ((x_page_reduced -1) // column_int ) + 1
pos_column = x_page_reduced - (pos_line-1)*column_int
print("the record is on page",record_page_int,", line",pos_line,", column",pos_column)