0% found this document useful (0 votes)
34 views27 pages

Confusion Matrix Analysis

Uploaded by

sanjaymani2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views27 pages

Confusion Matrix Analysis

Uploaded by

sanjaymani2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Confusion matrix analysis

Which metric is best to analyze true positives, false positives, false negatives, and true
negatives?

Select ane correct answer from the following

R-squared

ROC Curve

Confusion Matrix

Accuracy

The correct answer is Confusion Matrix ✅


A confusion matrix directly displays true positives, false positives, false negatives, and true
negatives, making it the best tool to analyze them.

What is the result of this code?

f = open('file.txt','r')

print(f.readline())

Select one correct answer from the following

Prints Tue txt

Prints entire filo

Prints the first line of filet

Error

The correct answer is: Prints the first line of file ✅


f.readline() reads only the first line from the file.

What will be the output of the given code?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/27
Import numpy as np

n1= [[1, 2], [4, 5]] n2 = [[6, 7], [9, 3]] prod = np.dot(n1, n2)

print(prod)

Select one correct answer from the following

None of the above.

[[69,43]

[24 13]]

[[24 13 69 43]]

[[24 13]

[6943]]

Let's calculate step-by-step.

We have:

python

import numpy as np

n1 = [[1, 2], [4, 5]]


n2 = [[6, 7], [9, 3]]
prod = np.dot(n1, n2)

print(prod)

Matrix multiplication:

1 2 6 7
n1 = [ ], n2 = [ ]
4 5 9 3
​ ​ ​ ​

First row × first column: (1 × 6) + (2 × 9)


= 6 + 18 = 24
First row × second column: (1 × 7) + (2 × 3) = 7 + 6 = 13
Second row × first column: (4 × 6) + (5 × 9) = 24 + 45 = 69
Second row × second column: (4 × 7) + (5 × 3) = 28 + 15 = 43

Result:

24 13
[ ]
69 43
​ ​

✅ Correct answer: [[24 13] [69 43]]


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/27
What does myList[::-1] do?

Select one correct answer from the following

Copies myList

Removes the last element from myList

Reverses myList

Sorts myList in descending order

The correct answer is: Reverses myList ✅


myList[::-1] uses slicing with a step of -1, which returns a reversed copy of the list.

mylist [1.2.3

myList(1) 4

print(myList)

Select one correct answer from the following

(14.3

[4.2.3)

[123]

Error

Your code seems to have syntax errors as written, but if we interpret it correctly as:

python

myList = [1, 2, 3]
myList[1] = 4
print(myList)

Explanation:

myList[1] = 4 changes the element at index 1 (which was 2) to 4.

The list becomes [1, 4, 3].

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/27
✅ Correct answer: [1, 4, 3]

How can you organize routes modularly in FastAPI?

Select one correct answer from the following

Through a single app instance only

By splitting routes into APiRouter instances

Using the Grouter.route() decorator

Using Django-style views

The correct answer is: By splitting routes into APIRouter instances ✅


In FastAPI, you can organize routes modularly by creating multiple APIRouter objects for different parts
of your application and then including them in the main app.

Question-4

Mary for

What will be the correct output of the given code snippet? "import pandas as pd fruit =
pd.Series(['Mango', 'Apple']) color - [Yellow', 'Red'] df = pd.DataFrame(colour, index fruit,
columns=['Color']) print(df)

04

Select one correct answer from the following

10

Color

Apple Red

Mango Yellow

Mango Color

Apple Red

Yellow

None of the above

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/27
Color

Mango Yellow

Apple Red

Let’s break it down carefully — the provided code has small typos, so I’ll rewrite it in a valid form:

python

import pandas as pd

fruit = pd.Series(['Mango', 'Apple'])


color = ['Yellow', 'Red']

df = pd.DataFrame(color, index=fruit, columns=['Color'])


print(df)

Step-by-step:

fruit is a Series:

vbnet

0 Mango
1 Apple
dtype: object

color is a list:

css

['Yellow', 'Red']

pd.DataFrame(color, index=fruit, columns=['Color'])


Creates a DataFrame with:

Data = color list ('Yellow', 'Red')


Index = values from fruit ('Mango', 'Apple')
Columns = ['Color']

Output will be:

mathematica

Color
Mango Yellow
Apple Red

✅ Correct answer: Color → Mango Yellow, Apple Red


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/27
In LangChain, agents rely on a model's output to decide next steps dynamically. What format do
these outputs follow in a typical agent loop?

Select one correct answer from the following

SOL query

Static plan of APis

Chain of Observations and Actions

JSON file

The correct answer is: Chain of Observations and Actions ✅


In LangChain, agents work in loops where each step consists of:

1. Observation – result from the last action.

2. Action – the next tool or step to execute based on the observation.

This cycle continues until the agent decides to stop.

In an embedding vector, closer vectors typically represent

Select one correct answer from the following

Semantically similar content

Random associations

Unrelated content

Higher token counts

The correct answer is: Semantically similar content ✅


In embedding space, vectors that are closer together usually represent content with similar meaning or
context.

In Lang Chain, which combination is commonly used in retrieval chains for RAG systems?

Select one correct answer from the following

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/27
Retriever Agent OutputParser

Action Agent Prompt Template

Retriever+LLM+Prompt Template

Memory Agent OutputParser

The correct answer is: Retriever + LLM + Prompt Template ✅


In Retrieval-Augmented Generation (RAG) systems with LangChain, this combination is common:

Retriever → fetches relevant documents from a knowledge source.

LLM → generates responses using retrieved context.

Prompt Template → structures how the context and query are passed to the LLM.

Question-10

DM

What is a valid reason to declare an endpoint as async def in FastAPI?

Select one correct answer from the following

To improve CPU-bound computations

To allow concurrent I/O operations like API calls or DB queries

To reduce Pydantic model validation time

To support synchronous file writes

The correct answer is: To allow concurrent I/O operations like API calls or DB queries ✅
In FastAPI, declaring an endpoint with async def is beneficial when your code performs I/O-bound tasks
(e.g., database queries, external API requests, file reads) so other requests can be handled while waiting
for these operations to complete.

What header does CORS primarily control?

Select one correct answer from the following

Content-Type

Access-Control-Allow-Origin

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/27
Cache-Control

Authorization

The correct answer is: Access-Control-Allow-Origin ✅


CORS (Cross-Origin Resource Sharing) primarily uses the Access-Control-Allow-Origin header to specify
which origins are allowed to access resources from a server.

What will the following function return:

def example():

return 5+5

Select one correct answer from the following

None

5+5

OD

10

The correct answer is: 10 ✅


return 5+5 evaluates the expression 5+5 first (which is 10) and then returns that value.

What will be the correct output of the following code? "Import numpy as np a = np.array([[4, 3],
[4, 6]]) b = np.array([[1,2], [4, 5]]) c = np.sum(a - b)

print(c)

Select one correct answer from the following

29

None of the above

[[55]

[811]]

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/27
[[10]. [19]]

Let’s calculate step-by-step.


Given code (with correct syntax):

python

import numpy as np

a = np.array([[4, 3], [4, 6]])


b = np.array([[1, 2], [4, 5]])
c = np.sum(a - b)

print(c)

Step 1: Subtract arrays element-wise

4−1 3−2 3 1
a−b=[ ]=[ ]
4−4 6−5 0 1
​ ​ ​ ​

Step 2: Sum all elements

3+1+0+1=5

✅ Correct output: 5
Since 5 is not in your listed options, the right choice here is None of the above.

import numpy as np

a = np.array([[4, 3], [4, 6]])


b = np.array([[1, 2], [4, 5]])
c = np.sum(a + b)

print(c)

Let’s calculate step-by-step.


Step 1: Add the arrays element-wise

4+1 3+2 5 5
a+b=[ ]=[ ]
4+4 6+5 8 11
​ ​ ​ ​

Step 2: Sum all elements

5 + 5 + 8 + 11 = 29

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/27
✅ Output: 29

F1 Score is especially useful when:

Select one correct answer from the following

Precision and recall are both important

Only precision matters

Classes are perfectly balanced

Only accuracy matters

< Previous Question

The correct answer is: Precision and recall are both important ✅
The F1 Score is the harmonic mean of precision and recall, making it especially useful when you need a
balance between the two — particularly in cases with imbalanced classes.

What is the difference between saguments and parameters in Pythors Hunctions?

Select one correct acower from the following

Based on data type

Parameters define, arguments cat

Arguments define, parameters cat

No-difference

The correct answer is: Parameters define, arguments call ✅


Parameters → variables listed in the function definition.

Arguments → actual values passed to the function when calling it.

Which of the following limits the length of output tokens from OpenAI APIs, potentially
truncating long responses?

Select one correct answer from the following

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/27
temperature

top p

frequency penalty

max tokens

The correct answer is: max tokens ✅


max_tokens in OpenAI APIs sets the maximum length of the generated output, and if the model reaches
this limit, the response may be truncated.

Find the mistake:

d = {'a': 1, 'b': 2}

print(d.get('c', 'Not Found'))

Select one correct answer from the following

No error

Syntax error in the dictionary

get() method used incorrectly

Key 'c' doesn't exist

The correct answer is: No error ✅


Explanation:

d.get('c', 'Not Found') safely tries to access key 'c'.


Since 'c' is not in the dictionary, it returns the default value "Not Found" without raising an error.

Question-23

DMark

Why are Approximate Nearest Neighbor (ANN) algorithms preferred over exact searches in
vector databases?

Select one correct answer from the following

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/27
They provide perfect accuracy

They avoid the need for embeddings.

They require less storage

They significantly improve speed in high-dimensional spaces with acceptable accuracy tradeoffs

The correct answer is: They significantly improve speed in high-dimensional spaces with acceptable
accuracy tradeoffs ✅
Approximate Nearest Neighbor (ANN) algorithms trade a small amount of accuracy for much faster
search times in large, high-dimensional vector databases, making them ideal for embeddings-based
retrieval.

The transformer decoder is primarily responsible for

Select one correct answer from the following

Token classification only

Sentence segmentation

Text understanding

Text generation in sequence-to-sequence tasks

The correct answer is: Text generation in sequence-to-sequence tasks ✅


In transformer architectures, the decoder takes encoded representations and generates output
sequences token-by-token, making it key for tasks like translation, summarization, and other text
generation tasks.

Which is NOT a typical step in the Transform phase of ETL?

Select one correct answer from the following

Data cleaning

Data extraction from APis

Data aggregation

Data enrichment

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/27
The correct answer is: Data extraction from APIs ✅
Reason:

Transform phase involves tasks like data cleaning, aggregation, and enrichment.

Data extraction from APIs happens in the Extract phase, not in Transform.

Which of the following can help reduce overfitting?

Select one correct answer from the following

Applying techniques like dropout or cross-validation

Reducing training data size

Removing regularization

Using a more complex model

The correct answer is: Applying techniques like dropout or cross-validation ✅


These methods help the model generalize better and prevent it from memorizing the training data,
thereby reducing overfitting.

Which of the following plots is best suited to understand distribution of a single numerical
variable?

Select one correct answer from the following

Line chart

Bar chart

Histogram

Scatter plot

The correct answer is: Histogram ✅


A histogram is best for visualizing the distribution of a single numerical variable by grouping data into
bins and showing the frequency of values in each bin.

What will be the correct output of the given code snippet? "import numpy as np print(np.fuil
(1.2), 5))"

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/27
Select one correct answer from the following

[1.2.3.4.5]

None of the above.

[5.5.5,5,5)

[[55]]

The code in your question seems to have a small typo, so I’ll rewrite it correctly:

python

import numpy as np
print(np.full((1, 2), 5))

Explanation:

np.full((1, 2), 5) creates a NumPy array of shape (1, 2) filled with the value 5.
Shape (1, 2) means 1 row, 2 columns.

Output:

lua

[[5 5]]

✅ Correct answer: [[5 5]]

How is memory allocation for lists and tuples different in Python?

Select one correct answer from the following

Lists use more memory than tuples

Both use the same amount of memory

Memory usage is random and unpredictable

Tuples use more memory than lists

The correct answer is: Lists use more memory than tuples ✅
Reason:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/27
Lists are mutable, so Python allocates extra memory to accommodate changes (adding/removing
elements).
Tuples are immutable, so they need less memory since their size is fixed once created.

Sam and Alex are competitive coders who enjoy creating string challenges for each other. In
one such challenge, Sam asks Alex to write a function that sorts a string according to specific
rules.

Rules for Building the Sorted String ss:

1. Start by appending the smallest character from the original string s to ss.

2. From the remaining characters, append the next smallest character that is greater than the
last appended character.

3. Repeat step 2 until no more valid characters can be added (ie., no greater characters remain).

4. Then, start appending the largest character that is less than the last character added.

5. Repeat step 4 until no more valid characters can be added (ie, no smaller characters remain).

6. If the remaining characters are all the same and none satisfy the conditions in steps 2-5, pick
any one of them and add it to ss.

7. Repeat steps 2-6 until all characters from the original string s have been used.

Input Format

A single line containing the string s

Constraints:

1≤s≤ 10^5

All characters are lowercase English letters (a-z)


All characters are lowercase English letters (a-z)

Example

sababyz

The following table shows the method.

ababyz a a

<- step 1

babyz b

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/27
ab

<- step 2

abyz y

aby

<- repeat step 2

abz z

abyz

<-repeat step 2, reached the end

ab

abyzb <- step 4

abyzba <- repeat step 4, reached the end

The final sorted string is abyzba.

Returns

string: the characters sorted per the rules

You must write a complete program, starting from the main function. Your program should
read input from standard input and write the result to standard output.

Sample input:

ababyz

Sample output:

abyzba

Got it — this is essentially a custom sorting simulation problem, similar to LeetCode’s “Increasing
Decreasing String” (1370).
We’ll solve it step-by-step:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/27
Plan

1. Count the frequency of each character (since we’ll need to know how many remain).

2. Build the output string by repeatedly:


Looping from 'a' to 'z', picking characters if they exist and are greater than the last appended.
Then looping from 'z' to 'a', picking characters if they exist and are smaller than the last
appended.
3. Stop when all characters are used.

Code:

python

def main():
s = input().strip()

# Count frequency of each character


from collections import Counter
freq = Counter(s)

result = []
while len(result) < len(s):
# Step 1 & 2: Append smallest -> largest (ascending order)
for ch in sorted(freq.keys()):
if freq[ch] > 0:
result.append(ch)
freq[ch] -= 1

# Step 4 & 5: Append largest -> smallest (descending order)


for ch in sorted(freq.keys(), reverse=True):
if freq[ch] > 0:
result.append(ch)
freq[ch] -= 1

print("".join(result))

if __name__ == "__main__":
main()

Example Run:

Input:

nginx

ababyz

Process:

makefile

Ascending: a b y z
Descending: b a

Output:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/27
nginx

abyzba

This runs in O(n log k) where k ≤ 26, which is efficient for n ≤ 10^5.
Do you want me to also optimize it to O(n) by avoiding sorting in every loop? That would make it even
faster for large inputs.

Python 3.6

Got it — for Python 3.6, we can still implement it the same way, but to make it faster and avoid sorting
on every loop, we’ll just iterate over the alphabet string 'abcdefghijklmnopqrstuvwxyz' and its reverse
once per pass.
Here’s the optimized Python 3.6 version:

python

def main():
s = input().strip()

from collections import Counter


freq = Counter(s)

result = []
total_len = len(s)
alphabet = 'abcdefghijklmnopqrstuvwxyz'

while len(result) < total_len:


# Ascending order
for ch in alphabet:
if freq[ch] > 0:
result.append(ch)
freq[ch] -= 1

# Descending order
for ch in reversed(alphabet):
if freq[ch] > 0:
result.append(ch)
freq[ch] -= 1

print("".join(result))

if __name__ == "__main__":
main()

Example run:

makefile

Input:
ababyz

Output:
abyzba

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/27
✅ Works in Python 3.6, avoids repeated sorting, runs in O(n).
If you want, I can also simulate the exact “step-by-step” picking like in your example table. That would
show how it builds the string at each stage.

Traceback (most recent call last): File "script-3.6.0.py", line 1, in <module> userinput =
input().strip() EOFError: EOF when reading a line

That EOFError happens because your Python environment is running the script without actually
passing any input to input().
In a normal terminal, you’d run it like:

bash

python script.py
ababyz

and press Enter.

But in online judges or certain IDEs, you may need to handle no input gracefully.
We can fix it by wrapping input() in a try-except block:

python

def main():
import sys
from collections import Counter

try:
s = input().strip()
except EOFError:
# No input provided
return

freq = Counter(s)
result = []
total_len = len(s)
alphabet = 'abcdefghijklmnopqrstuvwxyz'

while len(result) < total_len:


# Ascending order
for ch in alphabet:
if freq[ch] > 0:
result.append(ch)
freq[ch] -= 1

# Descending order
for ch in reversed(alphabet):
if freq[ch] > 0:
result.append(ch)
freq[ch] -= 1

print("".join(result))

if __name__ == "__main__":
main()

Why this fixes it:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/27
If the environment sends no input, EOFError is caught, and the program ends without crashing.
If input is given, it runs normally.

Do you want me to also rewrite it so you can test it without typing input (by hardcoding s) while
developing? That would avoid the EOF issue in your test environment.

Coding 03

DMark for Review

A manufacturing facility uses a milling machine equipped with a circular tool changer that holds
n tools. These tools are arranged in a circular array and may include duplicate names.

The machine operator can rotate the tool changer one position at a time, either to the left or to
the right, to bring the desired tool into position. After reaching the end of the array in either
direction, it wraps around to the other side (i.e., the array is circular).

Given:

A list of n tool names in the order they appear on the tool changer,

The starting index of the currently active tool,

The name of the required tool,

Your task is to calculate and print the minimum number of moves (either left or right) needed to
reach the nearest instance of the required tool.

You must read input from standard input and print output to standard output.

Input Format

The first line contains an integer n, the number of tools in the changer. The next n lines each
contain a string tools[i], the name of a tool at index i. The following line contains an integer
startIndex, representing the index of the currently active tool.

The last line contains a string target, the name of the required tool.

Constraints:

Constraints:

1 ≤ n ≤ 100

0s startindex ≤ n - 1

1s length of tools[i] and target ≤ 100

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/27
The target tool is guaranteed to be present in the list

Output Format

Print a single integer - the minimum number of moves required to reach the closest occurrence
of the target tool.

Customiinput

Output

Sample input:

['ballendmill", "keywaycutter', 'slotdrill, 'facemill']

"ballendmill

Sample output:

<< Previous Question

Alright — this is a minimum rotation on a circular array problem.


We just need to:

1. Find all indices where the target tool appears.


2. For each such index, calculate the distance clockwise and distance counter-clockwise from the
startIndex.

3. Take the minimum of those distances.

Python 3.6 solution:

python

def main():
# Read inputs
n = int(input().strip())
tools = [input().strip() for _ in range(n)]
startIndex = int(input().strip())
target = input().strip()

min_moves = n # maximum possible

for i, tool in enumerate(tools):


if tool == target:
# Clockwise distance
clockwise = abs(i - startIndex)
# Counter-clockwise distance (wrap-around)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/27
counter_clockwise = n - clockwise
# Take the smaller
min_moves = min(min_moves, min(clockwise, counter_clockwise))

print(min_moves)

if __name__ == "__main__":
main()

Example Run:

Input:

4
ballendmill
keywaycutter
slotdrill
facemill
1
ballendmill

Output:

Why it works:

For each occurrence of target, we compute:

Clockwise: abs(i - startIndex)


Counter-clockwise: n - abs(i - startIndex)
The minimum of these is the shortest rotation.
The final answer is the smallest among all possible target positions.

If you want, I can also make it accept array-like input like in your sample (['ballendmill',
'keywaycutter', ...]) directly instead of line-by-line. That would let you copy-paste sample inputs
exactly. Would you like me to do that?

Getting the same compilation error

Ah — the EOFError you’re getting is the same issue as before:


Your execution environment is trying to run input() calls without supplying the expected input lines.
For your milling machine problem, we can still handle this gracefully so it won’t crash even if no input is
given.
Here’s the safe version that:

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/27
Wraps input() in try-except
Lets you hardcode test values if no stdin is provided (useful for debugging in environments like
yours).

python

def main():
try:
# Read number of tools
n = int(input().strip())
tools = [input().strip() for _ in range(n)]
startIndex = int(input().strip())
target = input().strip()
except EOFError:
# Hardcoded fallback for testing without stdin
n = 4
tools = ["ballendmill", "keywaycutter", "slotdrill", "facemill"]
startIndex = 1
target = "ballendmill"

min_moves = n
for i, tool in enumerate(tools):
if tool == target:
clockwise = abs(i - startIndex)
counter_clockwise = n - clockwise
min_moves = min(min_moves, min(clockwise, counter_clockwise))

print(min_moves)

if __name__ == "__main__":
main()

If run without stdin, it will automatically test with:

4
ballendmill
keywaycutter
slotdrill
facemill
1
ballendmill

and output:

If you do have a way to give input, run it like this in a terminal:

nginx

python script.py
4
ballendmill
keywaycutter
slotdrill
facemill

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/27
1
ballendmill

Do you want me to modify it so it parses the list directly from one line like your example
['ballendmill', 'keywaycutter', ...]? That would make it easier to paste test data.

Its an online proctor compiler

Got it✅ — in an online proctored compiler you won’t be able to hardcode or skip input, you must read
exactly in the format the system sends.
From your problem statement, the input is not given in Python list form — the example ['ballendmill',
'keywaycutter', ...] in the text was just for illustration.
In the real test case, it will be given line by line like this:

4
ballendmill
keywaycutter
slotdrill
facemill
1
ballendmill

So your code should only use input() for reading exactly those lines and nothing else.
Here’s the clean submission-ready version (Python 3.6 compatible, no extra prints, no try-except):

python

def main():
n = int(input().strip())
tools = [input().strip() for _ in range(n)]
startIndex = int(input().strip())
target = input().strip()

min_moves = n
for i, tool in enumerate(tools):
if tool == target:
clockwise = abs(i - startIndex)
counter_clockwise = n - clockwise
min_moves = min(min_moves, min(clockwise, counter_clockwise))

print(min_moves)

if __name__ == "__main__":
main()

Why this will pass in the proctored environment

Reads exactly the number of lines the system sends.


No debug/fallback code.
Produces only the required output.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/27
Do you want me to also prepare the Java version in case the online test asks for Java instead of Python?
That’s common in proctored coding rounds.

You are given a sentence consisting of words separated by spaces. Each word contains only
English letters (uppercase or lowercase).

Your task is to find and print the first word that has an even length and is the longest among all
even-length words in the sentence.

If no even-length word is found, print "00" (zero zero).

Input Format

A single line of input: a string representing the sentence.

The sentence contains only letters (a-z, A-Z) and spaces.

Words are separated by a single space.

You may assume:

1 length of sentence ≤ 10^5

Output Format

Print the first longest even-length word, or "00" if none exists.

Example Input

Time to write great code

Example Output

Time

Explanation

Words: "Time", "to", "write", "great", "code"

Their lengths: 4, 2, 5, 5, 4

Even-length words: "Time" (4), "to" (2), "code" (4)

"Time" and "code" are the longest even-length words (characters), but "Time""Time" and "code"
are the longest even-length words (characters), but "Time" appears first.

You must write a complete program, starting from the main function, that reads input from
standard input and prints the result to standard output.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/27
Sample input:

It is a pleasant day today

Sample output:

Pleasant

<Previous Question

Got it — you’re facing an EOFError because your online proctor compiler doesn’t actually provide input
interactively; it expects the code to just read whatever input is already there.
We can solve your problem with a simple input() read, process the sentence, and print the required
word.
Here’s a Python 3.6 compliant solution:

python

def main():
try:
sentence = input().strip()
except EOFError:
sentence = ""

words = sentence.split()
longest_word = ""
max_length = 0

for word in words:


if len(word) % 2 == 0:
if len(word) > max_length:
longest_word = word
max_length = len(word)

if max_length > 0:
print(longest_word)
else:
print("00")

if __name__ == "__main__":
main()

How it works:

1. Read input safely → try/except avoids crash if no input is provided.


2. Split sentence into words → .split() handles spaces automatically.

3. Check even-length → len(word) % 2 == 0.


4. Track longest → Store the first one encountered if there’s a tie.
5. Print → Either the longest even-length word or "00".

✅ This will pass in online compilers where input is provided in one go.
If you want, I can also give you an optimized version for O(n) traversal that doesn’t store all words in
memory — better for 10^5 length constraints.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/27
Would you like me to prepare that?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/27

You might also like