11module
22
3- def total_match : Unit :=
4- ()
3+ public import Std
4+ open Std
5+
6+ public section
7+
8+ /-! ## Missing API -/
9+
10+ def Std.Iter.sum [Iterator α Id Nat] [IteratorLoop α Id Id] (it : Iter (α := α) Nat) :
11+ Nat :=
12+ it.fold (init := 0 ) (· + ·)
13+
14+ theorem Std.Iter.sum_toList [Iterator α Id Nat] [IteratorLoop α Id Id]
15+ [LawfulIteratorLoop α Id Id] [Iterators.Finite α Id] {it : Iter (α := α) Nat} :
16+ it.toList.sum = it.sum := by
17+ simp [sum, List.sum_eq_foldl, foldl_toList]
18+
19+ theorem Std.Iter.sum_toArray [Iterator α Id Nat] [IteratorLoop α Id Id]
20+ [LawfulIteratorLoop α Id Id] [Iterators.Finite α Id] {it : Iter (α := α) Nat} :
21+ it.toArray.sum = it.sum := by
22+ simp [← toArray_toList, sum_toList]
23+
24+ /-! ## Implementation -/
25+
26+ def totalMatch (xs ys : Array String) : Array String :=
27+ minOn (fun zs => (zs.iter.map (·.length)).sum) xs ys
28+
29+ /-! ## Tests -/
30+
31+ example : totalMatch #[] #[] = #[] := by native_decide
32+ example : totalMatch #["hi" , "admin" ] #["hi" , "hi" ] = #["hi" , "hi" ] := by native_decide
33+ example : totalMatch #["hi" , "admin" ] #["hi" , "hi" , "admin" , "project" ] = #["hi" , "admin" ] := by
34+ native_decide
35+ example : totalMatch #["4" ] #["1" , "2" , "3" , "4" , "5" ] = #["4" ] := by native_decide
36+ example : totalMatch #["hi" , "admin" ] #["hI" , "Hi" ] = #["hI" , "Hi" ] := by native_decide
37+ example : totalMatch #["hi" , "admin" ] #["hI" , "hi" , "hi" ] = #["hI" , "hi" , "hi" ] := by
38+ native_decide
39+ example : totalMatch #["hi" , "admin" ] #["hI" , "hi" , "hii" ] = #["hi" , "admin" ] := by native_decide
40+ example : totalMatch #[] #["this" ] = #[] := by native_decide
41+ example : totalMatch #["this" ] #[] = #[] := by native_decide
42+
43+ /-! ## Verification -/
44+
45+ theorem totalMatch_spec :
46+ totalMatch xs ys = if (xs.map (·.length)).sum ≤ (ys.map (·.length)).sum then xs else ys := by
47+ simp [totalMatch, ← Iter.sum_toArray, minOn_eq_if]
548
649/-!
750## Prompt
@@ -10,7 +53,7 @@ def total_match : Unit :=
1053
1154def total_match(lst1, lst2):
1255 '''
13- Write a function that accepts two lists of strings and returns the list that has
56+ Write a function that accepts two lists of strings and returns the list that has
1457 total number of chars in the all strings of the list less than the other list.
1558
1659 if the two lists have the same number of chars, return the first list.
@@ -30,11 +73,11 @@ def total_match(lst1, lst2):
3073 l1 = 0
3174 for st in lst1:
3275 l1 += len(st)
33-
76+
3477 l2 = 0
3578 for st in lst2:
3679 l2 += len(st)
37-
80+
3881 if l1 <= l2:
3982 return lst1
4083 else:
@@ -63,4 +106,4 @@ def check(candidate):
63106 assert candidate(['this'], []) == []
64107
65108```
66- -/
109+ -/
0 commit comments