What Are the Most Common Python Basic Interview Questions?

Most common python basic interview questions

Categories:

  • Author Avatar
    Written by:

    Nathan Rosidi

This article covers key Python interview questions for beginners, focusing on basics and data handling in Python. Let's dive in!

Did you know that Python is now the most used programming language? As of October 2022, more people use Python than C or Java. This fact comes from the TIOBE Index, a famous ranking for programming languages.

Another fact that, Python's popularity keeps growing fast. Every year, it gets 22% more users. By 2022, over four million developers were using Python on GitHub.

In this article, we will talk about the most common Python questions in job interviews, especially for beginners. We will look at basic things and also how to work with data in Python, buckle up and let’s get started!

Basic Python Interview Question #1: Find out search details for apartments designed for a sole-person stay

This question asks us to identify the search details for apartments that are suitable for just one person to stay in by Airbnb.

EasyID 9615

Find the search details for apartments where the property type is Apartment and the accommodation is suitable for one person.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9615-find-out-search-details-for-apartments-designed-for-a-sole-person-stay

Let’s see our data.

Table: airbnb_search_details
Loading Dataset

We are looking at information about apartments made for one person. We use two tools, pandas and numpy, which are like helpers for managing and understanding data.

  • First, we focus on the data that shows apartments for one person. We check where 'accommodates' is equal to 1.
  • Then, we also want these apartments to be of a specific type - 'Apartment'. So, we look for where 'property_type' says 'Apartment'.
  • By combining these two conditions, we get details only for apartments perfect for one person.
  • We store this specific information in a new place called 'result'.

In simple words, we are just picking out the apartment searches that match two things: meant for one person and are apartments. Let’s see the code.

import pandas as pd
import numpy as np

result = airbnb_search_details[(airbnb_search_details['accommodates'] == 1) & (airbnb_search_details['property_type'] == 'Apartment')]

Python
Go to the question on the platformTables: airbnb_search_details

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

idpriceproperty_typeroom_typeamenitiesaccommodatesbathroomsbed_typecancellation_policycleaning_feecityhost_identity_verifiedhost_response_ratehost_sinceneighbourhoodnumber_of_reviewsreview_scores_ratingzipcodebedroomsbeds
5059214431.75ApartmentPrivate room{TV,"Wireless Internet","Air conditioning",Kitchen,"Free parking on premises",Breakfast,Heating,"Smoke detector","Carbon monoxide detector","First aid kit","Fire extinguisher",Essentials,Shampoo,"Lock on bedroom door",Hangers,"Laptop friendly workspace","Private living room"}13Real BedstrictFALSENYCf2014-03-14Harlem01003021
10923708340.12ApartmentPrivate room{TV,Internet,"Wireless Internet","Air conditioning",Kitchen,"Pets live on this property",Cat(s),"Buzzer/wireless intercom",Heating,"Family/kid friendly",Washer,"Smoke detector","Carbon monoxide detector","First aid kit","Fire extinguisher",Essentials}11Real BedstrictFALSENYCt100%2014-06-30Harlem166911003111
1077375400.73ApartmentPrivate room{"Wireless Internet",Heating,"Family/kid friendly","Smoke detector","Carbon monoxide detector","Fire extinguisher",Essentials,Shampoo,Hangers,Iron,"Laptop friendly workspace","translation missing: en.hosting_amenity_50"}11Real BedmoderateTRUENYCt2015-04-04Sunset Park11001122011
13121821501.06ApartmentPrivate room{TV,"Cable TV",Internet,"Wireless Internet","Air conditioning",Kitchen,Heating,"Smoke detector","First aid kit",Essentials,Hangers,"Hair dryer",Iron,"Laptop friendly workspace"}11Real BedflexibleFALSENYCf2014-09-20Park Slope01121511
19245819424.85ApartmentPrivate room{Internet,"Wireless Internet",Kitchen,"Pets live on this property",Dog(s),Washer,Dryer,"Smoke detector","Fire extinguisher"}11Real BedmoderateFALSESFt2010-03-16Mission District12909411011
11157369409.43ApartmentPrivate room{TV,Internet,"Wireless Internet","Air conditioning",Kitchen,Heating,Essentials,Shampoo,Iron,"Laptop friendly workspace"}11Real BedflexibleTRUENYCt2014-06-30Harlem01002611
12386097366.36ApartmentShared room{TV,Internet,"Wireless Internet","Air conditioning",Kitchen,Heating,"Smoke detector",Essentials,Shampoo}11Real BedmoderateTRUENYCt100%2015-10-02Harlem18961002712

Basic Python Interview Question #2: Users Activity Per Month Day

Basic Python Interview Question from Facebook

This question is about figuring out how active users are on different days of the month on Facebook. Specifically, it asks for a count of how many posts are made each day, asked by Meta/Facebook.

Last Updated: January 2021

EasyID 2006

Return the total number of posts for each month, aggregated across all the years (i.e., posts in January 2019 and January 2020 are both combined into January). Output the month number (i.e., 1 for January, 2 for February) and the total number of posts in that month.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2006-users-activity-per-month-day

Let’s see our data.

Table: facebook_posts
Loading Dataset

We are analyzing how often users post on Facebook during different days of the month. We use pandas, a tool for data handling, to do this.

  • First, we change the post dates into a format that's easy to work with.
  • Then, we look at these dates and focus on the day part of each date.
  • For each day, we count how many posts were made.
  • We then make a new table called 'user_activity' to show these counts.
  • Finally, we make sure this table is easy to read by resetting its layout.

Simply, we are counting Facebook posts for each day of the month and presenting it in a clear table. Let’s see the code.

import pandas as pd

result = facebook_posts.groupby(pd.to_datetime(facebook_posts['post_date']).dt.day)['post_id'].count().to_frame('user_activity').reset_index()

Python

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

post_dateuser_activity
13
23

Basic Python Interview Question #3: Customers Who Purchased the Same Product

This question involves finding customers who bought the same furniture items, asked by Meta. It asks for details like the furniture's product ID, brand name, the unique customer IDs who bought each item, and how many different customers bought each item.

The final list should start with the furniture items bought by the most customers

Last Updated: February 2023

MediumID 2150

In order to improve customer segmentation efforts for users interested in purchasing furniture, you have been asked to find customers who have purchased the same items of furniture.

Output the product_id, brand_name, unique customer ID's who purchased that product, and the count of unique customer ID's who purchased that product. Arrange the output in descending order with the highest count at the top.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2150-customers-who-purchased-the-same-product

Let’s see our data.

Table: online_orders
Loading Dataset
Table: online_orders
Loading Dataset

We are focusing on customers who are interested in buying furniture. We use pandas and numpy, which help us organize and analyze data.

  • We start by combining two sets of data: one with order details (online_orders) and the other with product details (online_products). We match them using 'product_id'.
  • Then, we only keep the data that is about furniture.
  • We simplify this data to show only product ID, brand name, and customer ID, removing any duplicates.
  • Next, we count how many different customers bought each product.
  • We create a new table showing these counts along with product ID, brand name, and customer ID.
  • Lastly, we arrange this table so the products with the most unique buyers are at the top.

In short, we are finding and listing furniture items based on how popular they are with different customers, showing the most popular first. Let’s see the code.

import pandas as pd
import numpy as np

merged = pd.merge(online_orders, online_products, on="product_id", how="inner")
merged = merged.loc[merged["product_class"] == "FURNITURE", :]
merged = merged[["product_id", "brand_name", "customer_id"]].drop_duplicates()
unique_cust = (
    merged.groupby(["product_id"])["customer_id"]
    .nunique()
    .to_frame("unique_cust_no")
    .reset_index()
)
result = pd.merge(merged, unique_cust, on="product_id", how="inner").sort_values(
    by="unique_cust_no", ascending=False
)

Python
Go to the question on the platformTables: online_orders, online_products

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

product_idbrand_namecustomer_idunique_cust_no
10American Home23
10American Home33
10American Home13
8Lucky Joe31
11American Home11

Basic Python Interview Question #4: Sorting Movies By Duration Time

This basic Python interview question requires sorting a list of movies based on how long they last, with the longest movies shown first, asked by Google.

Last Updated: May 2023

EasyID 2163

You have been asked to sort movies according to their duration in descending order.

Your output should contain all columns sorted by the movie duration in the given dataset.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2163-sorting-movies-by-duration-time

Let’s see our data.

Table: movie_catalogue
Loading Dataset

We need to organize movies based on their duration, from longest to shortest. We use pandas, a tool for handling data, to do this.

  • We start by focusing on the movie duration. We extract the duration in minutes from the 'duration' column.
  • We change these duration values into numbers so that we can sort them.
  • Next, we sort the whole movie catalogue based on these duration numbers, putting the longest movies at the top.
  • After sorting, we remove the column with the duration in minutes since we don't need it anymore.

In simple terms, we are putting the movies in order from the longest to the shortest based on their duration. Let’s see the code.

import pandas as pd

movie_catalogue["movie_minutes"] = (
    movie_catalogue["duration"].str.extract("(\d+)").astype(float)
)

result = movie_catalogue.sort_values(by="movie_minutes", ascending=False).drop(
    "movie_minutes", axis=1
)

Python
Go to the question on the platformTables: movie_catalogue

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

show_idtitlerelease_yearratingduration
s8083Star Wars: Episode VIII: The Last Jedi2017PG-13152 min
s6201Avengers: Infinity War2018PG-13150 min
s6326Black Panther2018PG-13135 min
s8052Solo: A Star Wars Story2018PG-13135 min
s8053Solo: A Star Wars Story (Spanish Version)2018PG-13135 min
s600The Best of Enemies2019PG-13133 min
s1561The Prom2020PG-13132 min
s2755Greater2016PG131 min
s7418Mary Poppins Returns2018PG131 min
s8581Thor: Ragnarok2017PG-13131 min
s7152Jupiter Ascending2015PG-13128 min
s7812Queen of the Desert2015PG-13128 min
s1036The Zookeeper's Wife2017PG-13127 min
s2331Eurovision Song Contest: The Story of Fire Saga2020PG-13124 min
s1704Jingle Jangle: A Christmas Journey2020PG124 min
s1690Loving2016PG-13124 min
s1289Operation Finale2018PG-13123 min
s4538The Black Prince2017PG-13121 min
s1500The Midnight Sky2020PG-13119 min
s2679Jem and the Holograms2015PG119 min
s6172Ant-Man and the Wasp2018PG-13118 min
s8361The Incredibles 22018PG118 min
s7068Incredibles 2 (Spanish Version)2018PG118 min
s1204The BFG2016PG118 min
s583Mother's Day2016PG-13118 min
s163Marshall2017PG-13118 min
s3392The Command2018PG-13118 min
s3583Selfless2015PG-13117 min
s8069Spider-Man: Into the Spider-Verse2018PG117 min
s7455Midnight Special2016PG-13112 min
s1242Moxie2021PG-13112 min
s7856Rememory2017PG-13112 min
s6884Goosebumps 2: Haunted Halloween2018PG90 min
s2573Roped2020PG90 min
s3081Benchwarmers 2: Breaking Balls2019PG-1390 min
s108A Champion Heart2018G90 min
s95Show Dogs2018PG90 min
s1Dick Johnson Is Dead2020PG-1390 min
s1219YES DAY2021PG90 min
s6331Blackway2015PG-1390 min
s7685Our House2018PG-1390 min
s6114Aliens Ate My Homework2018PG90 min
s4820Brain on Fire2016PG-1389 min
s6945He Named Me Malala2015PG-1389 min
s7062In The Deep2017PG-1389 min
s2560Becoming2020PG89 min
s925Aliens Stole My Body2020PG88 min
s8783Yoga Hosers2016PG-1388 min
s6258Be Somebody2016PG88 min
s2934Polaroid2019PG-1388 min
s3873Knock Down The House2019PG88 min
s4874Pup Star: World Tour2018G87 min
s1537Incarnate2016PG-1387 min
s2912A Shaun the Sheep Movie: Farmageddon2019G87 min
s6252Bathtubs Over Broadway2018PG-1387 min
s6641Dr. Seuss' The Grinch2018PG86 min
s3189A Cinderella Story: Christmas Wish2019PG86 min
s7620November Criminals2017PG-1386 min
s4493Gnome Alone2018PG86 min
s1901Vampires vs. the Bronx2020PG-1386 min
s5124Pottersville2017PG-1386 min
s5488Wild Oats2016PG-1386 min
s346Open Season: Scared Silly2015PG85 min
s7316Little Men2016PG85 min
s1887David Attenborough: A Life on Our Planet2020PG84 min
s174Snervous Tyler Oakley2015PG-1383 min
s8046SMOSH: The Movie2015PG-1383 min
s1577Bobbleheads The Movie2020PG83 min
s3103Sweetheart2019PG-1383 min
s3384Echo in the Canyon2019PG-1382 min
s2989Menashe2017PG82 min
s6995Hope Springs Eternal2018PG79 min
s8702Water & Power: A California Heist2017PG78 min
s5274Ghost of the Mountains2017G78 min
s5597Growing Up Wild2016G78 min
s7536My Entire High School Sinking Into the Sea2016PG-1377 min
s5199SPF-182017PG-1375 min
s5646Marvel's Hulk: Where Monsters Dwell2016PG75 min
s5866Marvel Super Hero Adventures: Frost Fight!2015PG74 min

Basic Python Interview Question #5: Find the date with the highest opening stock price

Basic Python Interview Question from Apple

This question asks us to identify the date when a stock (presumably Apple's, given the dataframe name) had its highest opening price, by Apple.

EasyID 9613

Find the date when Apple's opening stock price reached its maximum

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/9613-find-the-date-with-the-highest-opening-stock-price

Let’s see our data.

Table: aapl_historical_stock_price
Loading Dataset

We are looking to find the day when a specific stock had its highest starting price. We use pandas and numpy, tools for data analysis, and handle dates with datetime and time.

  • We start with the stock price data, named 'aapl_historical_stock_price'.
  • Then, we adjust the dates to a standard format ('YYYY-MM-DD').
  • Next, we search for the highest opening price in the data. The 'open' column shows us the starting price of the stock on each day.
  • Once we find the highest opening price, we look for the date(s) when this price occurred.
  • The result shows us the date or dates with this highest opening stock price.

In summary, we are identifying the date when the stock started trading at its highest price. Let’s see the code.

import pandas as pd
import numpy as np
import datetime, time 

df = aapl_historical_stock_price
df['date'] = df['date'].apply(lambda x: x.strftime('%Y-%m-%d'))

result = df[df['open'] == df['open'].max()][['date']]

Python
Go to the question on the platformTables: aapl_historical_stock_price

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

date
2012-09-21

Basic Python Interview Question #6: Low Fat and Recyclable

This question wants us to calculate what proportion of all products are both low fat and recyclable by Meta/Facebook.

Last Updated: October 2021

EasyID 2067

What percentage of all products are both low fat and recyclable?

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2067-low-fat-and-recyclable

Let’s see our data.

Table: facebook_products
Loading Dataset

We need to find out how many products are both low in fat and can be recycled. We use pandas for data analysis.

  • First, we look at the products data and pick out only those that are marked as low fat ('Y' in 'is_low_fat') and recyclable ('Y' in 'is_recyclable').
  • We then count how many products meet both these conditions.
  • Next, we compare this number to the total number of products in the dataset.
  • We calculate the percentage by dividing the number of low fat, recyclable products by the total number of products and multiplying by 100.

Simply put, we are figuring out the fraction of products that are both healthy (low fat) and environmentally friendly (recyclable) and expressing it as a percentage, let’s see the code.

df = facebook_products[(facebook_products.is_low_fat == 'Y') & (facebook_products.is_recyclable == 'Y')]
result = len(df) / len(facebook_products) * 100.0

Python
Go to the question on the platformTables: facebook_products

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

Missing or invalid data

Basic Python Interview Question #7: Products with No Sales

This question asks us to find products that have not been sold at all by Amazon. We need to list the ID and market name of these unsold products.

Last Updated: May 2022

EasyID 2109

Write a query to get a list of products that have not had any sales. Output the ID and market name of these products.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2109-products-with-no-sales

Let’s see our data.

Table: fct_customer_sales
Loading Dataset
Table: dim_product
Loading Dataset

We are looking for products that haven't been sold yet. We use a merge function, a way of combining two sets of data, for this task.

  • We start by joining two data sets: 'fct_customer_sales' (which has sales details) and 'dim_product' (which has product details). We link them using 'prod_sku_id', which is like a unique code for each product.
  • We then look for products that do not have any sales. We do this by checking for missing values in the 'order_id' column. If 'order_id' is missing, it means the product wasn't sold.
  • After finding these products, we create a list showing their ID ('prod_sku_id') and market name ('market_name').

In simple words, we are identifying products that have never been sold and listing their ID and the market they are associated with, let’s see the code.

sales_and_products = fct_customer_sales.merge(dim_product, on='prod_sku_id', how='right')
result = sales_and_products[sales_and_products['order_id'].isna()][['prod_sku_id', 'market_name']]

Python
Go to the question on the platformTables: fct_customer_sales, dim_product

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

prod_sku_idmarket_name
P473Apply IPhone 13 Pro Max
P481Samsung Galaxy Tab A
P483Dell XPS13
P488JBL Charge 5

Basic Python Interview Question #8: Most Recent Employee Login Details

Basic Python Interview Question from Amazon

This question is about finding the latest login information for each employee at Amazon's IT department.

Last Updated: December 2022

EasyID 2141

Amazon's information technology department is looking for information on employees' most recent logins.

The output should include all information related to each employee's most recent login.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2141-most-recent-employee-login-details

Let’s see our data.

Table: worker_logins
Loading Dataset

We need to identify when each employee last logged in and gather all the details about these logins. We use pandas and numpy for data management and analysis.

  • We start with the 'worker_logins' data, which records employees' login times.
  • For each employee ('worker_id'), we find the most recent ('max') login time.
  • We then create a new table ('most_recent') that shows the latest login time for each employee.
  • Next, we merge this table with the original login data. This helps us match each employee's most recent login time with their other login details.
  • We ensure that we're combining the data based on both employee ID and their last login time.
  • Finally, we remove the 'last_login' column from the result as it's no longer needed.

In short, we are sorting out the most recent login for each employee and displaying all related information about that login, let’s see the code.

import pandas as pd
import numpy as np

most_recent = (
    worker_logins.groupby(["worker_id"])["login_timestamp"]
    .max()
    .to_frame("last_login")
)
result = pd.merge(
    most_recent,
    worker_logins,
    how="inner",
    left_on=["worker_id", "last_login"],
    right_on=["worker_id", "login_timestamp"],
).drop(columns=['last_login'])

Python

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

worker_ididlogin_timestampip_addresscountryregioncitydevice_type
1202022-01-26 08:58:0065.111.191.14USAFloridaMiamidesktop
2142022-01-10 09:52:0066.68.93.191USATexasAustindesktop
3162022-01-25 08:58:0080.211.248.182PolandMazoviaWarsawdesktop
4152022-01-24 08:48:0046.212.154.172NorwayVikenSkjettendesktop
532021-12-19 09:55:0010.2.135.23FranceNorthRoubaixdesktop
6172022-01-24 09:56:00185.103.180.49SpainCataloniaAlcarrasdesktop
7192022-01-26 10:55:00212.102.111.33SpainValenciaSuecamobile
8182022-01-25 09:59:0010.1.14.224ItalyLombardyBorgarellodesktop

Basic Python Interview Question #9: Customer Consumable Sales Percentages

This Python question requires us to compare different brands based on the percentage of unique customers who bought consumable products from them, following a recent advertising campaign, asked by Meta/Facebook.

Last Updated: February 2023

MediumID 2149

Following a recent advertising campaign, you have been asked to compare the sales of consumable products across all brands.

A consumable product is defined as any product where product_family = 'CONSUMABLE'.

Do the comparison of the brands by finding the percentage of unique customers (among all customers in the dataset) who purchased consumable products of some brand and then do the calculation for each brand.

Your output should contain the brand_name and percentage_of_customers rounded to the nearest whole number and ordered in descending order.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2149-customer-consumable-sales-percentages

Let’s see our data.

Table: online_orders
Loading Dataset
Table: online_products
Loading Dataset

We are comparing brands to see how popular their consumable products are with customers. We use pandas for data handling.

  • We begin by combining two data sets: one with customer orders (online_orders) and another with product details (online_products). We link them using 'product_id'.
  • Then, we focus on consumable products by filtering the data to include only items in the 'CONSUMABLE' product family.
  • For each brand, we count how many different customers bought their consumable products.
  • We then calculate the percentage of these unique customers out of all customers in the dataset.
  • We round these percentages to the nearest whole number for simplicity.
  • Finally, we arrange the brands so that those with the highest percentage of unique customers are listed first.

In short, we are finding out which brands had the most unique customers for their consumable products, and presenting this information in an easy-to-understand percentage form, ordered from most to least popular, let’s see the code.

import pandas as pd

merged = pd.merge(online_orders, online_products, on="product_id", how="inner")
consumable_df = merged.loc[merged["product_family"] == "CONSUMABLE", :]
result = (
    consumable_df.groupby("brand_name")["customer_id"]
    .nunique()
    .to_frame("pc_cust")
    .reset_index())

unique_customers = merged.customer_id.nunique()
result["pc_cust"] = (100.0 * result["pc_cust"] / unique_customers).round()
result

Python
Go to the question on the platformTables: online_orders, online_products

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

brand_namepc_cust
Fort West80
Golden80
Lucky Joe20

Basic Python Interview Question #10: Unique Employee Logins

This question asks by Meta/Facebook us to identify the worker IDs of individuals who logged in during a specific week in December 2021, from the 13th to the 19th inclusive.

Last Updated: March 2023

EasyID 2156

You have been tasked with finding the worker IDs of individuals who logged in between the 13th to the 19th inclusive of December 2021.

In your output, provide the unique worker IDs for the dates requested.

Go to the Question

Link to the question: https://platform.stratascratch.com/coding/2156-unique-employee-logins

Let’s see our data.

Table: worker_logins
Loading Dataset

We are searching for the IDs of workers who logged in between the 13th and 19th of December 2021. We use pandas, a tool for managing data, and datetime for handling dates.

  • We start with the 'worker_logins' data, which has records of when workers logged in.
  • First, we make sure the login timestamps are in a date format that's easy to use.
  • Then, we find the logins that happened between the 13th and 19th of December 2021. We use the 'between' function for this.
  • From these selected logins, we gather the unique worker IDs.
  • The result will be a list of worker IDs who logged in during this specific time period.

Simply put, we are pinpointing which workers logged in during a certain week in December 2021 and listing their IDs, let’s see the code.

import pandas as pd
import datetime as dt

worker_logins["login_timestamp"] = pd.to_datetime(worker_logins["login_timestamp"])
dates_df = worker_logins[
    worker_logins["login_timestamp"].between("2021-12-13", "2021-12-19")
]
result = dates_df["worker_id"].unique()

Python

You have reached your daily limit for code executions on our blog.
Please login/register to execute more code.

  • The dataset has already been loaded as a pandas.DataFrame.
  • print() functions and the last line of code will be displayed in the output.
  • In order for your solution to be accepted, your solution should be located on the last line of the editor and match the expected output data type listed in the question.

Here is the expected output.

Missing or invalid data

Final Thoughts

So, we've explored some of the most common basic Python interview questions. From basic syntax to complex data manipulation, we've covered topics that mirror real-world scenarios, and asked by the big tech companies.

Practice is the key to becoming not just good, but great at data science. Theory is important, but the real learning happens when you apply what you've learned. If you want to see more, here are the python interview questions.

Share