You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: app/docs/CommunityShare/Leetcode/9021_TUT_3_25T1.md
+45-32Lines changed: 45 additions & 32 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,22 +2,24 @@
2
2
title: 9021_TUT_3_25T1.md
3
3
date: 2025/3/07
4
4
tags:
5
-
- '9021'
5
+
- "9021"
6
6
- lab
7
7
abbrlink: 974decd3
8
+
docId: s0cadbu09dgu54q0zxttkx7z
8
9
---
9
10
10
11
# Exercise 1
11
12
12
13
### Problem Description:
14
+
13
15
You are given two integers, `m` and `n`, where:
14
16
15
17
-`m` represents the number of repeated units (patterns).
16
18
-`n` represents the number of elements (underscores) within each unit.
17
19
18
20
The goal is to generate a string where:
19
21
20
-
- Each unit contains `n` underscores (_), separated by `|`.
22
+
- Each unit contains `n` underscores (\_), separated by `|`.
21
23
- These units are then concatenated together, separated by `*`.
22
24
23
25
### My Solution:
@@ -57,7 +59,6 @@ In summary, my solution focuses on modularity by breaking down the problem into
57
59
58
60
# Exercise 2
59
61
60
-
61
62
### Problem Description:
62
63
63
64
The goal is to generate a pattern based on the digits of a given number n. Specifically:
@@ -82,19 +83,17 @@ def f2(n):
82
83
#### My Thought Process:
83
84
84
85
1. Loop through each digit:
85
-
Convert the number n to a string to iterate over each digit individually.
86
+
Convert the number n to a string to iterate over each digit individually.
86
87
87
88
2. Check if the digit is even or odd:
88
-
Convert each digit back to an integer and use the modulus operator (% 2) to check if the digit is even or odd.
89
+
Convert each digit back to an integer and use the modulus operator (% 2) to check if the digit is even or odd.
89
90
90
91
3. Append the corresponding square:
91
92
- If the digit is even, append a white square (⬜) to the result string.
92
93
- If the digit is odd, append a black square (⬛).
93
94
94
95
4. Print the final string:
95
-
After processing all the digits, print the final string containing black and white squares.
96
-
97
-
96
+
After processing all the digits, print the final string containing black and white squares.
98
97
99
98
### Standard Solution:
100
99
@@ -104,6 +103,7 @@ def f2(n):
104
103
```
105
104
106
105
Dr.Martin's solution is:
106
+
107
107
1. More compact and Pythonic.
108
108
2. Uses a dictionary and list comprehension for brevity and efficiency.
109
109
3. The Unicode characters for the squares are referenced directly using their escape sequences (`\u2b1c` for white, `\u2b1b` for black).
@@ -115,9 +115,10 @@ Dr.Martin's solution is:
115
115
In this task, the number `n` is treated as a number expressed in different bases (ranging from 2 to 10), and we aim to convert it into its corresponding base 10 value for each of these bases, where the conversion is valid.
116
116
117
117
For n = 2143:
118
-
-`2143` in base `5` is equivalent to `298` in base `10`.
119
-
-`2143` in base `6` is equivalent to `495` in base `10`.
120
-
- And so on.
118
+
119
+
-`2143` in base `5` is equivalent to `298` in base `10`.
120
+
-`2143` in base `6` is equivalent to `495` in base `10`.
121
+
- And so on.
121
122
122
123
The goal is to iterate over different base systems from 2 to 10, treat the input number `n` as if it is expressed in each base, and then convert it to base 10.
123
124
@@ -133,7 +134,9 @@ def f3(n: int):
133
134
exceptValueError:
134
135
pass
135
136
```
137
+
136
138
#### My Thought Process:
139
+
137
140
1. Iterating over Bases (2 to 10):
138
141
- We loop through the base values i ranging from 2 to 10.
139
142
@@ -146,16 +149,16 @@ def f3(n: int):
146
149
- The `try-except` block ensures that invalid bases are skipped, allowing us to handle cases where the digits in `n` are not valid for a particular base.
147
150
148
151
### Standard Solution:
149
-
152
+
150
153
```python
151
154
deff3(n):
152
155
n_as_string =str(n)
153
156
min_base =max(2, max({int(d) for d in n_as_string}) +1)
154
157
for b inrange(min_base, 11):
155
158
print(f'{n} is {int(n_as_string, b)} in base {b}')
156
159
```
157
-
It skips the bases where the digits in n are not valid, and it uses a set comprehension to extract the unique digits from n_as_string. The maximum digit is then used to determine the minimum base to start iterating from.
158
160
161
+
It skips the bases where the digits in n are not valid, and it uses a set comprehension to extract the unique digits from n_as_string. The maximum digit is then used to determine the minimum base to start iterating from.
159
162
160
163
# Exercise 4
161
164
@@ -194,23 +197,25 @@ def f4(n: int, base: int):
194
197
- After collecting all digits, we reverse the list and return it as a string.
195
198
196
199
2. Main Function `f4(n, base)`:
197
-
We initialize an empty dictionary `D`.
198
-
For each number `i` from `0` to `n`, we convert `i` to the given base using `convert_to_base()`.
199
-
The converted base digits are then mapped to integers and stored in a tuple as the value for each key `i` in the dictionary.
200
+
We initialize an empty dictionary `D`.
201
+
For each number `i` from `0` to `n`, we convert `i` to the given base using `convert_to_base()`.
202
+
The converted base digits are then mapped to integers and stored in a tuple as the value for each key `i` in the dictionary.
200
203
201
204
### Explanation of Why `map()` is not Pythonic:
205
+
202
206
In the function f4, the use of `map(int, convert_to_base(i, base))` applies the `int` function
203
207
to each element of the result from `convert_to_base`, effectively converting each character to an integer.
204
208
205
209
However, it's worth noting that the `map()` function, which originates from functional programming,
206
210
has largely been superseded by more Pythonic constructs such as list comprehensions.
207
211
208
212
These comprehensions are generally considered superior for several reasons:
209
-
- They are more elegant and concise.
210
-
- They tend to be shorter in terms of syntax, making the code easier to read.
211
-
- They are easier to understand for most people, especially those who are more familiar with Python's
212
-
standard syntax rather than functional programming constructs.
213
-
- In many cases, they are also more efficient in terms of performance.
213
+
214
+
- They are more elegant and concise.
215
+
- They tend to be shorter in terms of syntax, making the code easier to read.
216
+
- They are easier to understand for most people, especially those who are more familiar with Python's
217
+
standard syntax rather than functional programming constructs.
218
+
- In many cases, they are also more efficient in terms of performance.
214
219
215
220
For example, instead of using `map(int, ...)`, the same functionality could be achieved with a
216
221
list comprehension, like so:
@@ -240,9 +245,11 @@ whereas the standard solution is more concise and directly integrates the conver
240
245
# Exercise 5
241
246
242
247
At the first, try to run this:
248
+
243
249
```python
244
250
print(0.1+0.2)
245
251
```
252
+
246
253
What happened? The result is not 0.3, but 0.30000000000000004. Why?
247
254
248
255
### Problem Description:
@@ -252,6 +259,7 @@ The approach we are using in this exercise is designed to expose the limitations
252
259
This problem can seem complex, and it's designed to highlight the subtleties of floating-point arithmetic. Let's walk through the logic using the test cases to figure out what the function does.
253
260
254
261
### Key Concepts:
262
+
255
263
-**Floating-point numbers**: Computers store floating-point numbers using a binary format, which often introduces precision errors.
256
264
-**Precision**: We’re working with two types of precision in this function—simple precision (same as the length of the fractional part) and double precision (twice that length).
257
265
@@ -261,22 +269,22 @@ This problem can seem complex, and it's designed to highlight the subtleties of
261
269
deff5(integral_part, fractional_part):
262
270
# Calculate the number of digits in the fractional part
263
271
precision =len(str(fractional_part))
264
-
272
+
265
273
# Concatenate the integral and fractional parts as strings, then convert to a float
# Format the float with precision equal to twice the number of fractional digits (double precision)
275
283
double_precision =f'{a_float:.{precision *2}f}'
276
-
284
+
277
285
# Print the first part of the output
278
286
print('With', precision *2, 'digits after the decimal point, ', end='')
279
-
287
+
280
288
# Compare if extended precision and double precision values are the same
281
289
if extended_simple_precision == double_precision:
282
290
# If they are the same, it means the float is precise and has trailing zeros
@@ -307,6 +315,7 @@ We are required to sort the list L by using a multi-key sorting mechanism, where
307
315
- Finally, if required, the sorting proceeds up to the last field in `fields`.
308
316
309
317
### Example of Fields Explanation:
318
+
310
319
If `fields = [2, 1]`, it means:
311
320
312
321
1. First, sort based on the second element of each sublist.
@@ -320,39 +329,43 @@ def f6(L, fields):
320
329
```
321
330
322
331
1. Sorting with sorted():
323
-
The `sorted()` function is used to sort the list `L`.
324
-
The key parameter defines how the sorting will be performed.
332
+
The `sorted()` function is used to sort the list `L`.
333
+
The key parameter defines how the sorting will be performed.
325
334
326
335
2. Lambda Function:
327
-
The lambda function defines how the sublists will be sorted. It generates a list of values for each sublist based on the positions specified in `fields`.
328
-
For example, if `fields = [2, 1]`, the lambda function will extract the second and first elements from each sublist in that order, and sorting will be done based on this new list.
336
+
The lambda function defines how the sublists will be sorted. It generates a list of values for each sublist based on the positions specified in `fields`.
337
+
For example, if `fields = [2, 1]`, the lambda function will extract the second and first elements from each sublist in that order, and sorting will be done based on this new list.
329
338
330
339
3. Key Structure:
331
-
The key is a list of elements from each sublist, indexed by the positions specified in fields. We use `x[i - 1]` because fields is `1-based`, and list indexing in Python is `0-based`.
340
+
The key is a list of elements from each sublist, indexed by the positions specified in fields. We use `x[i - 1]` because fields is `1-based`, and list indexing in Python is `0-based`.
332
341
333
342
4. What is Lambda Function?
334
343
335
344
For example:
336
345
337
346
We have:
347
+
338
348
```python
339
349
f =lambdax: x * x
340
350
```
341
351
342
352
This is equivalent to:
353
+
343
354
```python
344
355
deff(x):
345
356
return x * x
346
357
```
347
358
348
359
And lambda function in a sorted function is used to define a custom sorting key.
360
+
349
361
```python
350
362
L = [(1,2), (3,1), (5,0)]
351
363
352
364
SortedL =sorted(L, key=lambdax: x[1])
353
365
354
366
print(SortedL)
355
367
```
368
+
356
369
The result is: `[(5, 0), (3, 1), (1, 2)]`, it sorts the list based on the second element of each tuple.
0 commit comments