Skip to content

Commit 33ead5b

Browse files
Merge branch 'main' into log-entry
2 parents 2f50a1b + b48a6ef commit 33ead5b

File tree

3 files changed

+160
-160
lines changed

3 files changed

+160
-160
lines changed
Lines changed: 75 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,111 @@
11
---
22
Title: '.sort()'
3-
Description: 'Returns an array with its items sorted in place.'
3+
Description: 'Sorts the elements of an array in place.'
44
Subjects:
5-
- 'Web Development'
65
- 'Computer Science'
6+
- 'Web Development'
77
Tags:
88
- 'Arrays'
9-
- 'Comparison'
109
- 'Functions'
1110
- 'Methods'
12-
- 'Sort'
13-
- 'Unicode'
11+
- 'Values'
1412
CatalogContent:
1513
- 'introduction-to-javascript'
1614
- 'paths/front-end-engineer-career-path'
1715
---
1816

19-
The **`.sort()`** method returns an array with its items sorted in place.
17+
The JS **`.sort()`** [method](https://www.codecademy.com/resources/docs/javascript/methods) is used to sort the elements of an array in place. By default, it sorts elements as [strings](https://www.codecademy.com/resources/docs/javascript/strings) in ascending order. However, a custom comparison [function](https://www.codecademy.com/resources/docs/javascript/functions) can be provided to achieve more advanced sorting.
2018

21-
## Syntax
19+
## JS `.sort()` Syntax
2220

2321
```pseudo
24-
// No parameters
25-
array.sort();
26-
27-
// With optional function
28-
array.sort((firstElement, secondElement) => { /* function body */ };
22+
arr.sort(compareFn)
2923
```
3024

31-
If the `.sort()` method is used with no arguments, all items with `undefined` values are shifted to the end of the array while the remaining items are converted to [strings](https://www.codecademy.com/resources/docs/javascript/strings) and sorted by [Unicode code point value](https://en.wikipedia.org/wiki/Code_point).
25+
**Parameters:**
3226

33-
An optional function is used to define how items are sorted. This is done by iterating over the `array` and comparing every `firstElement` and `secondElement` in the `/* function body */`.
27+
- `compareFn` (Optional): A function that defines the sort order. It takes two arguments, `a` and `b`, and should return:
28+
- A negative value if `a` should come before `b`
29+
- `0` if `a` and `b` are considered equal
30+
- A positive value if `a` should come after `b`
3431

35-
## Example
32+
**Return value:**
3633

37-
In the following example, the `.sort()` method is applied to two arrays, `letters` and `numbers` (a mix of floats and integers):
34+
JS `.sort()` returns the original array with its elements sorted in the given order.
3835

39-
```js
40-
const letters = ['d', 'b', 'e', 'a', 'c'];
41-
const numbers = [5, 2, 123, 5.01, 43.5];
36+
## Example 1: Sorting Array of Strings Using JS `.sort()`
4237

43-
console.log('Letters: ', letters.sort());
44-
console.log('Numbers: ', numbers.sort());
38+
This example uses JS `.sort()` to sort an array of strings:
39+
40+
```js
41+
const fruits = ['banana', 'apple', 'cherry', 'date'];
42+
fruits.sort();
43+
console.log(fruits);
4544
```
4645

47-
This results in the following output:
46+
Here is the output:
4847

4948
```shell
50-
Letters: [ 'a', 'b', 'c', 'd', 'e' ]
51-
Numbers: [ 123, 2, 43.5, 45, 5, 5.01 ]
49+
[ 'apple', 'banana', 'cherry', 'date' ]
5250
```
5351

54-
The `letters` were sorted in alphabetical order. The items in `numbers` were sorted based on the leading number in the item's value (e.g., their Unicode value). Sorting numerical values more strictly requires a custom comparison function.
52+
## Example 2: Sorting Array of Numbers Using JS `.sort()`
5553

56-
## Codebyte Example
54+
This example uses JS `.sort()` with a comparison function to sort an array of numbers:
5755

58-
The following example showcases how the optional `callback` argument can be used to sort a `numbers` array in ascending and descending order:
56+
```js
57+
const numbers = [10, 5, 20, 1, 100];
58+
numbers.sort((a, b) => a - b);
59+
console.log(numbers);
60+
```
61+
62+
Here is the output:
63+
64+
```shell
65+
[ 1, 5, 10, 20, 100 ]
66+
```
67+
68+
## Codebyte Example: Sorting Array of Objects Using JS `.sort()`
69+
70+
This codebyte example uses JS `.sort()` to sort an array of objects:
5971

6072
```codebyte/javascript
61-
const numbers = [5, 2, 123, 5.01, 43.5];
73+
const users = [
74+
{ name: "Alice", age: 25 },
75+
{ name: "Bob", age: 20 },
76+
{ name: "Charlie", age: 30 }
77+
];
78+
79+
users.sort((a, b) => a.age - b.age);
6280
63-
const ascending = numbers.sort((a, b) => a - b);
64-
console.log("Ascending order: ", ascending);
81+
console.log(users);
82+
```
83+
84+
## Frequently Asked Questions
85+
86+
### 1. How do I sort numbers in descending order using JS `.sort()`?
87+
88+
You can reverse the comparison in your function in JS `.sort()` to sort numbers in descending order:
89+
90+
```js
91+
numbers.sort((a, b) => b - a);
92+
```
93+
94+
### 2. Can I use `sort()` on a string?
6595

66-
const descending = numbers.sort((a, b) => b - a);
67-
console.log("Descending order: ", descending);
96+
No. The `sort()` method is only available on arrays, not on strings. If you want to sort the characters of a string, you first need to convert it into an array (for example, using `split()`), apply `sort()`, and then join it back:
97+
98+
```js
99+
const str = 'hello';
100+
const sorted = str.split('').sort().join('');
101+
console.log(sorted); // "ehllo"
102+
```
103+
104+
### 3. What happens when `sort()` is used in a list (array)?
105+
106+
When you call `sort()` on an array, JavaScript converts the elements to strings by default and compares them in Unicode code point order. This means that numbers may not sort as you expect:
107+
108+
```js
109+
const numbers = [10, 1, 5];
110+
console.log(numbers.sort()); // [1, 10, 5] (string comparison)
68111
```

content/javascript/concepts/sort/sort.md

Lines changed: 0 additions & 112 deletions
This file was deleted.

content/pytorch/concepts/tensors/terms/randn/randn.md

Lines changed: 85 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,45 +5,114 @@ Subjects:
55
- 'Data Science'
66
- 'Machine Learning'
77
Tags:
8+
- 'Python'
89
- 'PyTorch'
910
- 'Tensors'
11+
- 'Values'
1012
CatalogContent:
1113
- 'intro-to-py-torch-and-neural-networks'
1214
- 'py-torch-for-classification'
1315
---
1416

15-
The **`.randn()`** function in PyTorch generates a tensor with random numbers drawn from a normal distribution with a mean of _0_ and a standard deviation of _1_. This function is particularly useful for initializing weights in neural networks and for other purposes requiring randomized data, especially in machine learning applications.
17+
The **`torch.randn()`** function in PyTorch generates a [tensor](https://www.codecademy.com/resources/docs/pytorch/tensors) with random numbers drawn from a standard normal distribution (mean = 0, variance = 1). This function is particularly useful for initializing weights in [neural networks](https://www.codecademy.com/resources/docs/ai/neural-networks) and for other purposes requiring randomized data, especially in machine learning applications.
1618

17-
## Syntax
19+
## `torch.randn()` Syntax
1820

1921
```pseudo
20-
torch.randn(*size, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False)
22+
torch.randn(*size, *, generator=None, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False)
2123
```
2224

25+
**Parameters:**
26+
2327
- `*size`: Specifies the shape of the output tensor. This can be one or more integers, defining the dimensions of the tensor.
24-
- `out` (optional): A tensor where the result will be stored. If specified, the output is stored in this tensor; otherwise, a new tensor is created.
25-
- `dtype` (optional): The desired data type of the returned tensor.
26-
- `layout` (optional): The desired layout of the returned tensor. The default is `torch.strided`.
27-
- `device` (optional): The device on which the tensor is allocated.
28-
- `requires_grad` (optional): If set to `True`, PyTorch will track operations on the tensor for automatic differentiation. Defaults to `False`.
28+
- `generator` (Optional): A pseudorandom number generator for sampling.
29+
- `out` (Optional): A tensor where the result will be stored. If specified, the output is stored in this tensor; otherwise, a new tensor is created.
30+
- `dtype` (Optional): The desired data type of the returned tensor.
31+
- `layout` (Optional): The desired layout of the returned tensor. The default is `torch.strided`.
32+
- `device` (Optional): The device on which the tensor is allocated.
33+
- `requires_grad` (Optional): If set to `True`, PyTorch will track operations on the tensor for automatic differentiation. Defaults to `False`.
34+
- `pin_memory` (Optional): If set to `True`, the tensor will be allocated in page-locked memory, which can speed up data transfer to CUDA devices.
35+
36+
**Return value:**
37+
38+
Returns a tensor of the specified shape, containing random numbers drawn from a normal distribution.
2939

30-
## Example
40+
## Example 1: Basic Usage of `torch.randn()`
3141

32-
The following example uses `.randn()` to create a 4x4 tensor with random values from a normal distribution:
42+
This example uses `torch.randn()` to create a 4x4 tensor with random values from a normal distribution:
3343

3444
```py
3545
import torch
46+
3647
tensor = torch.randn(4, 4)
48+
49+
print(tensor)
50+
```
51+
52+
Here is the output:
53+
54+
```shell
55+
tensor([[ 1.6012, 0.1432, 2.1874, 1.1822],
56+
[-1.4331, -1.4752, 1.5541, 1.1185],
57+
[ 0.2751, -0.7885, -1.0202, -0.7851],
58+
[ 0.8050, -0.6548, 1.7703, -1.3595]])
59+
```
60+
61+
> **Note:** This code may generate a random output each time it is run, as `torch.randn()` produces random values from a normal distribution.
62+
63+
## Example 2: Specifying Device and Data Type in `torch.randn()`
64+
65+
This example uses `torch.randn()` to create a 4×4 tensor on the CPU with double precision:
66+
67+
```py
68+
import torch
69+
70+
tensor = torch.randn(4, 4, device='cpu', dtype=torch.float64)
71+
3772
print(tensor)
3873
```
3974

40-
This produces the following output:
75+
Here is the output:
4176

4277
```shell
43-
tensor([[-0.7484, 1.2086, 0.3430, 0.6699],
44-
[ 0.7022, 0.0815, 0.4855, 0.1603],
45-
[-0.1214, 0.2484, 1.5672, -0.7005],
46-
[ 1.3106, -0.6518, 0.7351, -0.1027]])
78+
tensor([[-0.8092, -0.6702, -0.6960, 0.2639],
79+
[ 0.6808, 0.5304, -0.8820, -0.7556],
80+
[ 0.1226, -1.0764, 0.9428, 1.4216],
81+
[-0.5007, 1.3984, 0.0343, -1.1393]], dtype=torch.float64)
4782
```
4883

49-
**Note:** This code will generate a different random output each time it is run, as `.randn()` produces random values from a normal distribution.
84+
## Example 3: Using `requires_grad` in `torch.randn()`
85+
86+
This example uses `torch.randn()` with `requires_grad` set to `True` to create a 4×4 tensor with gradient tracking:
87+
88+
```py
89+
import torch
90+
91+
tensor = torch.randn(4, 4, requires_grad=True)
92+
93+
print(tensor)
94+
```
95+
96+
Here is the output:
97+
98+
```shell
99+
tensor([[ 0.8901, 0.6525, -0.7170, -1.2236],
100+
[-1.7839, 0.0180, -0.8420, 0.6561],
101+
[ 0.1359, 0.8233, -0.4252, 0.7597],
102+
[-1.1085, 0.9300, 0.1958, -0.9679]], requires_grad=True)
103+
```
104+
105+
## Frequently Asked Questions
106+
107+
### 1. What does randn do in PyTorch?
108+
109+
`torch.randn()` creates a tensor containing random numbers drawn from a normal distribution.
110+
111+
### 2. What is the difference between `torch.rand()` and `torch.randn()`?
112+
113+
- `torch.rand()` generates numbers evenly spread between `0` and `1`.
114+
- `torch.randn()` generates numbers based on the bell curve, centered at `0` with most values falling between `-3` and `3`.
115+
116+
### 3. What is the range of `torch.randn()`?
117+
118+
Theoretically, values for `torch.randn()` range from negative infinity to positive infinity because of the normal distribution. However, in practice, most values are between `-3` and `3`.

0 commit comments

Comments
 (0)