0

i have an array

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

how could I count the distance between the two strings? expected output 5.

5
  • Could any give value possibly exist more than once in your array? Commented Feb 13, 2022 at 2:45
  • no the same string wouldn't appear twice. Commented Feb 13, 2022 at 2:46
  • 1
    Are these stations along a railway / bus line and you want to calculate the number of stops between two of them? Just asking for some context. Commented Feb 13, 2022 at 9:58
  • 1
    How do you define "distance"? Levenshtein distance? Jaccard? Cosine? Commented Feb 13, 2022 at 14:48
  • I see 8 strings in your code. 6 are stored in an array, and two are stored in separate variables. What is the distance between strings anyway? Commented Feb 14, 2022 at 8:07

2 Answers 2

4

The first thing that comes to mind:

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

(line_one.find_index(user_input1) - line_one.find_index(user_input2)).abs
#=>  5
Sign up to request clarification or add additional context in comments.

1 Comment

@engineersmnky, always test!
0
line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

Code

p (line_one.index("flinders street")...line_one.index("glenferrie")).count

output

5

2 Comments

That seems the same as (line_one.index("flinders street")...line_one.index("glenferrie")).count, but more importantly, what if user_input1 = "glenferrie"; user_input2 = "flinders street"?
I don't think they would be checking something like you say. and I modified the answer according to your suggestion, that looks correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.