Skip to content

Instantly share code, notes, and snippets.

@miku
Last active December 6, 2016 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miku/f7ac5873f6a29a096fde to your computer and use it in GitHub Desktop.
Save miku/f7ac5873f6a29a096fde to your computer and use it in GitHub Desktop.
Fuzzy Finder
package main
import (
"fmt"
"regexp"
"sort"
"strings"
)
var Collection = []string{
"django_migrations.py",
"django_admin_log.py",
"main_generator.py",
"migrations.py",
"api_user.doc",
"user_group.doc",
"accounts.txt",
}
type match struct {
grouplen int
start int
value string
}
type matches []match
func (m matches) Len() int {
return len(m)
}
func (m matches) Swap(i, j int) {
m[i], m[j] = m[j], m[i]
}
func (m matches) Less(i, j int) bool {
if m[i].start > m[i].start {
return false
}
if m[i].grouplen > m[i].grouplen {
return false
}
return true
}
func (m matches) Values() []string {
var vals []string
for _, v := range m {
vals = append(vals, v.value)
}
return vals
}
func FuzzyFinder(input string, collection []string) []string {
var ms matches
var chars []string
for _, c := range input {
chars = append(chars, string(c))
}
s := strings.Join(chars, ".*?")
r := regexp.MustCompile(s)
for _, item := range collection {
idx := r.FindStringIndex(item)
if idx != nil {
ms = append(ms, match{grouplen: idx[1] - idx[0], start: idx[0], value: item})
}
}
sort.Sort(ms)
return ms.Values()
}
func main() {
fmt.Println(FuzzyFinder("djm", Collection))
fmt.Println(FuzzyFinder("mig", Collection))
fmt.Println(FuzzyFinder("user", Collection))
}
#!/usr/bin/env python
import re
def fuzzyfinder(user_input, collection):
suggestions = []
pattern = '.*?'.join(user_input)
regex = re.compile('%s' % pattern)
for item in collection:
match = regex.search(item)
if match:
suggestions.append((len(match.group()), match.start(), item))
return [x for _, _, x in sorted(suggestions)]
collection = [
'django_migrations.py',
'django_admin_log.py',
'main_generator.py',
'migrations.py',
'api_user.doc',
'user_group.doc',
'accounts.txt',
]
if __name__ == '__main__':
print(fuzzyfinder('djm', collection))
print(fuzzyfinder('mig', collection))
print(fuzzyfinder('user', collection))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment