![]() |
VOOZH | about |
To excel in data science coding interviews, it's essential to master a variety of questions that test your programming skills and understanding of data science concepts. We have prepared a list of the Top 50 Data Science Interview Questions along with their answers to ace interviews.
Reversing a string means flipping its order of characters. You can do this by using Python slicing ([::-1]) or by iterating from the end to the start. This is a common operation in string manipulation.
olleh
Compare the original string with its reversed version to see if they are the same. If they match, it means the string is a palindrome. Return True or False based on this comparison. How can you check a string is palindrome or not in Python:
True
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Let's see the code to find the nth Fibonacci number:
The 5th Fibonacci number is: 5
First we create a dictionary to store numbers and their indices as you iterate through the array. For each number, check if its complement (target minus the number) exists in the dictionary. If it does, return their indices.
Let's see the code:
[1, 2]
This function calculates the factorial of a number using recursion. If the number is 0 or 1, it returns 1. Otherwise, it multiplies the number by the factorial of the number minus 1.
120
we use Python's Counter from the collections module to count how often each element appears in a list. Let's do the implementation:
Counter({3: 3, 2: 2, 1: 1})
we can load a csv file into the pandas DataFrame like we have implemented .You can also do this for any csv file
This adds corresponding elements of two Numpy arrays, creating a new array with the results.
[5 7]
In this question we have to retreive the diagonal elements in the numpy matrix and we do this with the help of a function called 'np.diagonal'.
[1 5]
To reshape 1D Numpy array into 2D array we use the function named as 'array.reshape' and this concept is called reshaping the Array
[[1 2] [3 4] [5 6]]
we calculate the mean, median, and standard deviation of a list using Numpy's built-in functions. Now we see the implementation of this:
25.0 25.0 11.180339887498949
fillna() replaces missing values with the mean of each column, while dropna() removes rows with any missing values.
df.fillna(df.mean(), inplace=True)
df.dropna(inplace=True)
To read and write data from file in Python, we use the built-in open() function, which provides a way to open a file and perform various operations on it, such as reading or writing.
employees where the age is greater than 30.This query selects all columns from the employees table where the age column value is greater than 30.
SELECT * FROM employees
WHERE age > 30;
orders and customers, where the customer_id in orders matches the id in customers.The JOIN operation merges orders and customers based on the matching customer_id and id columns.
SELECT orders, customers.
FROM orders
JOIN customers ON orders.customer_id = customers.id;
company table, but only for departments with more than 10 employees.This query calculates the average salary by department but only for those departments that have more than 10 employees, using HAVING to filter the groups.
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING COUNT(employee_id) > 10;
employees table.The subquery (SELECT AVG(salary) FROM employees) calculates the average salary, and the outer query retrieves all employees earning more than that average.
SELECT * FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
sales table for each product.This query groups the data by product_id and calculates the total sales (SUM(sales_amount)) for each product.
SELECT product_id, SUM(sales_amount) AS total_sales
FROM sales
GROUP BY product_id;
To return JSON data, you can use the jsonify() function, which converts Python dictionaries to JSON format.This route will return the dictionary as a JSON response.
To create a simple Flask app, you define a route using the @app.route() decorator and return a response from a view function. This will start a basic Flask app that responds with “Hello, World!” when the root URL is accessed
Flask allows you to specify which HTTP methods a route should respond to by using the methods parameter in the @app.route() decorator. By default, Flask routes respond to GET requests, but you can specify others such as POST, PUT, DELETE, etc
__init__(self, name, age) initializes the Person object with a name and age.birthday(self) increases the person's age by 1.__str__(self) provides a human-readable string representation of the Person object.Name: Alice, Age: 30 Name: Alice, Age: 31
Hash table is a data structure that stores key-value pairs. It uses a hash function to compute an index into an array of buckets or slots, from which the desired value can be found.
Traverse the string and keep track of the frequency of each character. Check which character appears exactly once and return it.
w None
True False
Transposing an array means swapping its rows and columns. You can use the transpose method or the .T attribute. Here’s how you can do it:
[[1 4] [2 5]]
We merge both arrays, sort them, and return the median value. If the total number of elements is odd, the middle element is the median. If even, it is the average of the two middle elements.
3
k.We use a sliding window technique to calculate the sum of each subarray of size k. The maximum sum is updated at each step.
9
We use the heapq library to find the kth smallest element in unsorted array. Below is the code:
7
We use Python's itertools.permutations to generate all permutations of the given list.
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
We flip the fair coin twice. If the result is heads-tails or tails-heads, we return a biased value; otherwise, repeat
1
Confidence Interval is a range where we are certain that true value exists. The selection of a confidence level for an interval determines the probability that the confidence interval will contain the true parameter value. is the We calculate the mean and margin of error using the standard deviation and z-score for the confidence level.
Calculate the Chi-squared statistic by comparing observed and expected frequencies in the contingency table.
Use numpy.random.choice to generate random numbers based on a given probability distribution.
[2 1 2 2 2 3 1 2 2 2]
In this we calculate distances from a given point, sort them, and return the majority label of the k closest points.
1
we use sklearn's silhouette_score function to evaluate the quality of clustering. let' see the implementation with code.
Use pandas.get_dummies to convert categorical columns into one-hot-encoded columns.
Color_Blue Color_Green Color_Red 0 0 0 1 1 1 0 0 2 0 1 0
Compute covariance matrix, eigenvalues, and eigenvectors to reduce dimensions.
[[-2.82842712] [ 0. ] [ 2.82842712]]
we use Simple Imputer to replace missing values with the mean or another strategy. Below is the code:
Use pandas.groupby and rolling to calculate rolling averages.
Group level_1 Value 0 A 0 NaN 1 A 1 15.0 2 B 2 NaN 3 B 3 35.0
Use nltk to extract and count n-grams.
Use pandas.pivot_table to summarize data into a pivot table.
Type X Y Category A 10.0 20.0 B 30.0 NaN
Use spacy for named entity recognition (NER).
Tokenization is a basic text processing step. Here we tokenize the input text into words, ignoring punctuation.
We’ll use regular expressions to extract potential named entities such as names (capitalized words), locations, and dates.
Grayscale conversion can be done by averaging the RGB channels or using a weighted sum.
A custom loss function can be written to not only calculate the error but also include additional conditions, like penalizing large predictions.
ReLU and sigmoid. Use it in a neural network model.You are required to define a function combining both ReLU and Sigmoid functions. You will then use this function within a Keras model for neural network training.