Skip to content

Commit 0e74b01

Browse files
committed
updated
1 parent 3d7cea1 commit 0e74b01

11 files changed

+467
-13
lines changed

.gitattributes

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
* text=auto
2+
.vscode

.vscode/settings.json

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
{
22
"githubPullRequests.ignoredPullRequestBranches": [
33
"master"
4-
]
4+
],
5+
"python.terminal.activateEnvInCurrentTerminal": true,
6+
"python.terminal.activateEnvironment": true,
7+
"python.defaultInterpreterPath": "${workspaceFolder}\\.venv\\Scripts\\python.exe",
8+
"python.analysis.typeCheckingMode": "strict",
59
}
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""1732. Find the Highest Altitude
2+
3+
4+
There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.
5+
You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point.
6+
7+
8+
9+
Example 1:
10+
11+
Input: gain = [-5,1,5,0,-7]
12+
Output: 1
13+
Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
14+
Example 2:
15+
16+
Input: gain = [-4,-3,-2,-1,4,3,2]
17+
Output: 0
18+
Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
19+
20+
21+
Constraints:
22+
23+
n == gain.length
24+
1 <= n <= 100
25+
-100 <= gain[i] <= 100"""
26+
27+
from typing import List
28+
def largestAltitude(gain: List[int]) -> int:
29+
current_altitude = 0
30+
highest_altitude = 0
31+
32+
for g in gain:
33+
current_altitude += g
34+
if current_altitude > highest_altitude:
35+
highest_altitude = current_altitude
36+
37+
return highest_altitude
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def getAverages(nums: list[int], k: int) -> list[int]:
2+
n = len(nums)
3+
avgs = [-1] * n
4+
if 2 * k + 1 > n:
5+
return avgs
6+
7+
# Calculate prefix sums
8+
# Why n + 1? To simplify the sum of elements from the start of the array up to any given point without having to handle special cases.
9+
prefix_sum = [0] * (n + 1)
10+
for i in range(n):
11+
prefix_sum[i + 1] = prefix_sum[i] + nums[i]
12+
13+
# Calculate k-radius averages
14+
for i in range(k, n - k):
15+
# The sum of elements from the start of the array up to i + k + 1 minus the sum of elements from the start of the array up to i - k
16+
total_sum = prefix_sum[i + k + 1] - prefix_sum[i - k]
17+
avgs[i] = total_sum // (2 * k + 1)
18+
19+
return avgs

data_structures/arrays/num_subarray_with_product_less_than_k.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
def num_subarrays_with_product_less_than_k(arr, k):
1+
def num_subarrays_with_product_less_than_k(arr: list[int], k: int) -> int:
22
if k <= 1:
33
return 0
44

data_structures/arrays/permutations.py

+16
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,25 @@ def backtrack(start: int) -> None:
4040
return output
4141

4242

43+
def permute_interleave(nums: list[int]) -> list[list[int]]:
44+
"""
45+
Return all permutations of the given list.
46+
47+
Logic: For each number in the list, we can insert it at any position in the permutations of the remaining numbers
48+
49+
>>> permute_interleave([1, 2, 3])
50+
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
51+
"""
52+
if not nums:
53+
return [[]]
54+
return [
55+
[n] + p for i, n in enumerate(nums) for p in permute_interleave(nums[:i] + nums[i + 1 :])
56+
]
57+
4358
if __name__ == "__main__":
4459
import doctest
4560

4661
result = permute_backtrack([1, 2, 3])
4762
print(result)
63+
print(permute_interleave([1, 2, 3]))
4864
doctest.testmod()

data_structures/hashing/subsets_iterative.py

+115-11
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,54 @@
2020
# subset.pop_back();
2121
# }
2222
# }
23+
def generate_subsets(nums: list[int]) -> list[list[int]]:
24+
"""
25+
Explanation of the Code
26+
Initialization:
27+
28+
generate_subsets(nums): Initializes an empty list result to store all subsets and calls the backtrack function starting from the first index.
29+
Backtracking Function:
30+
31+
backtrack(start, current): A recursive function that generates all subsets starting from index start and using the current subset current.
32+
Base Case: The base case is implicitly handled by the loop termination. When start equals the length of nums, there are no more elements to consider.
33+
Recursive Step:
34+
35+
For each element starting from start to the end of the list nums, the function explores two possibilities:
36+
Include: Add nums[i] to the current subset current and call backtrack recursively with the next index (i + 1).
37+
Exclude: Remove nums[i] from current (backtrack) and proceed to the next iteration.
38+
Adding Subsets:
39+
40+
Every time backtrack is called, the current subset current is added to the result list result. This ensures that all subsets are captured.
41+
Example Usage
42+
For nums = [1, 2, 3], the function generates the following subsets:
43+
44+
Start with an empty subset: []
45+
Include 1: [1]
46+
Include 2: [1, 2]
47+
Include 3: [1, 2, 3]
48+
Backtrack to exclude 3: [1, 2]
49+
Backtrack to exclude 2 and include 3: [1, 3]
50+
Backtrack to exclude 1 and include 2: [2]
51+
Include 3: [2, 3]
52+
Backtrack to exclude 3: [2]
53+
Backtrack to exclude 2 and include 3: [3]
54+
Backtrack to exclude 3: []"""
55+
def backtrack(start: int, current: list[int]) -> None:
56+
# Add the current subset to the result list
57+
result.append(current[:])
58+
59+
for i in range(start, len(nums)):
60+
# Include nums[i] in the current subset
61+
current.append(nums[i])
62+
# Move to the next element
63+
backtrack(i + 1, current)
64+
# Exclude nums[i] from the current subset (backtrack)
65+
current.pop()
66+
67+
result: list[list[int]] = []
68+
backtrack(0, [])
69+
return result
70+
2371

2472
def search(k: int, n: int, subset: list[Any], all_subsets: list[list[Any]]):
2573
"""
@@ -45,12 +93,14 @@ def search(k: int, n: int, subset: list[Any], all_subsets: list[list[Any]]):
4593
# Include nums[k] in the subset
4694
# The element k is then added to the subset, and search(k + 1) is called again to include the current element in the subset.
4795
subset.append(k)
96+
print(f"included {k} index in subset: {subset}")
4897
search(k + 1, n, subset, all_subsets)
4998

5099
subset.pop()
100+
print(f"removed {k} index from subset: {subset}")
51101

52102
def subsets_recursive(nums: List[int]) -> List[List[int]]:
53-
all_subsets = []
103+
all_subsets: list[list[int]] = []
54104
search(0, len(nums), [], all_subsets)
55105
return all_subsets
56106

@@ -66,13 +116,67 @@ def subsets_recursive(nums: List[int]) -> List[List[int]]:
66116
# return result
67117

68118

69-
# def subsets_bitmask(nums: List[int]) -> List[List[int]]:
70-
# n = len(nums)
71-
# result = []
72-
# for i in range(1 << n):
73-
# subset = []
74-
# for j in range(n):
75-
# if i & (1 << j):
76-
# subset.append(nums[j])
77-
# result.append(subset)
78-
# return result
119+
def generate_subsets(n: int) -> list[list[int]]:
120+
"""
121+
Explanation of the Python Code
122+
Outer Loop (for b in range(1 << n)):
123+
124+
The variable b ranges from 0 to 2^n - 1.
125+
1 << n is equivalent to 2^n, so this loop iterates 2^n
126+
times, generating all possible subsets.
127+
128+
Inner Loop (for i in range(n)):
129+
130+
For each value of b, this loop checks each bit position i from 0 to n-1.
131+
Bit Check (if b & (1 << i)):
132+
133+
1 << i creates a number with only the i-th bit set.
134+
b & (1 << i) checks if the i-th bit in b is set.
135+
If the i-th bit is set, it means the i-th element is included in the current subset.
136+
Subset Construction (subset.append(i)):
137+
138+
If the bit check is true, the i-th element is added to the current subset.
139+
Collecting All Subsets (all_subsets.append(subset)):
140+
141+
Each generated subset is added to the list all_subsets."""
142+
all_subsets: list[list[int]] = []
143+
for b in range(1 << n): # Iterate over all possible subsets
144+
subset: list[int] = []
145+
for i in range(n): # Check each bit position
146+
if b & (1 << i): # If the ith bit is set, include i in the subset
147+
subset.append(i)
148+
all_subsets.append(subset)
149+
return all_subsets
150+
151+
# Example usage
152+
n = 3
153+
subsets = generate_subsets(n)
154+
print(subsets) # Output: [[], [0], [1], [0, 1], [2], [0, 2], [1, 2], [0, 1, 2]]
155+
156+
def generate_subsets(nums: list[Any]) -> list[list[Any]]:
157+
n = len(nums)
158+
all_subsets: list[list[Any]] = []
159+
160+
for b in range(1 << n): # Iterate over all possible subsets (2^n subsets)
161+
subset = [nums[i] for i in range(n) if b & (1 << i)] # Use list comprehension to build the subset
162+
all_subsets.append(subset)
163+
164+
return all_subsets
165+
166+
# Example usage
167+
nums = [1, 2, 3]
168+
subsets = generate_subsets(nums)
169+
print(subsets)
170+
171+
def binary_and(str1: str, str2: str) -> str:
172+
# Remove '0b' prefix and ensure equal lengths
173+
str1 = str1[2:].zfill(max(len(str1), len(str2)) - 2)
174+
str2 = str2[2:].zfill(max(len(str1), len(str2)) - 2)
175+
176+
result = ""
177+
for i in range(len(str1)):
178+
result += '1' if str1[i] == '1' and str2[i] == '1' else '0'
179+
return '0b' + result
180+
181+
combined_binary = binary_and(bin(1), bin(1 << 2))
182+
print(combined_binary) # Output: 0b0

mypy.ini

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[mypy]
2+
plugins =
3+
returns.contrib.mypy.returns_plugin

0 commit comments

Comments
 (0)