a9302c
a9302c

Reputation: 241

Comparing items within tuple and returning index of item in Python

This is for a school assignment.

I am given a tuple representing a fictional subway line.

line = ('S Line', (('S2', 'Dairy Park'), ('S3', 'National Theatre'), ('S4', 'Commerce')))

line[0] is the line name ' S Line', line[1] represents all the different stations. Specifically, within each station, the first string 'S2' or 'S3' represents the station code, the the second 'Dairy Park' or 'Commerce' is the station name.

I need to define a function get_station_position(line, station_code) that takes in the subway line (line) and a station code ('S3') for example, and returns the station index, starting with 0. Keying in get_station_position(line, 'S3') should return me 1. If the station_code does not exist, like 'S5', I should be returned -1.

I know how to compare the station codes to know when it matches and return the code. Here's the code:

def get_station_by_name(line, station_name):
    for i in line[1]:
        if i[1] == station_name:
            return i
    print("None")

I am trying to find the index, and I thought it would be similar. Here's what I've tried:

def get_station_position(line, station_code):
    for i in line[1]:
        if i[0] == station_code:
            index = line.index(i)
            return index
    return int(-1)

But this code doesn't work. I get ValueError: tuple.index(x): x not in tuple. Can anyone provide some advice? Thank you for reading through this long question, I greatly appreciate it.

Upvotes: 1

Views: 296

Answers (1)

Gulzar
Gulzar

Reputation: 28014

line = ('S Line', (('S2', 'Dairy Park'), ('S3', 'National Theatre'), ('S4', 'Commerce')))

def get_station_position(line: tuple, station_code: str) -> int:
    for i, element in enumerate(line[1]):
        code, name = element
        if code == station_code:
            return i
    return -1

print(get_station_position(line, 'S3'))

This uses tuple unpacking, rather than .index for which you gave an argument which is not in the tuple.

Upvotes: 1

Related Questions