Skip to content

Commit f6fb1fe

Browse files
MIME Type
1 parent 9f03d92 commit f6fb1fe

File tree

7 files changed

+265
-109
lines changed

7 files changed

+265
-109
lines changed
Lines changed: 52 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,81 @@
1-
# Mime Type
1+
# MIME Type
22

3-
This is a solution to the "Mime Type" problem on [Codingame](https://www.codingame.com/training/easy/mime-type).
3+
## Description
44

5-
## Problem Description
5+
The task involves creating a program to determine the MIME type of files based on their names. This involves associating file extensions with MIME types. The program reads an association table with N elements and a list of Q file names to be analyzed. For each file name, the program identifies the extension by finding the substring after the last dot character. If the extension is found in the association table (case insensitive), it prints the corresponding MIME type. If the MIME type cannot be determined or the file has no extension, it outputs UNKNOWN. The program takes the number of elements in the table, the number of file names, the extension-MIME associations, and the file names as input, and outputs the corresponding MIME types or UNKNOWN.
66

7-
You are given a list of file names and their corresponding MIME types. You need to read a list of file names and determine the corresponding MIME type for each file name. If the MIME type cannot be determined, the program should output `UNKNOWN`.
7+
## Solution Overview
88

9-
The MIME type is determined by the file extension. The table of file extensions and their corresponding MIME types is given.
9+
To solve this problem, we need to map file extensions to their respective MIME types, and then analyze the file names to determine the MIME type by extracting the extension from the file name. If the extension matches one in our table (case insensitive), we return the MIME type; otherwise, we return `UNKNOWN`.
1010

11-
| Extension | MIME Type |
12-
|-----------|-----------|
13-
|html |text/html |
14-
|htm |text/html |
15-
|png |image/png |
16-
|jpeg |image/jpeg |
17-
|jpg |image/jpeg |
18-
|gif |image/gif |
19-
|bmp |image/bmp |
20-
|txt |text/plain|
21-
|pdf |application/pdf|
11+
### Explanation:
2212

23-
The file name may have multiple periods (.) in it, but the extension is always the substring that follows the last period.
13+
- We use a dictionary `mime_table` to store the file extensions and their corresponding MIME types, converting extensions to lowercase to handle case insensitivity.
14+
- For each file name, the program finds the last occurrence of a `.` in the string, and extracts the file extension if valid.
15+
- The MIME type is printed if the extension is found in the dictionary, otherwise `UNKNOWN` is printed.
2416

25-
## Solution
17+
### Edge Cases Handled:
2618

27-
The solution reads the the number of MIME types, number of file names and the file names. It stores the MIME types in a map with the extension as the key. Then it reads a list of file names and determines the corresponding MIME type by looking up the extension in the map. If the extension is not found, it outputs `UNKNOWN`.
19+
- Files with no extension or a dot at the end.
20+
- Extensions in different cases (e.g., `.TXT`, `.txt`, `.tXt` all map to the same MIME type).
21+
- Files whose extensions aren't in the provided table result in `UNKNOWN`.
2822

2923
## Example Input/Output
3024

31-
Input:
25+
**Input**
3226

3327
```
34-
4
35-
2
28+
3
29+
3
3630
html text/html
3731
png image/png
3832
gif image/gif
39-
txt text/plain
40-
file.html
41-
file.txt
33+
animated.gif
34+
portrait.png
35+
index.html
4236
```
4337

44-
Output:
38+
**Output**
4539

4640
```
41+
image/gif
42+
image/png
4743
text/html
48-
text/plain
4944
```
5045

51-
## Example Code
46+
## Code Example
5247

5348
```python
54-
# Read the number of elements in the association table
55-
n = int(input())
56-
57-
# Read the number of file names to be analyzed
58-
q = int(input())
59-
60-
# Create a dictionary to store the association table
61-
mime_types = {}
62-
63-
# Read the association table
64-
for _ in range(n):
65-
ext, mime = input().split()
66-
mime_types[ext.lower()] = mime
67-
68-
# Process each file name
69-
for _ in range(q):
70-
file_name = input().lower()
71-
72-
# Find the extension of the file
73-
if '.' in file_name:
74-
extension = file_name.split('.')[-1]
75-
if extension in mime_types:
76-
print(mime_types[extension])
49+
# Number of elements which make up the association table.
50+
N = int(input())
51+
52+
# Number of file names to be analyzed.
53+
Q = int(input())
54+
55+
mime_table = {}
56+
57+
# Reading the MIME type associations.
58+
for _ in range(N):
59+
ext, mime_type = input().split()
60+
mime_table[ext.lower()] = mime_type # Store extensions as lowercase for case-insensitivity.
61+
62+
# Processing each file name.
63+
for _ in range(Q):
64+
fname = input()
65+
66+
# Find the position of the last '.' in the file name.
67+
last_dot_index = fname.rfind('.')
68+
69+
# If there's a '.' and it isn't the last character, extract the extension.
70+
if last_dot_index != -1 and last_dot_index < len(fname) - 1:
71+
file_ext = fname[last_dot_index + 1:].lower() # Get the file extension and convert to lowercase.
72+
73+
# Check if the extension exists in the mime_table.
74+
if file_ext in mime_table:
75+
print(mime_table[file_ext]) # Output the MIME type.
7776
else:
78-
print("UNKNOWN")
77+
print('UNKNOWN') # Output UNKNOWN if extension not found.
7978
else:
80-
print("UNKNOWN")
79+
print('UNKNOWN') # Output UNKNOWN if no extension or '.' at the end.
8180

8281
```
Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,36 @@
1-
from typing import Dict
1+
def mime_type_puzzle():
2+
# Number of elements which make up the association table.
3+
N = int(input())
24

5+
# Number of file names to be analyzed.
6+
Q = int(input())
37

4-
def main():
5-
table: Dict[str, str] = {} # file extension => mime type
6-
nb_elements: int = int(input())
7-
nb_names: int = int(input())
8+
mime_table = {}
89

9-
for _ in range(nb_elements):
10-
extension, mime_type = input().split()
11-
table[extension.lower()] = mime_type
10+
# Reading the MIME type associations.
11+
for _ in range(N):
12+
ext, mime_type = input().split()
13+
mime_table[ext.lower()] = mime_type # Store extensions as lowercase for case-insensitivity.
1214

13-
for _ in range(nb_names):
14-
name: str = input().lower()
15-
dot_index: int = name.rfind(".")
16-
if dot_index == -1 or dot_index == len(name) - 1:
17-
print("UNKNOWN")
18-
else:
19-
extension: str = name[dot_index + 1 :]
20-
if extension in table:
21-
print(table[extension])
15+
# Processing each file name.
16+
for _ in range(Q):
17+
fname = input()
18+
19+
# Find the position of the last '.' in the file name.
20+
last_dot_index = fname.rfind('.')
21+
22+
# If there's a '.' and it isn't the last character, extract the extension.
23+
if last_dot_index != -1 and last_dot_index < len(fname) - 1:
24+
file_ext = fname[last_dot_index + 1:].lower() # Get the file extension and convert to lowercase.
25+
26+
# Check if the extension exists in the mime_table.
27+
if file_ext in mime_table:
28+
print(mime_table[file_ext]) # Output the MIME type.
2229
else:
23-
print("UNKNOWN")
30+
print('UNKNOWN') # Output UNKNOWN if extension not found.
31+
else:
32+
print('UNKNOWN') # Output UNKNOWN if no extension or '.' at the end.
2433

2534

2635
if __name__ == "__main__":
27-
main()
36+
mime_type_puzzle()

puzzles/python3/mime-type/test_mime_type.py

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from unittest.mock import patch, call
22

3-
from mime_type import main
3+
from mime_type import mime_type_puzzle
44

55

6-
def test_mime_type():
6+
def test_mime_type_with_unknown_extension():
77
# Set up
88
input_data = [
99
"3", # Number of elements
@@ -26,10 +26,71 @@ def test_mime_type():
2626
# Execute
2727
with patch("builtins.input", side_effect=input_data):
2828
with patch("builtins.print") as mocked_print:
29-
main()
29+
mime_type_puzzle()
3030

3131
# Assert
3232
mocked_print.assert_has_calls([call(output) for output in expected_output])
3333

3434

35-
test_mime_type()
35+
def test_mime_type_with_no_extension_or_dot_character():
36+
# Set up
37+
input_data = [
38+
"3", # Number of elements
39+
"4", # Number of names
40+
"html text/html", # Extension and mime type mapping
41+
"png image/png", # Extension and mime type mapping
42+
"gif image/gif", # Extension and mime type mapping
43+
"file", # Input name
44+
"image", # Input name
45+
"file.", # Input name with no extension
46+
"image.", # Input name with no extension
47+
]
48+
expected_output = [
49+
"UNKNOWN",
50+
"UNKNOWN",
51+
"UNKNOWN",
52+
"UNKNOWN",
53+
]
54+
55+
# Execute
56+
with patch("builtins.input", side_effect=input_data):
57+
with patch("builtins.print") as mocked_print:
58+
mime_type_puzzle()
59+
60+
# Assert
61+
mocked_print.assert_has_calls([call(output) for output in expected_output])
62+
63+
64+
def test_mime_type_with_different_cases():
65+
# Set up
66+
input_data = [
67+
"3", # Number of elements
68+
"4", # Number of names
69+
"txt text/plain", # Extension and mime type mapping
70+
"jpg image/jpeg", # Extension and mime type mapping
71+
"png image/png", # Extension and mime type mapping
72+
"file.TXT", # Input name
73+
"image.JPG", # Input name
74+
"file.tXt", # Input name
75+
"image.Png", # Input name
76+
]
77+
expected_output = [
78+
"text/plain",
79+
"image/jpeg",
80+
"text/plain",
81+
"image/png",
82+
]
83+
84+
# Execute
85+
with patch("builtins.input", side_effect=input_data):
86+
with patch("builtins.print") as mocked_print:
87+
mime_type_puzzle()
88+
89+
# Assert
90+
mocked_print.assert_has_calls([call(output) for output in expected_output])
91+
92+
93+
if __name__ == "__main__":
94+
test_mime_type_with_unknown_extension()
95+
test_mime_type_with_no_extension_or_dot_character()
96+
test_mime_type_with_different_cases()

puzzles/ts/mime-type/README.md

Lines changed: 84 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,89 @@
11
# MIME Type
22

3-
"MIME Type" is a beginner-level coding challenge available on the CodinGame platform. In this challenge, the player is given a list of file names and their corresponding MIME types, and is asked to determine the MIME type of a given file name.
3+
## Description
44

5-
A MIME type is a type of Internet standard that is used to indicate the type of data that a file contains. It is typically represented as a two-part identifier, with the first part indicating the type of data (such as "image" or "text") and the second part indicating the specific format or subtype (such as "jpeg" or "html").
5+
The task involves creating a program to determine the MIME type of files based on their names. This involves associating file extensions with MIME types. The program reads an association table with N elements and a list of Q file names to be analyzed. For each file name, the program identifies the extension by finding the substring after the last dot character. If the extension is found in the association table (case insensitive), it prints the corresponding MIME type. If the MIME type cannot be determined or the file has no extension, it outputs UNKNOWN. The program takes the number of elements in the table, the number of file names, the extension-MIME associations, and the file names as input, and outputs the corresponding MIME types or UNKNOWN.
66

7-
The challenge consists of writing a program that takes as input a list of file names and their corresponding MIME types, as well as the name of a file, and outputs the corresponding MIME type for that file. If the file type is not known, the program should output "UNKNOWN".
7+
## Solution Overview
88

9-
The challenge is designed to help players learn and practice programming skills such as string manipulation, conditional statements, and data structures. It is a fun and engaging way to improve programming skills while solving a challenging and entertaining puzzle.
9+
To solve this problem, we need to map file extensions to their respective MIME types, and then analyze the file names to determine the MIME type by extracting the extension from the file name. If the extension matches one in our table (case insensitive), we return the MIME type; otherwise, we return `UNKNOWN`.
10+
11+
### Explanation:
12+
13+
1. **Input Parsing:**
14+
- The number of MIME type associations (`N`) and the number of file names to analyze (`Q`) are read first.
15+
- Then, the MIME type associations are stored in an object (`mimeTable`), where the key is the file extension and the value is the MIME type. Extensions are stored in lowercase to ensure case insensitivity.
16+
17+
2. **File Name Analysis:**
18+
- For each file name, we determine if it has a valid extension by checking for the last occurrence of a `.` (dot) character.
19+
- If the file has an extension (i.e., the `.` is not the last character), we extract the extension, convert it to lowercase, and look it up in the MIME type table.
20+
- If the extension exists in the table, the corresponding MIME type is printed; otherwise, `UNKNOWN` is printed.
21+
22+
### Edge Cases Handled:
23+
24+
- Files with no extension or a dot at the end.
25+
- Extensions in different cases (e.g., `.TXT`, `.txt`, `.tXt` all map to the same MIME type).
26+
- Files whose extensions aren't in the provided table result in `UNKNOWN`.
27+
28+
## Example Input/Output
29+
30+
**Input**
31+
32+
```
33+
3
34+
3
35+
html text/html
36+
png image/png
37+
gif image/gif
38+
animated.gif
39+
portrait.png
40+
index.html
41+
```
42+
43+
**Output**
44+
45+
```
46+
image/gif
47+
image/png
48+
text/html
49+
```
50+
51+
## Code Example
52+
53+
```typescript
54+
const N: number = parseInt(readline()); // Number of elements which make up the association table.
55+
const Q: number = parseInt(readline()); // Number Q of file names to be analyzed.
56+
57+
const mimeTable: { [key: string]: string } = {};
58+
59+
// Reading the MIME type associations.
60+
for (let i = 0; i < N; i++) {
61+
const inputs: string[] = readline().split(' ');
62+
const EXT: string = inputs[0].toLowerCase(); // file extension (converted to lowercase for case-insensitivity)
63+
const MT: string = inputs[1]; // MIME type
64+
mimeTable[EXT] = MT; // Store the MIME type with the extension as the key
65+
}
66+
67+
// Processing each file name.
68+
for (let i = 0; i < Q; i++) {
69+
const FNAME: string = readline();
70+
71+
// Find the position of the last '.' in the file name.
72+
const lastDotIndex = FNAME.lastIndexOf('.');
73+
74+
// If there's a '.' and it isn't the last character, extract the extension.
75+
if (lastDotIndex !== -1 && lastDotIndex < FNAME.length - 1) {
76+
const fileExt = FNAME.slice(lastDotIndex + 1).toLowerCase(); // Get the file extension and convert to lowercase
77+
78+
// Check if the extension exists in the mimeTable.
79+
if (mimeTable.hasOwnProperty(fileExt)) {
80+
console.log(mimeTable[fileExt]); // Output the MIME type
81+
} else {
82+
console.log('UNKNOWN'); // Output UNKNOWN if extension not found
83+
}
84+
} else {
85+
console.log('UNKNOWN'); // Output UNKNOWN if no extension or '.' at the end
86+
}
87+
}
88+
89+
```

puzzles/ts/mime-type/mime-type.ts

Lines changed: 0 additions & 23 deletions
This file was deleted.

0 commit comments

Comments
 (0)