8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

如何以单行字符串的形式输入字母算术方程,并以单行字符串的形式返回有效的算术方程

Spo1ler 1月前

45 0

因此,每个字母都与一个数字相对应,所以(a = 1,b = 2,c = 3,... z = 26),并且我不知道如何用整数替换字符串,以便输入字符串('COUPLE + COUPLE = QUARTET')

所以,每个字母都对应一个数字,所以

(a=1, b=2, c=3,...z=26),

我不知道如何用整数替换字符串,以便输入字符串

('COUPLE + COUPLE = QUARTET')

将输出

('653924 + 653924 = 1307848')

禁止导入模块

我曾尝试调整其他帖子中的解决方案,但它们都返回 None 或不同的东西。这是我当前的代码:

def alphametics(puzzle):
    return [ord(char) - 96 for char in puzzle.lower()]

当我输入以下内容时:

'SEND + MORE = MONEY'

我的输出是这样的:

[19, 5, 14, 4, -64, -53, -64, 13, 15, 18, 5, -64, -35, -64, 13, 15, 14, 5, 25]

但应该是这样的:

'9567 + 1085 = 10652'
帖子版权声明 1、本帖标题:如何以单行字符串的形式输入字母算术方程,并以单行字符串的形式返回有效的算术方程
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Spo1ler在本站《python》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 你必须解释如何将 SEND -> 9567 和 COUPLE -> 653924

  • 中提到的方法, itertools.permutations 因为 “禁止模块导入” :

    import re
    from typing import TypeVar
    from collections.abc import Iterable
    
    T = TypeVar('T')
    
    # From https://docs.python.org/3/library/itertools.html#itertools.permutations.
    def permutations(iterable: Iterable[T], r: int | None = None):
      # permutations('ABCD', 2) → AB AC AD BA BC BD CA CB CD DA DB DC
      # permutations(range(3)) → 012 021 102 120 201 210
      pool = tuple(iterable)
      n = len(pool)
      r = n if r is None else r
      if r > n:
        return
      indices = list(range(n))
      cycles = list(range(n, n-r, -1))
      yield tuple(pool[i] for i in indices[:r])
      while n:
        for i in reversed(range(r)):
          cycles[i] -= 1
          if cycles[i] == 0:
            indices[i:] = indices[i+1:] + indices[i:i+1]
            cycles[i] = n - i
          else:
            j = cycles[i]
            indices[i], indices[-j] = indices[-j], indices[i]
            yield tuple(pool[i] for i in indices[:r])
            break
        else:
            return
    
    def extract_s1_s2_s3(puzzle: str) -> tuple[str, str, str] | None:
      """Extracts S1, S2, and S3 from the alphametic puzzle string.
    
      Args:
        puzzle: A string representing the alphametic equation
                (e.g., 'SEND + MORE = MONEY').
      Returns:
        A tuple (S1, S2, S3) if the puzzle format is valid, or None if invalid.
      """
      match = re.match(r'(\w+)\s*\+\s*(\w+)\s*=\s*(\w+)', puzzle)
      if not match:
        return None
      return match.groups()
    
    def solve_alphametic(S1: str, S2: str, S3: str) -> tuple[int, int, int] | str:
      """Solves the alphametic problem S1 + S2 = S3.
    
      Args:
        S1: The first string operand in the equation.
        S2: The second string operand in the equation.
        S3: The result string in the equation.
      Returns:
        A tuple (N1, N2, N3) representing the solution if it exists,
        or 'UNSOLVABLE' otherwise.
      """
      letters = set(S1 + S2 + S3)
      digits = '0123456789'
      for perm in permutations(digits, len(letters)):
        mapping = {letter: digit for letter, digit in zip(letters, perm)}
        if mapping[S1[0]] == '0' or mapping[S2[0]] == '0' or mapping[S3[0]] == '0':
          continue  # Leading zeros are not allowed
        N1 = int(''.join(mapping[char] for char in S1))
        N2 = int(''.join(mapping[char] for char in S2))
        N3 = int(''.join(mapping[char] for char in S3))
        if N1 + N2 == N3:
          return N1, N2, N3
      return 'UNSOLVABLE'
    
    def main() -> None:
      """Main function to execute the alphametic solver."""
      puzzle = input('Enter the alphametic puzzle (e.g., "SEND + MORE = MONEY"): ')
      parts = extract_s1_s2_s3(puzzle)
      if parts is None:
        print('Invalid puzzle format')
        return
      S1, S2, S3 = parts
      solution = solve_alphametic(S1, S2, S3)
      if solution == 'UNSOLVABLE':
        print(solution)
      else:
        a, b, c = solution
        print(f'{a} + {b} = {c}')
    
    if __name__ == '__main__':
      main()
    

    使用示例1:

    Enter the alphametic puzzle (e.g., "SEND + MORE = MONEY"): SEND + MORE = MONEY
    9567 + 1085 = 10652
    

    示例用法2:

    Enter the alphametic puzzle (e.g., "SEND + MORE = MONEY"): COUPLE + COUPLE = QUARTET
    653924 + 653924 = 1307848
    
  • 这可以使用 .join 函数来完成,该函数将循环遍历字符串中的每个字符,然后引用字母到数字字典映射并相应地转换输入字符串。

    您可能需要更改 create_alphabet_to_number_map() alphabet_to_number 自定义字母数字映射,因为我提供的示例只是 a=1、b=2,等等……

    # Create a dictionary of your conversions 
    def create_alphabet_to_number_map():
        # Create a map from alphabet letters A-J to corresponding numbers 0-9
        alphabet_to_number = {chr(65 + i): str(i) for i in range(26)}
        return alphabet_to_number
    
    # Apply conversion function to every character 
    def convert_string_using_map(input_string):
        # Create the alphabet-to-number map
        alphabet_to_number = create_alphabet_to_number_map()
        
        # Convert the input string using the map
        converted_string = ''.join([alphabet_to_number.get(char, char) for char in input_string])
        
        return converted_string
    
    
    # Example usage
    input_string = "Couple + Couple = Quartet"
    converted_string = convert_string_using_map(input_string.upper())
    print(f"Original String: {input_string}")
    print(f"Converted String: {converted_string}")
    
返回
作者最近主题: