Give me 10 python question for interview related to list and dictionary and pandas
- User
Give me 10 python question for interview related to list and dictionary and pandas
- Assistant
- User
python coding question easy to medium
- Assistant
Give me 10 python question for interview related to list and dictionary and pandas
python coding question easy to medium
Certainly! Here are 10 Python interview questions related to lists and dictionaries as well as the pandas library:
List Manipulation: How would you remove duplicates from a list while preserving the order?
Dictionary Comprehension: Explain with an example how you can create a dictionary comprehension from a list of tuples where each tuple has two elements: a key and a value.
List vs. Dictionary: Compare lists and dictionaries. When would you use one over the other? Provide examples.
Finding Dictionary Keys: How do you check if a key exists in a dictionary? Provide at least two different methods.
Nested Dictionary: Write a function that flattens a nested dictionary, i.e., converts it into a single-level dictionary with compound keys.
Defaultdict and Counter: Explain the defaultdict and Counter classes from the collections module with examples of their usage.
List and Dictionary Performance: Discuss the time complexity of basic operations (insert, delete, lookup) for lists and dictionaries.
Creating DataFrames: How would you create a Pandas DataFrame from a dictionary of lists? Provide a sample dictionary and its resulting DataFrame.
Data Cleaning: Describe how you’d handle missing values in a Pandas DataFrame. Mention at least three strategies.
GroupBy Operations: Given a DataFrame, demonstrate how you would use the groupby function to calculate the mean of a particular column for each group of another column.
# Removing duplicates while preserving order
def remove_duplicates(lst):
seen = set()
return [x for x in lst if not (x in seen or seen.add(x))]
# Example usage
nums = [1, 2, 3, 2, 1, 4, 5]
print(remove_duplicates(nums)) # Output: [1, 2, 3, 4, 5]
import pandas as pd
# Creating DataFrame from dictionary of lists
data = {
'A': [1, 2, 3],
'B': [4, 5, 6]
}
df = pd.DataFrame(data)
print(df)
import pandas as pd
import numpy as np
# Sample DataFrame with missing values
data = {
'A': [1, 2, np.nan],
'B': [4, np.nan, 6]
}
df = pd.DataFrame(data)
# 1. Drop rows with any missing values
df_dropna = df.dropna()
# 2. Fill missing values with a constant (e.g., 0)
df_fillna = df.fillna(0)
# 3. Fill missing values with the mean of the column
df_fill_mean = df.apply(lambda x: x.fillna(x.mean()), axis=0)
print(df_dropna)
print(df_fillna)
print(df_fill_mean)
Sure, here are some Python coding questions ranging from easy to medium difficulty:
Reverse a String: Write a function that takes a string as input and returns the string reversed.
def reverse_string(s):
return s[::-1]
# Example usage
print(reverse_string("hello")) # Output: "olleh"
Check for Anagrams: Write a function to check if two strings are anagrams of each other.
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)
# Example usage
print(are_anagrams("listen", "silent")) # Output: True
print(are_anagrams("hello", "world")) # Output: False
Find the Largest Element: Write a function that finds the largest element in a list.
def find_largest(nums):
return max(nums)
# Example usage
print(find_largest([1, 2, 3, 4, 5])) # Output: 5
FizzBuzz: Write a Python program that prints the numbers from 1 to 100. But for multiples of three, print "Fizz" instead of the number and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".
def fizzbuzz():
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
fizzbuzz()
Two Sum: Given a list of integers, write a function that returns indices of the two numbers such that they add up to a specific target.
def two_sum(nums, target):
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
# Example usage
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target)) # Output: [0, 1]
Valid Parentheses: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
def is_valid_parentheses(s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
# Example usage
print(is_valid_parentheses("()[]{}")) # Output: True
print(is_valid_parentheses("(]")) # Output: False
Find All Duplicates: Write a function that finds all elements that appear twice in an array.
def find_duplicates(nums):
seen = set()
duplicates = set()
for num in nums:
if num in seen:
duplicates.add(num)
else:
seen.add(num)
return list(duplicates)
# Example usage
nums = [4, 3, 2, 7, 8, 2, 3, 1]
print(find_duplicates(nums)) # Output: [2, 3]
Rotate Array: Given an array, rotate the array to the right by k steps, where k is non-negative.
def rotate(nums, k):
k %= len(nums)
nums[:] = nums[-k:] + nums[:-k]
# Example usage
nums = [1, 2, 3, 4, 5, 6, 7]
rotate(nums, 3)
print(nums) # Output: [5, 6, 7, 1, 2, 3, 4]
Merge Two Sorted Lists: Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def merge_two_lists(l1, l2):
dummy = ListNode()
current = dummy
while l1 and l2:
if l1.val <= l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 if l1 else l2
return dummy.next
# Example usage
# List 1: 1 -> 2 -> 4
# List 2: 1 -> 3 -> 4
l1 = ListNode(1, ListNode(2, ListNode(4)))
l2 = ListNode(1, ListNode(3, ListNode(4)))
merged_list = merge_two_lists(l1, l2)
# Output: 1 -> 1 -> 2 -> 3 -> 4 -> 4
Matrix Transpose: Write a function that returns the transpose of a 2D matrix.
def transpose(matrix):
return list(map(list, zip(*matrix)))
# Example usage
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(transpose(matrix))
# Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
These questions cover a range of concepts, including string manipulation, list operations, dictionary usage, and basic algorithmic problem-solving. They are designed to help assess fundamental Python programming skills.