Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数字转换为辅音-元音对_Python - Fatal编程技术网

Python 将数字转换为辅音-元音对

Python 将数字转换为辅音-元音对,python,Python,该项目特别要求使用%100和//100运算符将初始数字集划分为基数10,如6 | 30 | 45 | 10,然后使用%5和//5将最后两位数字转换为0-19之间的商和0-4之间的余数。目前我有,任何帮助感谢,谢谢 integer = pin number_string = str(integer) number_string2 = str(integer) number_string % 100 number_string2 // 100 vowels = ["a", "e", "i", "o

该项目特别要求使用%100和//100运算符将初始数字集划分为基数10,如6 | 30 | 45 | 10,然后使用%5和//5将最后两位数字转换为0-19之间的商和0-4之间的余数。目前我有,任何帮助感谢,谢谢

integer = pin
number_string = str(integer)
number_string2 = str(integer)
number_string % 100
number_string2 // 100

vowels = ["a", "e", "i", "o", "u"]

consonants = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
          "n", "p", "q", "r", "s", "t", "v", "w", "y", "z"]
` 代码最终应该会产生这样的结果

>>> pintoword(3463470)
'bomejusa'
>>> pintoword(3464140)
'bomelela'

你的代码有点奇怪。例如,将名为integer的变量转换为字符串,然后尝试对其执行算术运算。然后你不会把结果保存在任何地方

无论如何,这里有一些代码可以满足您的需要。它使用内置的divmod函数在一个函数调用中生成商和余数

vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwyz"

def pintoword(n):
    a = []
    while n:
        n, r = divmod(n, 100)
        c, v = divmod(r, 5)
        a.append(vowels[v])
        a.append(consonants[c])
    return ''.join(reversed(a))

for n in (3463470, 3464140):
    print n, pintoword(n)
输出

我们将字母对保存在一个列表中,并在末尾将它们连接成一个字符串。除以100操作以相反的顺序生成字母对,因此我们需要在加入列表之前反转列表

FWIW,这是一个执行逆运算的函数。index调用元音和辅音字符串,它使用一对字典来查找索引,因为这样更快

def invert_string(s):
    return dict((v, i) for i, v in enumerate(s))

dvowels = invert_string(vowels)
dconsonants = invert_string(consonants)

def wordtopin(s):
    ''' Convert string s of alternating consonants and vowels into an integer '''
    num = 0
    for c, v in zip(*[iter(s)]*2):
        num = 100 * num + 5 * dconsonants[c] + dvowels[v]
    return num

我真的不明白你的问题基本上从一个4位数或更多数字的基数10的低阶开始,我需要将数字转换成一个字母,比如说40%5给我0,它会分配字母a,40//5是8,所以它会给我字母l。看起来你的意思几乎是基数100。”40'是以10为底的两位数。
def invert_string(s):
    return dict((v, i) for i, v in enumerate(s))

dvowels = invert_string(vowels)
dconsonants = invert_string(consonants)

def wordtopin(s):
    ''' Convert string s of alternating consonants and vowels into an integer '''
    num = 0
    for c, v in zip(*[iter(s)]*2):
        num = 100 * num + 5 * dconsonants[c] + dvowels[v]
    return num