-
Notifications
You must be signed in to change notification settings - Fork 0
/
078-hex_key.py
54 lines (47 loc) · 2.03 KB
/
078-hex_key.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from typing import cast, List, Dict, Set, Optional, Union, Tuple
from nagini_contracts.contracts import *
#use-as-unpure
@Pure
def IsPrimeHexDigit(c : int) -> bool :
# pure-start
return ((((((c) == (2)) or ((c) == (3))) or ((c) == (5))) or ((c) == (7))) or ((c) == (11))) or ((c) == (13))
# pure-end
@Pure
def count__prime__hex__digits__rec(i : int, j : int, num : List[int]) -> int :
# pre-conditions-start
Requires(Acc(list_pred(num)))
Requires(((0) <= (i)) and ((i) <= (j)) and ((j) <= (len(num))))
# pre-conditions-end
# pure-start
if i == j:
return 0
else:
return (1 if IsPrimeHexDigit(num[j - 1]) else 0) + count__prime__hex__digits__rec(i, j - 1, num)
# pure-end
def count__prime__hex__digits(s : List[int]) -> int:
# pre-conditions-start
Requires(Acc(list_pred(s)))
# pre-conditions-end
# post-conditions-start
Ensures(Acc(list_pred(s)))
Ensures((Result()) == (count__prime__hex__digits__rec(0, len(s), s)))
Ensures(((0) <= (Result())) and ((Result()) <= (len(s))))
# post-conditions-end
# impl-start
count : int = 0
d_1_i_ : int = 0
while (d_1_i_) < (len(s)):
# invariants-start
Invariant(Acc(list_pred(s)))
Invariant(((0) <= (d_1_i_)) and ((d_1_i_) <= (len(s))))
Invariant((count) == (count__prime__hex__digits__rec(0, d_1_i_, s)))
Invariant(count >= 0 and count <= d_1_i_)
Invariant(Forall(int, lambda x : (Implies(x >= 0 and x < len(s), (count__prime__hex__digits__rec(0, x + 1, s)) == ((count__prime__hex__digits__rec(0, x, s) + ((1 if IsPrimeHexDigit((s)[x]) else 0))))), [[count__prime__hex__digits__rec(0, x + 1, s)]])))
# invariants-end
# assert-start
Assert((count__prime__hex__digits__rec(0, d_1_i_ + 1, s)) == ((count__prime__hex__digits__rec(0, d_1_i_, s) + ((1 if IsPrimeHexDigit((s)[d_1_i_]) else 0)))))
# assert-end
count = (count) + ((1 if IsPrimeHexDigit((s)[d_1_i_]) else 0))
d_1_i_ = (d_1_i_) + (1)
return count
# impl-end