0% found this document useful (0 votes)
2 views

python iv

Python is a high-level, interpreted programming language known for its ease of learning and versatility in applications such as web development and data analysis. Key features include a large standard library, support for multiple data types, control structures, and object-oriented programming concepts like classes and inheritance. The document also covers advanced topics like decorators, generators, and various coding challenges commonly encountered in interviews.

Uploaded by

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

python iv

Python is a high-level, interpreted programming language known for its ease of learning and versatility in applications such as web development and data analysis. Key features include a large standard library, support for multiple data types, control structures, and object-oriented programming concepts like classes and inheritance. The document also covers advanced topics like decorators, generators, and various coding challenges commonly encountered in interviews.

Uploaded by

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

What is Python?

Python is a high-level, interpreted programming language that is widely used for


web development, data analysis, artificial intelligence, and scientific computing.
What are the advantages of using Python?
Python is easy to learn, has a large standard library, is cross-platform, and has a
large and active developer community.

What are the data types in Python?


The basic data types in Python are integers, floats, strings, booleans, and None.

What are the control structures in Python?


Python has if/else statements, loops (for and while), and try/except blocks for
error handling.

What is PEP8?
PEP8 is a style guide for Python code that outlines best practices for formatting
code and naming variables, functions, and classes.

What are decorators in Python?


Decorators are a feature in Python that allow you to modify the behavior of a
function or class without modifying the source code of the function or class.
behaviour

What are generators in Python?


Generators are a type of iterable, like lists or tuples, but unlike lists, they do
not store their contents in memory. Instead, they generate the values on the fly.
for example:parachute

What is a virtual environment in Python?


A virtual environment is a tool in Python that allows you to create an isolated
environment for a Python project with its own dependencies and Python version.

What are modules in Python?


Modules are files containing Python code that can be imported into other Python
code to provide additional functionality.

What is a lambda function in Python?


A lambda function is an anonymous function in Python that can be defined in a
single line of code.

What is the difference between a list and a tuple in Python?


A list is mutable, meaning it can be changed, whereas a tuple is immutable, meaning
it cannot be changed.

What is a dictionary in Python?


A dictionary is a data structure in Python that stores key-value pairs, allowing
you to look up values by their corresponding keys.

What is the difference between a set and a frozenset in Python?


A set is mutable, meaning it can be changed, whereas a frozenset is immutable,
meaning it cannot be changed.

What is the difference between "==" and "is" in Python?


"==" checks if two objects have the same value, whereas "is" checks if two objects
are the same object in memory.

What is the difference between a shallow copy and a deep copy in Python?
A shallow copy of a list or dictionary creates a new object that references the
same elements as the original object. A deep copy creates a new object with new
elements that are copies of the original elements.

What is a class in Python?


A class is a blueprint for creating objects in Python. It contains attributes,
which are variables that hold data, and methods, which are functions that operate
on that data.

What is inheritance in Python?


Inheritance is a mechanism in Python that allows you to create a new class that is
a modified version of an existing class.

What is polymorphism in Python?


Polymorphism is the ability of objects in Python to take on multiple forms,
depending on the context in which they are used.

What are the different ways to handle exceptions in Python?


The different ways to handle exceptions in Python include using try/except blocks,
raising exceptions with the "raise" keyword, and using the "finally" keyword to
execute code regardless of whether an exception is raised.

What is a module in Python?


A module is a file

What is the difference between a list and a tuple in Python?


A list is a mutable data type in Python, meaning it can be changed after it is
created. It is represented by square brackets []. A tuple, on the other hand, is an
immutable data type in Python, meaning it cannot be changed after it is created. It

is represented by parentheses (). Tuples are generally faster than lists, but they
have fewer built-in methods.

What is the difference between a function and a method in Python?


A function is a standalone block of code that performs a specific task. It can be
called from anywhere in the program. A method, on the other hand, is a function
that belongs to a class or an object. It is called on an instance of the class or
the object itself.

What is a decorator in Python?


A decorator is a design pattern in Python that allows us to modify the behavior of
a function or a class without changing its source code. Decorators are implemented
using the "@" symbol, followed by the name of the decorator function. When a
decorated function is called, the decorator function is executed first, and its
return value is used as the actual function.

What is a generator in Python?


A generator is a special type of function in Python that allows us to generate a
sequence of values on the fly, without storing them in memory. It is implemented
using the "yield" keyword, which suspends the function and returns a value to the
caller. The function can then be resumed from where it left off by calling it
again.

What is the difference between "is" and "==" in Python?


The "is" keyword in Python is used to check whether two objects are the same object
in memory. It returns True if they are, and False otherwise. The "==" operator, on
the other hand, is used to check whether two objects have the same value. It
returns True if they do, and False otherwise.

What is the difference between deep and shallow copy in Python?


In Python, when we make a copy of an object, we can either make a shallow copy or a
deep copy. A shallow copy creates a new
object, but it refers to the same memory location as the original object. Any
changes made to the copy will be reflected in
the original object. A deep copy, on the other hand, creates a new object and
copies all the values recursively, so that any
changes made to the copy will not affect the original object.

===============================================================

Write a function that takes in two numbers and returns their sum. done
Write a function that takes in a string and returns the length of the string. done
Write a function that takes in a list of numbers and returns the sum of all the
even numbers in the list. done
Write a function that takes in a list of integers and returns the second-largest
number in the list. done
Write a function that takes in a string and returns the reversed string. done
Write a function that takes in a list of strings and returns a new list with all
the strings capitalized.
Write a function that takes in a list of integers and returns a new list with all
the odd numbers squared.
Write a function that takes in two lists and returns a new list containing the
common elements between the two lists.
Write a function that takes in a list of numbers and returns the product of all the
numbers in the list.
Write a function that takes in a string and returns a new string with all the
vowels removed.
Write a function that takes in a list of integers and returns a new list with all
the duplicates removed.
Write a function that takes in a list of strings and returns a new list with all
the strings that contain the letter "a".
Write a function that takes in a list of numbers and returns a new list with all
the prime numbers in the list.
Write a function that takes in a list of integers and returns the maximum
difference between any two elements in the list.
Write a function that takes in a string and returns True if the string is a
palindrome, False otherwise.
Write a function that takes in a list of strings and returns a new list with all
the strings sorted in alphabetical order.
Write a function that takes in a list of numbers and returns the average of all the
numbers in the list.
Write a function that takes in a list of strings and returns a new list with all
the strings that have a length of at least 5 characters.
Write a function that takes in a list of integers and returns the third-largest
number in the list.
Write a function that takes in a list of numbers and returns the median value of
the list.

now give 5 tricky ones which mostly asked in all companies


Sure, here are 10 tricky Python coding questions that are often asked in
interviews:
Write a Python function to reverse a string.
def reverse_string(s):
return s[::-1]

Write a Python function to check if a given number is a prime number.


def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True

Write a Python function to find the maximum sum of a contiguous subarray of a given
array of integers.
def max_subarray_sum(nums):
max_so_far = max_ending_here = 0
for num in nums:
max_ending_here = max(num, max_ending_here + num)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far

Write a Python function to implement a queue using two stacks.


class Queue:
def __init__(self):
self.in_stack = []
self.out_stack = []

def push(self, x):


self.in_stack.append(x)

def pop(self):
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
return self.out_stack.pop()

def peek(self):
if not self.out_stack:
while self.in_stack:
self.out_stack.append(self.in_stack.pop())
return self.out_stack[-1]

def is_empty(self):
return not self.in_stack and not self.out_stack

Write a Python function to implement a binary search algorithm for a sorted array
of integers.

def binary_search(nums, target):


left = 0
right = len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

Yes, I understand what you're looking for now. Here are 20 common coding questions
in Python with just mathematical formulas and logic:
Write a function to determine if a given number is even.

n % 2 == 0
Write a function to determine if a given number is a prime number.

Use a loop to iterate from 2 to the square root of the number, checking if any
number evenly divides the input number using the modulo operator.
Write a function to calculate the factorial of a given number.

n! = 1 * 2 * 3 * ... * n
Write a function to calculate the Fibonacci sequence up to a given number of terms.

Use a loop to calculate each number in the sequence by adding the previous two
numbers.
Write a function to calculate the area of a triangle given its base and height.

A = 1/2 * base * height


Write a function to calculate the sum of a given list of numbers.

Use a loop to iterate through the list and add up each number.
Write a function to calculate the mean of a given list of numbers.

Mean = sum(list) / len(list)


Write a function to calculate the median of a given list of numbers.

Sort the list, then if the length of the list is odd, return the middle element,
otherwise return the average of the middle two elements.
Write a function to calculate the mode of a given list of numbers.

Use a dictionary to count the frequency of each number in the list, then return the
number with the highest frequency.
Write a function to calculate the GCD (Greatest Common Divisor) of two given
numbers.

Use Euclid's algorithm to repeatedly divide the larger number by the smaller number
and update the numbers until the remainder is 0.
Write a function to calculate the LCM (Least Common Multiple) of two given numbers.

LCM = (n1 * n2) / GCD(n1, n2)


Write a function to determine if a given year is a leap year.

A year is a leap year if it is divisible by 4, unless it is divisible by 100 but


not 400.
Write a function to calculate the sum of the digits of a given number.

Use modulo and integer division to extract each digit and add them together.
Write a function to reverse a given integer.

Convert the integer to a string, reverse the string using slicing, then convert
back to an integer.
Write a function to determine if a given string is a palindrome.

Compare the string to its reverse using slicing.


Write a function to calculate the Euclidean distance between two given points in 2D
space.

Distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)


Write a function to calculate the area of a circle given its radius.
A = pi * r^2
Write a function to calculate the circumference of a circle given its radius.

C = 2 * pi * r
Write a function to convert a given temperature in Celsius to Fahrenheit.

F = C * 9/5 + 32
Write a function to convert a given temperature in Fahrenheit to Celsius.

C = (F - 32) * 5/9

===================================

You're welcome! I'll provide Python solutions for each of the 20 Data Structures
and Algorithms (DSA) questions listed. I'll keep the code clean and concise so you
can easily understand and practice.

---

### **1. Maximum Subarray Sum (Kadane's Algorithm)**

```python
def max_subarray_sum(arr):
max_sum = current_sum = arr[0]
for num in arr[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum

# Example usage
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(max_subarray_sum(arr)) # Output: 6
```

---

### **2. Rotate Array by `k` Positions**

```python
def rotate_array(nums, k):
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k]
return nums

# Example usage
arr = [1, 2, 3, 4, 5, 6, 7]
k = 3
print(rotate_array(arr, k)) # Output: [5, 6, 7, 1, 2, 3, 4]
```

---

### **3. Two Sum Problem**

```python
def two_sum(nums, target):
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num], i]
lookup[num] = i
return []

# Example usage
arr = [2, 7, 11, 15]
target = 9
print(two_sum(arr, target)) # Output: [0, 1]
```

---

### **4. Trapping Rain Water**

```python
def trap(height):
if not height:
return 0
left, right = 0, len(height) - 1
left_max, right_max = height[left], height[right]
water = 0
while left < right:
if left_max < right_max:
left += 1
left_max = max(left_max, height[left])
water += left_max - height[left]
else:
right -= 1
right_max = max(right_max, height[right])
water += right_max - height[right]
return water

# Example usage
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
print(trap(height)) # Output: 6
```

---

### **5. Longest Substring Without Repeating Characters**

```python
def length_of_longest_substring(s):
char_set = set()
left = 0
max_length = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_length = max(max_length, right - left + 1)
return max_length

# Example usage
s = "abcabcbb"
print(length_of_longest_substring(s)) # Output: 3
```

---

### **6. Reverse Words in a String**

```python
def reverse_words(s):
return ' '.join(reversed(s.split()))

# Example usage
s = "the sky is blue"
print(reverse_words(s)) # Output: "blue is sky the"
```

---

### **7. First Non-Repeating Character in a String**

```python
from collections import Counter

def first_unique_char(s):
count = Counter(s)
for idx, char in enumerate(s):
if count[char] == 1:
return idx
return -1

# Example usage
s = "loveleetcode"
print(first_unique_char(s)) # Output: 2
```

---

### **8. Reverse a Linked List**

```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

def reverse_list(head):
prev, current = None, head
while current:
next_temp = current.next
current.next = prev
prev = current
current = next_temp
return prev

# Example usage: Create a list [1 -> 2 -> 3 -> 4 -> 5]


head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
new_head = reverse_list(head) # Output: [5 -> 4 -> 3 -> 2 -> 1]
```
---

### **9. Detect Cycle in Linked List (Floyd’s Algorithm)**

```python
def has_cycle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
```

---

### **10. Merge Two Sorted Linked Lists**

```python
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
```

---

### **11. Find the Middle of a Linked List**

```python
def find_middle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
```

---

### **12. Inorder Traversal of Binary Tree**

```python
def inorder_traversal(root):
res = []
def inorder(node):
if not node:
return
inorder(node.left)
res.append(node.val)
inorder(node.right)
inorder(root)
return res
```

---

### **13. Check if a Binary Tree is Balanced**

```python
def is_balanced(root):
def height(node):
if not node:
return 0
left = height(node.left)
right = height(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return max(left, right) + 1
return height(root) != -1
```

---

### **14. Lowest Common Ancestor in a BST**

```python
def lowest_common_ancestor(root, p, q):
if root.val > p.val and root.val > q.val:
return lowest_common_ancestor(root.left, p, q)
elif root.val < p.val and root.val < q.val:
return lowest_common_ancestor(root.right, p, q)
else:
return root
```

---

### **15. Level Order Traversal (BFS)**

```python
from collections import deque

def level_order(root):
if not root:
return []
queue = deque([root])
result = []
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
```

---

### **16. Convert Sorted Array to a Balanced BST**

```python
def sorted_array_to_bst(nums):
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sorted_array_to_bst(nums[:mid])
root.right = sorted_array_to_bst(nums[mid+1:])
return root
```

---

### **17. Binary Search**

```python
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
```

---

### **18. Kth Largest Element in an Array**

```python
import heapq

def find_kth_largest(nums, k):


return heapq.nlargest(k, nums)[-1]
```

---

### **19. Merge Sort**

```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)

def merge(left, right):


sorted_list = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_list.append(left[i])
i += 1
else:
sorted_list.append(right[j])
j += 1
sorted_list.extend(left[i:])
sorted_list.extend(right[j:])
return sorted_list
```

---

### **20. Find the Missing Number (XOR Method)**

```python
def missing_number(nums):
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing
```

---

These solutions cover

each problem in the list with Python implementations. You can run and test them as
needed!

You might also like