Electric
Electric

Reputation: 537

Getting closest element from a list of list upon input

I have a text file containing something like a game of guessing digits where the first column is just a unique id, second and third column are range for the guess and fourth is a group type:

a:6.5:10.2:G1
b:2.4:11.7:G2
c:3.1:9.7:G1
d:4.6:8.7:G3

The user will be prompt to input two tries, for example:

3.1 : 9.9 : 3.2 : 9.8

where the first two will be the first try, and the third and forth would be the second try. Upon the input as of above, the code will make a comparison between the first try and the second try with the content in the text file.

Example:

The first try would be 3.1 : 9.9 and proceed to compare with content in the text file. The second try 3.2 : 9.8 would also be compared and producing the output of closest range to the user input which would be:

output = 3.1 , 9.7 (from the text file, without the id and type)

Here's what I've tried. For a start I created two list since there are only two sets of digit per row in the file and user has four sets of digits which i assume would be convenient if i split the input into two each in one list to be compared.

guess = input("Enter your guess:")  #Ex: 3.1:9.9:3.2:9.8
List1 = []                          # [3.1,9.9]
List2 = []                          # [3.2,9.8]
separateStr = guess.split(':')
floatInput = [float(i) for i in separateStr]

List1,List2 = floatInput[:2],floatInput[2:]

openFile = open('__.txt')
table = []                  #Created a list to contain the contents
for line in openFile:
    contents = line.strip().split(':')
    table.append(contents)

def getClosest(l):
    for i in range(....
    .
    .

I wasn't able to figure out the function for the closest range as I'm assuming whether it is possible if the two list is able to compare with the table containing the content of the file? My method might be wrong so I want to seek advice for this.

Upvotes: 2

Views: 55

Answers (1)

Ma0
Ma0

Reputation: 15204

I did not test it because i am lazy atm but it should be fine.

def get_closest(test, my_table):
    min_dist = 10e5
    pos = None
    for i, data in enumerate(my_table):
        dist = ((test[0] - data[0])**2 + (test[1] - data[1])**2)**0.5  # euclidean norm
        if dist < min_dist:
            pos = (i, data)
            min_dist = dist
    return pos

openFile = open('__.txt')
table = []
for line in openFile:
    table.append(line.strip().split(':')[1:3])  # only the numbers

user_input = input("Enter your guess:")  # Ex: 3.1:9.9:3.2:9.8
floatInput = list(map(float, user_input.split(':')))
guesses = [floatInput[:2], floatInput[2:]]
for guess in guesses:
    winner = get_closest(guess, table)
    print(winner[1])

Notes:

  • You are using a weird format for the user input. I would go with something more intuitive like 3.1,9.9;3.2,9.8 (distinguish between the middle and rest separators)

Upvotes: 1

Related Questions