【问题标题】:How to convert "String" to "Int" without using library functions in Python如何在不使用 Python 中的库函数的情况下将“String”转换为“Int”
【发布时间】:2018-03-06 11:22:55
【问题描述】:

我需要它来做作业,我们有一位新老师说我们应该用谷歌搜索它,但我没有找到有用的答案。

我尝试将例如:a = "546" 转换为 a = 546 而没有任何库函数

提前感谢您的帮助!

【问题讨论】:

  • 大概“库函数”包括像int这样的内置函数,对吧?考虑到这是家庭作业,我们想看看到目前为止您的想法/发现/尝试了什么,以及您遇到了什么问题。
  • 也许您应该询问您的老师认为您会发现哪些有用的谷歌术语并分享您搜索的内容,以便我们知道您查看的内容没有帮助?除此之外 - 您对“库函数”的理解是什么?
  • 看看技术上正确答案的最终版本,它需要 2-3 次迭代才能根除所有内置函数,我必须说这是一项相当虐待狂的任务。

标签: python string integer int


【解决方案1】:
def int(a):
ty = a.__class__.__name__
out = 0
di = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4,
      '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
if ty not in ("str", "int", "float", "bytes"):
    raise TypeError("unsupported format")
if a.__class__ == float:
    return a.__floor__()
elif a.__class__ == int:
    return a
else:
    ind = 0
    for val in a[::-1]:
        if val not in di:
            raise ValueError("invalid input")
        out += di[val]*(10**ind)
        ind += 1
        #print(out, di[val])
    return out
print(int("55"))
55

【讨论】:

    【解决方案2】:
    def stringToInt(s):
        result = 0
        value = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
        for digit in s:
            result = 10 * result + value[digit]
    
        return result
    

    【讨论】:

      【解决方案3】:
      astr = "1234"
      num = 0
      for index,val in enumerate(astr[::-1]):
          res = (ord(val) - ord('0')) * (10 ** index)
          num += (res)
      

      【讨论】:

      • ord 是一个库函数
      【解决方案4】:

      我能想到的“最纯粹”:

      >>> a = "546"
      >>> result = 0
      >>> for digit in a:
              result *= 10
              for d in '0123456789':
                  result += digit > d
      
      >>> result
      546
      

      如果允许的话,或者使用@Ajax1234 的字典理念:

      >>> a = "546"
      >>> value = {'0':0, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9}
      >>> result = 0
      >>> for digit in a:
              result = 10 * result + value[digit]
      
      >>> result
      546
      

      【讨论】:

      • 为什么要将结果乘以 10 呢?因为我没有看到任何效果,因为结果变量的原始值为零
      【解决方案5】:

      你可以循环遍历字符串并使用ord对每个字符执行操作。

      示例:

      a="546"
      num=0
      for i in a:
           num = num * 10 + ord(i) - ord('0')
      

      【讨论】:

      • ord 显然是一个库函数,因此是不允许的。
      【解决方案6】:

      您可以保留一个存储数字键的字符串和整数值的字典,然后遍历该字符串。在遍历字符串时,您可以使用 enumerate 来跟踪索引,然后将 10 的幂次方减去 1,然后乘以字典中的相应键:

      a = "546"
      length = 0
      for i in a:
         length += 1
      d = {'1': 1, '0': 0, '3': 3, '2': 2, '5': 5, '4': 4, '7': 7, '6': 6, '9': 9, '8': 8}
      count = 0
      counter = 0
      for i in a:
         count += (10**(length-counter-1)*d[i])
         counter += 1
      print(count)
      

      输出:

      546
      

      【讨论】:

      • enumerate :)
      • 我完全忘记了 OP 对所有内置函数的要求,而不仅仅是 int :) 请参阅我最近的编辑。
      • rangelen 也是内置函数不是吗?你可以做for i in a
      • 您可以避免使用rangelen,首先使用[::-1] 进行切片,然后手动增加功率。但是,我认为内置函数的问题可能更多的是问题的措辞而不是这个答案 - 函数在哪里停止?索引列表不是对list.__getitem__ 的调用吗?
      • 我的意思是,我认为我们都可能过度杀戮它。我猜老师试图阻止学生使用int(),但我认为使用任何其他常见的内置函数,如rangelen 都可以。
      【解决方案7】:

      诀窍是546 = 500 + 40 + 6,或5*10^2 + 4*10^1 + 6*10^0

      注意指数如何只是索引(反向)。使用它,您可以将这种方法推广到一个函数中:

      def strToInt(number):
          total = 0                             # this is where we accumulate the result
          pwr = len(number) - 1                 # start the exponent off as 2
          for digit in number:                  # digit is the str "5", "4", and "6"
              digitVal = ord(digit) - ord('0')  # using the ascii table, digitVal is the int value of 5,4, and 6.
              total += digitVal * (10 ** pwr)   # add 500, then 40, then 6
              pwr -= 1                          # make sure to drop the exponent down by one each time
          return total
      

      你可以像这样使用它:

      >>> strToInt("546")
      546
      

      【讨论】:

      • @Evan 这会产生好的、可读的、有教育意义的代码。我认为这个答案更符合任务的精神,而不是试图从你的代码中打出任何内置单词。
      猜你喜欢
      • 2013-07-02
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2014-05-19
      • 2015-11-19
      • 2022-11-13
      相关资源
      最近更新 更多