Tất cả thử thách
Dễ 1 người đã giải Tỷ lệ chấp nhận 100.0%

Z-Score Standardization

Center a feature at 0 and scale it to a standard deviation of 1.

Bạn sẽ học được gì

  • Compute the mean and standard deviation
  • Center and scale a feature
  • Handle zero variance

Đề bài

Xem bản dịch

Standardization rescales a feature so it has mean 0 and standard deviation 1, which many models (and gradient descent) work best with:

z = (x - mean) / std

Use the population standard deviation: std = √(Σ(x - mean)² / n). If std is 0 (all values equal), return 0 for every value.

Implement z_scores(values).

Input

values: The values of one feature.

Output

Return the z-score of each value, in the same order.

Ràng buộc

1 ≤ length ≤ 10,000

-1,000,000 ≤ each value ≤ 1,000,000

Ví dụ

Ví dụ 1
Đầu vào:
values = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]

Kết quả mong đợi:
expected = [-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0]
Đầu vào:
std::vector<double> values = {2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0};

Kết quả mong đợi:
std::vector<double> expected = {-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0};
Đầu vào:
double[] values = new double[] {2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0};

Kết quả mong đợi:
double[] expected = new double[] {-1.5, -0.5, -0.5, -0.5, 0.0, 0.0, 1.0, 2.0};

Giải thích

The mean is 40 / 8 = 5 and the population standard deviation is √(32 / 8) = 2, so 2 → (2 - 5) / 2 = -1.5, 4 → -0.5, 5 → 0, 7 → 1 and 9 → 2. Result: [-1.5, -0.5, -0.5, -0.5, 0, 0, 1, 2].

Ví dụ 2
Đầu vào:
values = [3.0, 3.0]

Kết quả mong đợi:
expected = [0.0, 0.0]
Đầu vào:
std::vector<double> values = {3.0, 3.0};

Kết quả mong đợi:
std::vector<double> expected = {0.0, 0.0};
Đầu vào:
double[] values = new double[] {3.0, 3.0};

Kết quả mong đợi:
double[] expected = new double[] {0.0, 0.0};

Giải thích

Both values equal the mean, so the standard deviation is 0 and both z-scores are 0.

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

You need the feature’s center and spread, so start by computing the mean.

Gợi ý 2

Use the population standard deviation, then transform each value by how far it sits from the mean.

Gợi ý 3

When all values match, the spread is zero, so every standardized value should be zero.

Độ phức tạp mong đợi

O(n) time, O(1) extra space

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 RCRiccardo Corti Python 959 ms - 4/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 1 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.