使用int值循环字符串的字符

时间:2017-08-27 23:39:37

标签: python string file dictionary character

我试图通过USACO培训来解决测试用例:"您的旅程就在这里"。我试图分配字母数字的字母,并将每个字符乘以产品的字符串。

示例:

C   O   M   E   T  Q       
3 *  15 *   13 * 5  * 20 * 17  =  994500 

不幸的是,产品一直搞砸了。

key = {
    'A':1,
    'B':2,
    'C':3,
    'D':4,
    'E':5,
    'F':6,
    'G':7,
    'H':8,
    'I':8,
    'J':10,
    'K':11,
    'L':12,
    'M':13,
    'N':14,
    'O':15,
    'P':16,
    'Q':17,
    'R':18,
    'S':19,
    'T':20,
    'U':21,
    'V':22,
    'W':23,
    'X':24,
    'Y':25,
    'Z':26
}

file = open("testdata.txt", "r")

message = file.readline(2)

for character in message:
    preSignal = key[character]
    s = preSignal*key[character]
    print(s)

4 个答案:

答案 0 :(得分:0)

您每次都会覆盖变量s,并将平方key[character]保存到它(这是不对的)。您需要创建一个变量来保持结果。试试这个:

result = 1

for character in message:
    result *= key[character]

print(result)

答案 1 :(得分:0)

您需要在乘法之前将答案保存到s,以便您的代码为:

key = {'A':1,
   'B':2,
   'C':3,
   'D':4,
   'E':5,
   'F':6,
   'G':7,
   'H':8,
   'I':8,
   'J':10,
   'K':11,
   'L':12,
   'M':13,
   'N':14,
   'O':15,
   'P':16,
   'Q':17,
   'R':18,
   'S':19,
   'T':20,
   'U':21,
   'V':22,
   'W':23,
   'X':24,
   'Y':25,
   'Z':26}

infile = open("testdata.txt", "r")

message = infile.readline(2)
s=1
for character in message:

    s = s*key[character]
print(s)

答案 2 :(得分:0)

问题&溶液

你的问题是你基本上覆盖了循环的每次迭代s的值。您需要创建一个变量来保存每次迭代的当前结果的值,并添加到该变量

result = 1
for character in message:
    result *= key[character] # same as result = result * key[character]

改进

您可以简化字母到数字的映射:

key = {chr(number): number - 64 for number in range(65, 91)}

或者您可以使用string.ascii_letters

from string import ascii_letters
key = {letter: number for number, letter in enumerate(ascii_letters, 1)}

答案 3 :(得分:0)

你可以试试这个:

s = 1

for i in message:
  s *= key[i]

请注意,构建字母字典及其对应值的更简单方法是:

import string

key = {a:i+1 for a, i in zip(string.ascii_uppercase, range(26))}

对于纯Python3解决方案,您可以使用itertools.accumulate

import itertools
import operator
result = list(itertools.accumulate([key[i] for i in message], func=operator.mul))[-1]

print(result)

输出:

994500