python iv
python iv
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 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.
is represented by parentheses (). Tuples are generally faster than lists, but they
have fewer built-in methods.
===============================================================
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.
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
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.
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.
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.
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.
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.
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.
---
```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
```
---
```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]
```
---
```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]
```
---
```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
```
---
```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
```
---
```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"
```
---
```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
```
---
```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
```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
```
---
```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
```
---
```python
def find_middle(head):
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
```
---
```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
```
---
```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
```
---
```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
```
---
```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
```
---
```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
```
---
```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
```
---
```python
import heapq
---
```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)
---
```python
def missing_number(nums):
missing = len(nums)
for i, num in enumerate(nums):
missing ^= i ^ num
return missing
```
---
each problem in the list with Python implementations. You can run and test them as
needed!