Why do many programmers use assert() function in their codes giving as its argument the answer to be outputed?
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | awoo | 154 |
8 | Dominater069 | 154 |
10 | luogu_official | 150 |
Why do many programmers use assert() function in their codes giving as its argument the answer to be outputed?
Name |
---|
Some judging systems provide full report of a submitted solution with the error codes the program returned. That why several coders use the following trick:
Let's assume you submitted code on ACM rules and got WA. In some situations with the input consisting of few numbers it is possible to find out such test. You only need to estimate amount of "interesting" tests and assert them.
E.g., if you asked to find all the numbers generated by permutating 1 and 0 in binary form of given N. If you failed Test #6, you can do
assert(N>=1000)
and it will cause RE if N<1000. So you can get N from the test using K times binary search (N>500&&N<1000, N>250&&N<500 and etc.).It doesn't worth it in ACM rules. But it's good for OI rules.
if N ≥ 1000
Yes, thanks a lot! I have corrected it
In short: because it's a good way of continuous local testing. They give you additional way of checking your program, and this doesn't even need your assistance after writing — your program checks its invariants during each run.
Say, you have some invariant in your code, which is essential for further work and it's easy to test. But sometimes, when it is not provided, answer is still correct. That's totally uncool, if you want to find all bugs. If you check this invariant with assertion, you will see that it is broken even if the answer on this particular test would be correct.
Another usecase: imagine that you have some data structure in your code. To be sure that it works correctly, you can add another implementation (say, O(n2)) and check with assertions that answers that both of these implementations provide are similar (locally only, of course). That way, if you get wrong answer locally, you know that it is not because of your data structures. And, similarly, if assertion fails inside of them, you know that something is definitely wrong.
History from KOTEHOK: one day he was participating in Google Code Jam. He successfully submitted small input and downloaded large input. Some assertion failed during run on large input. He rushed into his code and managed to locate a bug, fix it and submit correct answers. So, if it wasn't for assertions, he would be unable to understand that answers are wrong.