blog/assets/js/9eb50c57.23f36b2e.js
github-actions[bot] 70bdf5ed11 deploy: d91860e0f7
2023-09-07 18:30:53 +00:00

1 line
No EOL
23 KiB
JavaScript

"use strict";(self.webpackChunkfi=self.webpackChunkfi||[]).push([[7509],{3905:(e,t,n)=>{n.d(t,{Zo:()=>c,kt:()=>d});var i=n(7294);function o(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,i)}return n}function r(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){o(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t){if(null==e)return{};var n,i,o=function(e,t){if(null==e)return{};var n,i,o={},a=Object.keys(e);for(i=0;i<a.length;i++)n=a[i],t.indexOf(n)>=0||(o[n]=e[n]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)n=a[i],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}var l=i.createContext({}),p=function(e){var t=i.useContext(l),n=t;return e&&(n="function"==typeof e?e(t):r(r({},t),e)),n},c=function(e){var t=p(e.components);return i.createElement(l.Provider,{value:t},e.children)},m="mdxType",u={inlineCode:"code",wrapper:function(e){var t=e.children;return i.createElement(i.Fragment,{},t)}},h=i.forwardRef((function(e,t){var n=e.components,o=e.mdxType,a=e.originalType,l=e.parentName,c=s(e,["components","mdxType","originalType","parentName"]),m=p(n),h=o,d=m["".concat(l,".").concat(h)]||m[h]||u[h]||a;return n?i.createElement(d,r(r({ref:t},c),{},{components:n})):i.createElement(d,r({ref:t},c))}));function d(e,t){var n=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var a=n.length,r=new Array(a);r[0]=h;var s={};for(var l in t)hasOwnProperty.call(t,l)&&(s[l]=t[l]);s.originalType=e,s[m]="string"==typeof e?e:o,r[1]=s;for(var p=2;p<a;p++)r[p]=n[p];return i.createElement.apply(null,r)}return i.createElement.apply(null,n)}h.displayName="MDXCreateElement"},6239:(e,t,n)=>{n.r(t),n.d(t,{assets:()=>l,contentTitle:()=>r,default:()=>u,frontMatter:()=>a,metadata:()=>s,toc:()=>p});var i=n(7462),o=(n(7294),n(3905));const a={id:"postcondition-ambiguity",title:"Vague postconditions and proving correctness of algorithms",description:"Debugging and testing with precise postconditions.\n",tags:["python","testing","postconditions","sorting"],last_update:{date:new Date("2021-03-18T00:00:00.000Z")}},r=void 0,s={unversionedId:"algorithms-correctness/postcondition-ambiguity",id:"algorithms-correctness/postcondition-ambiguity",title:"Vague postconditions and proving correctness of algorithms",description:"Debugging and testing with precise postconditions.\n",source:"@site/ib002/02-algorithms-correctness/2021-03-18-postcondition-ambiguity.md",sourceDirName:"02-algorithms-correctness",slug:"/algorithms-correctness/postcondition-ambiguity",permalink:"/ib002/algorithms-correctness/postcondition-ambiguity",draft:!1,editUrl:"https://github.com/mfocko/blog/tree/main/ib002/02-algorithms-correctness/2021-03-18-postcondition-ambiguity.md",tags:[{label:"python",permalink:"/ib002/tags/python"},{label:"testing",permalink:"/ib002/tags/testing"},{label:"postconditions",permalink:"/ib002/tags/postconditions"},{label:"sorting",permalink:"/ib002/tags/sorting"}],version:"current",lastUpdatedAt:1616025600,formattedLastUpdatedAt:"Mar 18, 2021",frontMatter:{id:"postcondition-ambiguity",title:"Vague postconditions and proving correctness of algorithms",description:"Debugging and testing with precise postconditions.\n",tags:["python","testing","postconditions","sorting"],last_update:{date:"2021-03-18T00:00:00.000Z"}},sidebar:"autogeneratedBar",previous:{title:"Algorithms and Correctness",permalink:"/ib002/category/algorithms-and-correctness"},next:{title:"Asymptotic Notation and Time Complexity",permalink:"/ib002/category/asymptotic-notation-and-time-complexity"}},l={},p=[{value:"Introduction",id:"introduction",level:2},{value:"Implementation of select sort from the exercises",id:"implementation-of-select-sort-from-the-exercises",level:2},{value:"Discussed preconditions, loop invariants and postconditions",id:"discussed-preconditions-loop-invariants-and-postconditions",level:2},{value:"Precondition",id:"precondition",level:3},{value:"Loop invariant",id:"loop-invariant",level:3},{value:"Postcondition",id:"postcondition",level:3},{value:"So is the permutation really required?",id:"so-is-the-permutation-really-required",level:2},{value:"Implementation of the broken select sort",id:"implementation-of-the-broken-select-sort",level:2},{value:"Property-based tests for our sorts",id:"property-based-tests-for-our-sorts",level:2},{value:"Loop invariant",id:"loop-invariant-1",level:3},{value:"Postcondition(s)",id:"postconditions",level:3},{value:"Putting it together",id:"putting-it-together",level:3},{value:"Let&#39;s run the tests!",id:"lets-run-the-tests",level:3},{value:"Summary",id:"summary",level:2}],c={toc:p},m="wrapper";function u(e){let{components:t,...n}=e;return(0,o.kt)(m,(0,i.Z)({},c,n,{components:t,mdxType:"MDXLayout"}),(0,o.kt)("h2",{id:"introduction"},"Introduction"),(0,o.kt)("p",null,(0,o.kt)("a",{parentName:"p",href:"pathname:///files/ib002/algorithms-correctness/postcondition-ambiguity/test_sort.py"},"Source code")," used later on."),(0,o.kt)("h2",{id:"implementation-of-select-sort-from-the-exercises"},"Implementation of select sort from the exercises"),(0,o.kt)("p",null,"To implement select sort from the exercises and make it as easy to read as possible, I have implemented maximum function that returns index of the biggest element from the first ",(0,o.kt)("span",{parentName:"p",className:"math math-inline"},(0,o.kt)("span",{parentName:"span",className:"katex"},(0,o.kt)("span",{parentName:"span",className:"katex-mathml"},(0,o.kt)("math",{parentName:"span",xmlns:"http://www.w3.org/1998/Math/MathML"},(0,o.kt)("semantics",{parentName:"math"},(0,o.kt)("mrow",{parentName:"semantics"},(0,o.kt)("mi",{parentName:"mrow"},"n")),(0,o.kt)("annotation",{parentName:"semantics",encoding:"application/x-tex"},"n")))),(0,o.kt)("span",{parentName:"span",className:"katex-html","aria-hidden":"true"},(0,o.kt)("span",{parentName:"span",className:"base"},(0,o.kt)("span",{parentName:"span",className:"strut",style:{height:"0.4306em"}}),(0,o.kt)("span",{parentName:"span",className:"mord mathnormal"},"n")))))," elements."),(0,o.kt)("p",null,"For the sake of time and memory complexity, I am also using ",(0,o.kt)("inlineCode",{parentName:"p"},"itertools.islice"),", which makes a slice, but does not copy the elements into the memory like normal slice does."),(0,o.kt)("p",null,"There is also a ",(0,o.kt)("inlineCode",{parentName:"p"},"check_loop_invariant")," function that will be described later."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},"def compare_by_value(pair):\n index, value = pair\n return value\n\n\ndef maximum(arr, n):\n first_n_elements = itertools.islice(enumerate(arr), n)\n index, value = max(first_n_elements, key=compare_by_value)\n return index\n\n\ndef select_sort(arr, n):\n assert n == len(arr)\n\n check_loop_invariant(arr, n, n)\n for i in reversed(range(1, n)):\n j = maximum(arr, i + 1)\n arr[i], arr[j] = arr[j], arr[i]\n\n check_loop_invariant(arr, n, i)\n\n return arr\n")),(0,o.kt)("h2",{id:"discussed-preconditions-loop-invariants-and-postconditions"},"Discussed preconditions, loop invariants and postconditions"),(0,o.kt)("p",null,"You can safely replace ",(0,o.kt)("inlineCode",{parentName:"p"},"A")," with ",(0,o.kt)("inlineCode",{parentName:"p"},"arr")," or array for list."),(0,o.kt)("h3",{id:"precondition"},"Precondition"),(0,o.kt)("p",null,"As a precondition we have established that ",(0,o.kt)("inlineCode",{parentName:"p"},"A")," represents an array of values and ",(0,o.kt)("span",{parentName:"p",className:"math math-inline"},(0,o.kt)("span",{parentName:"span",className:"katex"},(0,o.kt)("span",{parentName:"span",className:"katex-mathml"},(0,o.kt)("math",{parentName:"span",xmlns:"http://www.w3.org/1998/Math/MathML"},(0,o.kt)("semantics",{parentName:"math"},(0,o.kt)("mrow",{parentName:"semantics"},(0,o.kt)("mi",{parentName:"mrow"},"n")),(0,o.kt)("annotation",{parentName:"semantics",encoding:"application/x-tex"},"n")))),(0,o.kt)("span",{parentName:"span",className:"katex-html","aria-hidden":"true"},(0,o.kt)("span",{parentName:"span",className:"base"},(0,o.kt)("span",{parentName:"span",className:"strut",style:{height:"0.4306em"}}),(0,o.kt)("span",{parentName:"span",className:"mord mathnormal"},"n")))))," is length of the ",(0,o.kt)("inlineCode",{parentName:"p"},"A"),"."),(0,o.kt)("h3",{id:"loop-invariant"},"Loop invariant"),(0,o.kt)("p",null,"As for loop invariant we have established that we require two properties:"),(0,o.kt)("ol",null,(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("inlineCode",{parentName:"li"},"A[i + 1 : n]")," is sorted"),(0,o.kt)("li",{parentName:"ol"},"all elements of ",(0,o.kt)("inlineCode",{parentName:"li"},"A[i + 1 : n]")," are bigger or equal to the other elements")),(0,o.kt)("p",null,"This invariant is later defined as ",(0,o.kt)("inlineCode",{parentName:"p"},"check_loop_invariant")," function. It is checked before the first iteration and after each iteration."),(0,o.kt)("h3",{id:"postcondition"},"Postcondition"),(0,o.kt)("p",null,"For the postcondition the first suggestion was that ",(0,o.kt)("inlineCode",{parentName:"p"},"A")," must be sorted. And later we have added that ",(0,o.kt)("inlineCode",{parentName:"p"},"A'")," must be a permutation of ",(0,o.kt)("inlineCode",{parentName:"p"},"A"),"."),(0,o.kt)("blockquote",null,(0,o.kt)("p",{parentName:"blockquote"},"However at the end of the session question arose if it is really required to state in the postcondition that ",(0,o.kt)("inlineCode",{parentName:"p"},"A'")," is a permutation.")),(0,o.kt)("h2",{id:"so-is-the-permutation-really-required"},"So is the permutation really required?"),(0,o.kt)("p",null,"As I have said it is better to have postconditions explicit and do not expect anything that is not stated explicitly, e.g. ",(0,o.kt)("em",{parentName:"p"},"name suggests it"),". In reality we could consider it as a smaller mistake (but it has consequences)."),(0,o.kt)("p",null,"On the other hand explicit postconditions can be used to our advantage ",(0,o.kt)("strong",{parentName:"p"},"and also")," help our proof of correctness."),(0,o.kt)("p",null,"Consequences:"),(0,o.kt)("ol",null,(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},"Property-based testing"),(0,o.kt)("p",{parentName:"li"},"If we have explicit postconditions we can use them to define properties of the output from our algorithms. That way we can use property-based testing, which does not depend on specific inputs and expected outputs, but rather on randomly generated input and checking if the output conforms to our expectations (the postconditions are fulfilled).")),(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},"Proof of correctness"),(0,o.kt)("p",{parentName:"li"},"If we can prove that algorithm is correct even for algorithm that ",(0,o.kt)("strong",{parentName:"p"},"is not")," correct, we have a problem. That proof has no value and is useless."))),(0,o.kt)("p",null,'For the sake of showcasing the power of postconditions I will introduce "select sort" that is not correct, but will comply with both the loop invariant and our vague postcondition and thus pass the tests.'),(0,o.kt)("h2",{id:"implementation-of-the-broken-select-sort"},"Implementation of the broken select sort"),(0,o.kt)("p",null,"To make sure this thing passes everything, but our explicit postcondition with permutation will ",(0,o.kt)("em",{parentName:"p"},"blow it up"),', I have designed this "select sort" as follows:'),(0,o.kt)("ol",null,(0,o.kt)("li",{parentName:"ol"},"If I get empty list, there is nothing to do."),(0,o.kt)("li",{parentName:"ol"},"I find maximum in the array."),(0,o.kt)("li",{parentName:"ol"},"For each index from the end, I will assign ",(0,o.kt)("inlineCode",{parentName:"li"},"maximum + index"),".\nThis will ensure that even if the maximum in the original array was the first element, I will always satisfy that 2nd part of the loop invariant.")),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},"def broken_select_sort(arr, n):\n assert n == len(arr)\n\n if not arr:\n return\n\n max_value = max(arr)\n\n check_loop_invariant(arr, n, n)\n for i in reversed(range(n)):\n arr[i] = max_value + i\n\n check_loop_invariant(arr, n, i)\n\n return arr\n")),(0,o.kt)("admonition",{type:"tip"},(0,o.kt)("p",{parentName:"admonition"},"There is also an easier way to break this, I leave that as an exercise ;)")),(0,o.kt)("h2",{id:"property-based-tests-for-our-sorts"},"Property-based tests for our sorts"),(0,o.kt)("p",null,"Since we have talked a lot about proofs at the seminar, I would like to demonstrate it on the testing of the sorts. In the following text I will cover implementation of the loop invariant and both postconditions we have talked about and then test our sorts using them."),(0,o.kt)("h3",{id:"loop-invariant-1"},"Loop invariant"),(0,o.kt)("p",null,"To check loop invariant I have implemented this function:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},'def check_loop_invariant(arr, n, i):\n # A[i + 1 : n] is sorted\n for x, y in zip(itertools.islice(arr, i + 1, n), itertools.islice(arr, i + 2, n)):\n assert x <= y\n\n # all elements of A[i + 1 : n] are bigger or equal to the other elements\n if i + 1 >= n:\n # in case there are no elements\n return\n\n # otherwise, since the "tail" is sorted, we can assume that it is enough to\n # check the other elements to the smallest value of the tail\n smallest = arr[i + 1]\n for element in itertools.islice(arr, i + 1):\n assert smallest >= element\n')),(0,o.kt)("p",null,'First part checks if the "ending" of the array is sorted.'),(0,o.kt)("p",null,"In second part I have used a ",(0,o.kt)("em",{parentName:"p"},"dirty trick")," of taking just the first element that is the smallest and compared the rest of the elements to it. Why is it enough? I leave it as an exercise ;)"),(0,o.kt)("h3",{id:"postconditions"},"Postcondition(s)"),(0,o.kt)("p",null,"I have defined both the vague and explicit postconditions:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},"def check_vague_postcondition(original_arr, arr):\n if not arr:\n return\n\n # check ordering\n for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):\n assert x <= y\n\n\ndef check_postcondition(original_arr, arr):\n if not arr:\n return\n\n # check ordering\n for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):\n assert x <= y\n\n # get counts from original list\n original_counts = {}\n for value in original_arr:\n original_counts[value] = 1 + original_counts.get(value, 0)\n\n # get counts from resulting list\n counts = {}\n for value in arr:\n counts[value] = 1 + counts.get(value, 0)\n\n # if arr is permutation of original_arr then all counts must be the same\n assert counts == original_counts\n")),(0,o.kt)("h3",{id:"putting-it-together"},"Putting it together"),(0,o.kt)("p",null,"Now that we have everything implement, we can move on to the implementation of the tests:"),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},'from hypothesis import given, settings\nfrom hypothesis.strategies import integers, lists\nimport pytest\n\n@given(lists(integers()))\n@settings(max_examples=1000)\n@pytest.mark.parametrize(\n "postcondition", [check_vague_postcondition, check_postcondition]\n)\n@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])\ndef test_select_sort(sorting_function, postcondition, numbers):\n result = sorting_function(numbers[:], len(numbers))\n postcondition(numbers, result)\n')),(0,o.kt)("p",null,"Since it might seem a bit scary, I will disect it by parts."),(0,o.kt)("ol",null,(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},"Parameters of test function"),(0,o.kt)("pre",{parentName:"li"},(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},"def test_select_sort(sorting_function, postcondition, numbers):\n")),(0,o.kt)("p",{parentName:"li"},"We are given 3 parameters:"),(0,o.kt)("ul",{parentName:"li"},(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("inlineCode",{parentName:"li"},"sorting_function")," - as the name suggests is the sorting function we test"),(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("inlineCode",{parentName:"li"},"postcondition")," - as the name suggests is the postcondition that we check"),(0,o.kt)("li",{parentName:"ul"},(0,o.kt)("inlineCode",{parentName:"li"},"numbers")," - is random list of numbers that we will be sorting"))),(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},"Body of the test"),(0,o.kt)("pre",{parentName:"li"},(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},"result = sorting_function(numbers[:], len(numbers))\npostcondition(numbers, result)\n")),(0,o.kt)("p",{parentName:"li"},"We pass to the sorting function ",(0,o.kt)("strong",{parentName:"p"},"copy")," of the numbers we got, this ensures that once we are checking the more strict postcondition, we can gather the necessary information even after sorting the list in-situ, i.e. we can check if the ",(0,o.kt)("inlineCode",{parentName:"p"},"result")," is really a ",(0,o.kt)("inlineCode",{parentName:"p"},"permutation")," of the ",(0,o.kt)("inlineCode",{parentName:"p"},"numbers")," even though the sorting functions has modified the passed in list."))),(0,o.kt)("admonition",{type:"caution"},(0,o.kt)("p",{parentName:"admonition"},"Now we get to the more complicated part and it is the ",(0,o.kt)("em",{parentName:"p"},"decorators"),".")),(0,o.kt)("ol",{start:3},(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},"1st ",(0,o.kt)("inlineCode",{parentName:"p"},"parametrize")," from the bottom"),(0,o.kt)("pre",{parentName:"li"},(0,o.kt)("code",{parentName:"pre",className:"language-py",metastring:"showLineNumbers",showLineNumbers:!0},'@pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])\n')),(0,o.kt)("p",{parentName:"li"},"This tells pytest, that we want to pass the values from the list to the parameter ",(0,o.kt)("inlineCode",{parentName:"p"},"sorting_function"),". In other words, this lets us use the same test function for both the correct and incorrect select sort.")),(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},"2nd ",(0,o.kt)("inlineCode",{parentName:"p"},"parametrize")," from the bottom is similar, but works with the postcondition.\nThe reason why they are separated is pretty simple, this way they act like cartesian product: for each sorting function we also use each postcondition.")),(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},(0,o.kt)("inlineCode",{parentName:"p"},"@settings")," raises the count of tests that hypothesis runs (from default of 100(?)).")),(0,o.kt)("li",{parentName:"ol"},(0,o.kt)("p",{parentName:"li"},(0,o.kt)("inlineCode",{parentName:"p"},"@given(lists(integers()))"),"\nThis means hypothesis is randomly creating lists of integers and passing them to the function, which has only one parameter left and that is ",(0,o.kt)("inlineCode",{parentName:"p"},"numbers"),"."))),(0,o.kt)("h3",{id:"lets-run-the-tests"},"Let's run the tests!"),(0,o.kt)("p",null,"In case you want to experiment locally, you should install ",(0,o.kt)("inlineCode",{parentName:"p"},"pytest")," and ",(0,o.kt)("inlineCode",{parentName:"p"},"hypothesis")," from the PyPI."),(0,o.kt)("pre",null,(0,o.kt)("code",{parentName:"pre"},'% pytest -v test_sort.py\n=================================== test session starts ====================================\nplatform linux -- Python 3.6.8, pytest-3.8.2, py-1.7.0, pluggy-0.13.1 -- /usr/bin/python3\ncachedir: .pytest_cache\nrootdir: /home/xfocko/git/xfocko/ib002/postcondition-ambiguity, inifile:\nplugins: hypothesis-5.16.1\ncollected 4 items\n\ntest_sort.py::test_select_sort[select_sort-check_vague_postcondition] PASSED [ 25%]\ntest_sort.py::test_select_sort[select_sort-check_postcondition] PASSED [ 50%]\ntest_sort.py::test_select_sort[broken_select_sort-check_vague_postcondition] PASSED [ 75%]\ntest_sort.py::test_select_sort[broken_select_sort-check_postcondition] FAILED [100%]\n\n========================================= FAILURES =========================================\n_________________ test_select_sort[broken_select_sort-check_postcondition] _________________\n\nsorting_function = <function broken_select_sort at 0x7fac179308c8>\npostcondition = <function check_postcondition at 0x7fac1786d1e0>\n\n @given(lists(integers()))\n> @settings(max_examples=1000)\n @pytest.mark.parametrize(\n "postcondition", [check_vague_postcondition, check_postcondition]\n )\n @pytest.mark.parametrize("sorting_function", [select_sort, broken_select_sort])\n def test_select_sort(sorting_function, postcondition, numbers):\n\ntest_sort.py:132:\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\ntest_sort.py:139: in test_select_sort\n postcondition(numbers, result)\n_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n\noriginal_arr = [0, 0], arr = [0, 1]\n\n def check_postcondition(original_arr, arr):\n if not arr:\n return\n\n # check ordering\n for x, y in zip(arr, itertools.islice(arr, 1, len(arr))):\n assert x <= y\n\n # get counts from original list\n original_counts = {}\n for value in original_arr:\n original_counts[value] = 1 + original_counts.get(value, 0)\n\n # get counts from resulting list\n counts = {}\n for value in arr:\n counts[value] = 1 + counts.get(value, 0)\n\n # if arr is permutation of original_arr then all counts must be the same\n> assert counts == original_counts\nE assert {0: 1, 1: 1} == {0: 2}\nE Differing items:\nE {0: 1} != {0: 2}\nE Left contains more items:\nE {1: 1}\nE Full diff:\nE - {0: 1, 1: 1}\nE + {0: 2}\n\ntest_sort.py:128: AssertionError\n----------------------------------- Captured stdout call -----------------------------------\nFalsifying example: test_select_sort(\n sorting_function=<function test_sort.broken_select_sort>,\n postcondition=<function test_sort.check_postcondition>,\n numbers=[0, 0],\n)\n============================ 1 failed, 3 passed in 6.84 seconds ============================\n')),(0,o.kt)("p",null,"We can clearly see that our broken select sort has passed the ",(0,o.kt)("em",{parentName:"p"},"vague postcondition"),", but the explicit one was not satisfied."),(0,o.kt)("h2",{id:"summary"},"Summary"),(0,o.kt)("p",null,"For proving the correctness of the algorithm it is better to be explicit than prove that algorithm is correct even though it is not. Being explicit also allows you to test smaller ",(0,o.kt)("em",{parentName:"p"},"chunks")," of code better."))}u.isMDXComponent=!0}}]);