将单词编码为整数的乘积

0 python

我正在尝试编写一个程序来检查是否在较大的单词中找到较小的单词.例如,单词"computer"包含单词"put","rum","cut"等.为了执行检查,我试图将每个单词编码为素数的乘积,这样小的单词将全部是较大词的因素.我有一个字母列表和一个素数列表,并为每个字母分配(我认为)一个整数值:

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 
61, 67, 71, 73, 79, 83, 89, 97, 101]

index = 0
while index <= len(letters)-1:
    letters[index] = primes[index]
    index += 1
Run Code Online (Sandbox Code Playgroud)

我现在遇到的问题是如何获取给定单词的整数代码,并能够为整个单词列表创建代码.例如,我希望能够输入单词"cab",并让代码生成其整数值5*2*3 = 30.

任何帮助将非常感激.

Hug*_*ell 5

from functools import reduce  # only needed for Python 3.x
from operator import mul

primes = [
    2,  3,  5,  7,  11, 13, 17, 19, 23, 29, 31, 37, 41,
    43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101
]
lookup = dict(zip("abcdefghijklmnopqrstuvwxyz", primes))

def encode(s):
    return reduce(mul, (lookup.get(ch, 1) for ch in s.lower()))
Run Code Online (Sandbox Code Playgroud)

然后

encode("cat")   # => 710
encode("act")   # => 710
Run Code Online (Sandbox Code Playgroud)

编辑:更重要的是,

def is_anagram(s1, s2):
    """
    s1 consists of the same letters as s2, rearranged
    """
    return encode(s1) == encode(s2)

def is_subset(s1, s2):
    """
    s1 consists of some letters from s2, rearranged
    """
    return encode(s2) % encode(s1) == 0
Run Code Online (Sandbox Code Playgroud)

然后

is_anagram("cat", "act")      # => True
is_subset("cat", "tactful")   # => True
Run Code Online (Sandbox Code Playgroud)