Try to solve problems in JavaScript, Python, and Java.
This is TIL(memo of key learnings) for solving problems in these languages,
but mostly python.
241214
In Python, a member variable is defined inside a class by assigning a value to it in the init method, like a constructor in js, it create a instance of the class.
Member variables are then bound to instances of the class, use self to refer to a instance-level variables
class MyClass:
def __init__(self, value):
self.member_var = value # This is a member variable
array[:] to copy the array in python? (shallow copy)Data integrity:
- Protecting the original data
- Independent data manipulation
You should create a shallow copy of nums, to ensures that self.origin points to a new list, independent nums, while preserving the integrity of the original data.
it pronounce as νΌμ -μμ΄μΈ μ ν (λμ€ μ ν)
Fisher-Yates shuffle is an algorithm for randomly shuffling a list in-place.
π ensures a uniform random shuffle, with time complexity O(n).
π no additional memory, because it shuffles in-place.
import random
def fisher_yates_shuffle(nums):
for i in range(len(nums) - 1, 0, -1):
j = random.randint(0, i)
nums[i], nums[j] = nums[j], nums[i]
return nums
random in python, how to use it?random.sample is slower than random.shuffle?random.shuffle() and random.sample()Shallow copy of an array or collection can be done using the clone(), it functions like ArrayList's constructor for lists.
// shallow copy for an array
int[] original = {1, 2, 3};
int[] copy = original.clone();
// shallow copy for an ArrayList
ArrayList<Integer> originalList = new ArrayList<>(Arrays.asList(1, 2, 3));
ArrayList<Integer> copyList = new ArrayList<>(originalList);
Declaring the Random object as a class-level field (instance variable), to ensures that you only create object once per instance of the class.
π avoids unnecessary object creation.
public class Solution {
private Random random = new Random(); // class-level field
public int[] shuffle() {
// use the class-level random object
int j = random.nextInt(i + 1);
}
}