简体   繁体   English

Python3 OOPS .. 我如何在同一个 python 文件中调用这个 class 以及 function 头的语法是什么意思?

[英]Python3 OOPS .. How would i call this class in the same python file and what does the syntax of the function head mean?

class Solution:
    def romanToInt(self, s: str) -> int:
       dict = {
        'I' : 1,
        'V' : 5,
        'X' : 10,
        'L' : 50,
        'C' : 100,
        'D' : 500,
        'M' : 1000
        } 
       result  = 0
       tmp = 0;
       i = 0

       while i < len(s):
           tmp = dict[s[i]];
           if (i +1) < len(s) and dict[s[i]] < dict[s[i + 1]]:
               tmp = dict[s[i + 1]] - dict[s[i]]
               i += 1
           i += 1
           result += tmp;

       print (result)

I edited your code a little bit because you shouldn't use type keywords as variable names and to make it more readable我稍微编辑了你的代码,因为你不应该使用类型关键字作为变量名并使其更具可读性

class Solution:

    def romanToInt(self, text: str) -> int:
       pairs = {
        'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50,
        'C' : 100, 'D' : 500, 'M' : 1000 
       } 
       result = tmp = i = 0
       while i < len(text):
           tmp = pairs[text[i]];
           if i + 1 < len(text) and pairs[text[i]] < pairs[text[i + 1]]:
               tmp = pairs[text[i + 1]] - pairs[text[i]]
               i += 1
           i += 1
           result += tmp
       print(result)


solution = Solution()          # initialize instance of Solution class
solution.romanToInt("XXVIII")  # run the romanToInt method 

ouput = 28输出 = 28

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM