鱼C论坛

 找回密码
 立即注册
查看: 2522|回复: 38

[已解决]Python:每日一题 258

[复制链接]
发表于 2019-10-17 20:29:40 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
今天的题目:


给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数

如果小数部分为循环小数,则将循环的部分括在括号内

示例 1:

输入: numerator = 1, denominator = 2
输出: "0.5"
示例 2:

输入: numerator = 2, denominator = 1
输出: "2"
示例 3:

输入: numerator = 2, denominator = 3
输出: "0.(6)"


欢迎大家一起答题!
最佳答案
2019-10-18 09:55:51
  1. class FracToDec:
  2.     def __init__(self):
  3.         self.sign = ''

  4.     def calc(self, numerator, denominator):
  5.                
  6.         if not denominator:
  7.             return ''
  8.         elif not numerator:
  9.             return 0
  10.          
  11.         self.sign = '-' if numerator / denominator < 0 else ''
  12.                     
  13.         numerator, denominator = abs(numerator), abs(denominator)
  14.         quot, rem = numerator//denominator, numerator%denominator

  15.         if rem == 0:
  16.             return '{0}{1}'.format(self.sign, quot)
  17.         
  18.         ans = '{0}{1}.'.format(self.sign, quot)
  19.         record = dict()
  20.         while rem:            
  21.             if rem in record:
  22.                 index = record[rem]
  23.                 ans = '{0}({1})'.format(ans[:index], ans[index:])
  24.                 break
  25.             else:
  26.                 ans += str(rem*10//denominator)
  27.                 record[rem] = len(ans) - 1

  28.             rem = rem*10%denominator

  29.         return ans

  30. if __name__ == '__main__':

  31.     f2d = FracToDec()
  32.     print(f2d.calc(1, 2))
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2019-10-17 22:25:31 | 显示全部楼层
本帖最后由 __mrsq__ 于 2019-10-18 15:20 编辑
  1. def reduction(numerator, denominator):
  2.     a = numerator
  3.     b = denominator
  4.     c = a % b
  5.     while c != 0:        
  6.         a = b
  7.         b = c
  8.         c = a % b
  9.     return int(numerator/b), int(denominator/b)

  10. def not_cycle(denominator):
  11.     factor5 = 0
  12.     factor2 = 0
  13.     while denominator >= 5:
  14.         if denominator % 5 == 0:
  15.             denominator /= 5
  16.             factor5 +=1
  17.         else:
  18.             break
  19.     while denominator >= 2:
  20.         if denominator % 2 == 0:
  21.             denominator /=2
  22.             factor2 +=1
  23.         else:
  24.             break
  25.     if denominator == 1:
  26.         return True, 1
  27.     else:
  28.         return False, factor5, factor2, denominator

  29. def find_cycle(numerator, denominator):
  30.     x = 9
  31.     while x % denominator:
  32.         x = x * 10 + 9
  33.     cycle = str(int((x / denominator) * numerator))
  34.     cycle = '(' + '0' * (len(str(x)) - len(cycle)) + cycle + ')'
  35.     return cycle
  36.    
  37.    
  38. def main(numerator, denominator):
  39.     after_reduction = reduction(numerator, denominator)
  40.     numerator = after_reduction[0]
  41.     denominator = after_reduction[1]
  42.     if not_cycle(denominator)[0]:
  43.         return str(numerator / denominator)
  44.     else:
  45.         int_part = str(numerator // denominator)
  46.         numerator = numerator % denominator
  47.         factor5 = not_cycle(denominator)[1]
  48.         factor2 = not_cycle(denominator)[2]
  49.         denominator = int(not_cycle(denominator)[3])
  50.         factor = max(factor5, factor2)
  51.         non_cycle_decimal_bits = ''   
  52.         if factor !=0:
  53.             numerator = int(numerator * 10**factor/(5**factor5 * 2**factor2))
  54.             non_cycle_decimal_bits = str(numerator // denominator)
  55.             non_cycle_decimal_bits = '0' *(factor - len(non_cycle_decimal_bits)) + non_cycle_decimal_bits
  56.             numerator = numerator % denominator
  57.             
  58.         return int_part + '.' + non_cycle_decimal_bits + find_cycle(numerator, denominator)
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-17 22:42:57 | 显示全部楼层
本帖最后由 大裤衩子 于 2019-10-18 08:50 编辑

我发现我也写错啦 ,再想想
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-17 23:46:56 | 显示全部楼层
题目难点就在循环小数循环体获取上。。。用正则不知道为啥匹配不上。求捉虫
  1. re.findall(r'\d+\.\d*(?:(\d+){2,})', str(1/7))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-18 09:55:51 | 显示全部楼层    本楼为最佳答案   
  1. class FracToDec:
  2.     def __init__(self):
  3.         self.sign = ''

  4.     def calc(self, numerator, denominator):
  5.                
  6.         if not denominator:
  7.             return ''
  8.         elif not numerator:
  9.             return 0
  10.          
  11.         self.sign = '-' if numerator / denominator < 0 else ''
  12.                     
  13.         numerator, denominator = abs(numerator), abs(denominator)
  14.         quot, rem = numerator//denominator, numerator%denominator

  15.         if rem == 0:
  16.             return '{0}{1}'.format(self.sign, quot)
  17.         
  18.         ans = '{0}{1}.'.format(self.sign, quot)
  19.         record = dict()
  20.         while rem:            
  21.             if rem in record:
  22.                 index = record[rem]
  23.                 ans = '{0}({1})'.format(ans[:index], ans[index:])
  24.                 break
  25.             else:
  26.                 ans += str(rem*10//denominator)
  27.                 record[rem] = len(ans) - 1

  28.             rem = rem*10%denominator

  29.         return ans

  30. if __name__ == '__main__':

  31.     f2d = FracToDec()
  32.     print(f2d.calc(1, 2))
复制代码

评分

参与人数 1荣誉 +1 鱼币 +1 贡献 +1 收起 理由
zltzlt + 1 + 1 + 1

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-18 14:59:40 | 显示全部楼层
def solution(numerator: int , denominator: int) -> str:
        res = list()

        if numerator*denominator<0:
            res.append("-")

        numerator = abs(numerator)
        denominator = abs(denominator)

        if numerator<denominator:
            res.append('0')

        while numerator>=denominator:
            mod = numerator%denominator
            res.append(str(numerator//denominator))
            numerator = mod

        if numerator == 0:
            return ''.join(res)
        else:
            res.append('.')

        mydict = {}
        numerator = numerator*10
        mydict[numerator] = len(res)
        while numerator != 0:
            mod = numerator%denominator
            res.append(str(numerator//denominator))
            numerator = mod*10
            ok = mydict.get(numerator, -1)
            if ok != -1:
                res = res[:ok] + ['('] + res[ok:] + [')']
                return ''.join(res)
            else:
                mydict[numerator] = len(res)

        return ''.join(res)

感觉写的不是很好

评分

参与人数 1荣誉 +1 鱼币 +1 贡献 +1 收起 理由
zltzlt + 1 + 1 + 1

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-18 15:36:08 | 显示全部楼层

  1. def fractionToDecimal(self, numerator: int, denominator: int) -> str:
  2.    
  3.     if numerator% denominator==0:  #整除
  4.         return str(numerator//denominator)
  5.         
  6.     else:
  7.             
  8.         decimals=""
  9.         remainders=[]  #储存余数,用于查找循环节
  10.         numerator1=abs(numerator)
  11.         denominator1=abs(denominator)
  12.         if numerator * denominator<0:
  13.             result="-"
  14.         else:
  15.             result=""
  16.         result+=str(numerator1//denominator1)+"."
  17.         remainder=numerator1%denominator1
  18.         while remainder not in remainders:
  19.             remainders.append(remainder)
  20.             remainder*=10
  21.             decimals+=str(remainder//denominator1)
  22.             if remainder%denominator1==0: #非无限循环小数
  23.                 return result+decimals
  24.             else:
  25.                 remainder=remainder%denominator1
  26.             
  27.         indexs=remainders.index(remainder)  # 定位循环起始位置:即余数相同的位置
  28.             
  29.         return result+str(decimals)[0:indexs]+"("+str(decimals)[indexs:]+")"     
复制代码

评分

参与人数 1荣誉 +1 鱼币 +1 贡献 +1 收起 理由
zltzlt + 1 + 1 + 1

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-18 16:15:50 | 显示全部楼层
  1. import re
  2. def kao(fz, fm):
  3.     if not fz or not fm:
  4.         return None
  5.     try:
  6.         result = fz / fm
  7.         if result == int(result):
  8.             return str(int(result))
  9.         else:
  10.             b,e=str(result).split(r'.')
  11.             dtemp=re.sub(r'(\d+)(?=\1)', '', e)
  12.             if int(e)== int(dtemp):
  13.                 return str(result)
  14.             else:
  15.                 return '{}.({})'.format(b, dtemp)
  16.     except ZeroDivisionError:
  17.         return None

  18. print(kao(1,3))
  19. print(kao(2,3))
  20. print(kao(1,7))
  21. print(kao(0,7))
  22. print(kao(1,2))
  23. print(kao(10,2))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-18 20:39:59 | 显示全部楼层
输入 numerator = 1, denominator = 214748364 报错
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-18 20:44:37 | 显示全部楼层

恭喜通过!

执行用时:44 ms
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-18 20:45:05 | 显示全部楼层
战场原 发表于 2019-10-18 14:59
def solution(numerator: int , denominator: int) -> str:
        res = list()

恭喜通过!

执行用时:48 ms
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-18 20:45:33 | 显示全部楼层

恭喜通过!

执行用时:56 ms
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-18 21:12:48 | 显示全部楼层

输入 numerator = 1, denominator = 214748364 报错
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-18 23:54:19 | 显示全部楼层
搞定 (^_^) 效率应该还可以
  1. def newdiv(numerator:int = 1, denominator:'int != 0' = 1):
  2.     '''
  3.     numerator 为分子,可为零
  4.     denominator 为分母,不可为零
  5.     两者必须为整数
  6.     '''
  7.     if numerator == 0:#分子为零则分式为零
  8.         return '0'
  9.    
  10.     point = False
  11.     result = ''
  12.     if (numerator * denominator) < 0:#上下异号必为负
  13.         result += '-'
  14.         
  15.     memory=[]

  16.     while numerator:#没除尽
  17.         if point:#已有小数点
  18.             now,numerator = divmod(numerator, denominator)
  19.             this_one = (now,numerator)
  20.             if this_one in memory:#已有循环节
  21.                 normal = memory[:memory.index(this_one)]
  22.                 the_loop = memory[memory.index(this_one):]
  23.                 for each in normal:
  24.                     result += str(each[0])
  25.                 loops = '('
  26.                 for each in the_loop:
  27.                     loops += str(each[0])
  28.                 loops += ')'
  29.                 result += loops
  30.                 return result
  31.             else:
  32.                 memory.append(this_one)
  33.             numerator *= 10
  34.         else:#还没有小数点
  35.             now,numerator = divmod(numerator, denominator)
  36.             result += str(now)
  37.             if numerator:
  38.                 numerator *= 10
  39.                 result += '.'
  40.                 point = True
  41.     else:#除尽了,但是没找到循环节
  42.         for each in memory:
  43.             result += str(each[0])
  44.         return result

  45. if __name__ == "__main__":
  46.     print('例1 输出:',newdiv(1,2))
  47.     print('例2 输出:',newdiv(2,1))
  48.     print('例3 输出:',newdiv(2,3))
  49.     print('自测(应为"0.2(15)") 输出:',newdiv(71,330))
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-19 06:44:18 | 显示全部楼层
zltzlt 发表于 2019-10-18 21:12
输入 numerator = 1, denominator = 214748364 报错
  1. import re


  2. class kao:

  3.     def __init__(self, fz, fm):

  4.         self.fz = fz
  5.         self.fm = fm

  6.     def numChecks(self):

  7.         if self.fm == 0:
  8.             return '分母不能为零!'
  9.         if self.fz == 0:
  10.             return '0'
  11.         else:
  12.             return self.fz / self.fm

  13.     def cal(self):
  14.         result = self.numChecks()
  15.         if 'e-' in str(result):
  16.             return self.eNum2float(result)
  17.         if r'e+' in str(result):
  18.             return self.eNum2float(float(result))
  19.         return self.repeatNum(float(result))

  20.     def eNum2float(self, num):
  21.         sign=''
  22.         lst = re.findall(r'(\d+)', str(num))
  23.         if str(num)[0]=='-':
  24.             sign='-'
  25.         if '+' in str(num):
  26.             return sign+'{}{}{}'.format(lst[0], lst[1], '0' * (int(lst[2]) - len(lst[1])))
  27.         else:
  28.             return sign+ '0.{}{}{}'.format('0' * (int(lst[2]) - 1), lst[0], lst[1])

  29.     def repeatNum(self, s):

  30.         if s == int(s):
  31.             return str(int(s))
  32.         else:
  33.             b, e = str(s).split(r'.')
  34.             dtemp = re.sub(r'(\d+)(?=\1)', '', e)
  35.             if int(e) == int(dtemp):
  36.                 return str(s)
  37.             else:
  38.                 return '{}.({})'.format(b, dtemp)


  39. print(kao(-1, 214748364).cal())
  40. print(kao(200000000000000000000, 3).cal())
  41. print(kao(1, 2).cal())
  42. print(kao(1, 3).cal())
  43. print(kao(-10, 2).cal())
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-19 07:59:38 | 显示全部楼层
阴阳神万物主 发表于 2019-10-18 23:54
搞定 (^_^) 效率应该还可以

解答错误

输入:numerator = -50, denominator = 8
输出:"--7.75"
预期结果:"-6.25"
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-19 08:02:38 | 显示全部楼层

解答错误

输入:numerator = 1, denominator = 6
输出:"0.(16)"
预期结果:"0.1(6)"
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-19 08:21:43 | 显示全部楼层
zltzlt 发表于 2019-10-19 07:59
解答错误

输入:numerator = -50, denominator = 8

改了一小点,应该OK了
  1. def newdiv(numerator:int = 1, denominator:'int != 0' = 1):
  2.     '''
  3.     numerator 为分子,可为零
  4.     denominator 为分母,不可为零
  5.     两者必须为整数
  6.     '''
  7.     if numerator == 0:#分子为零则分式为零
  8.         return '0'
  9.    
  10.     point = False
  11.    
  12.     result = ''
  13.     if (numerator * denominator) < 0:#上下异号必为负
  14.         result += '-'
  15.         numerator,denominator = abs(numerator),abs(denominator)
  16.         
  17.     memory=[]

  18.     while numerator:#没除尽
  19.         if point:#已有小数点
  20.             now,numerator = divmod(numerator, denominator)
  21.             this_one = (now,numerator)
  22.             if this_one in memory:#已有循环节
  23.                 normal = memory[:memory.index(this_one)]
  24.                 the_loop = memory[memory.index(this_one):]
  25.                 for each in normal:
  26.                     result += str(each[0])
  27.                 loops = '('
  28.                 for each in the_loop:
  29.                     loops += str(each[0])
  30.                 loops += ')'
  31.                 result += loops
  32.                 return result
  33.             else:
  34.                 memory.append(this_one)
  35.             numerator *= 10
  36.         else:#还没有小数点
  37.             now,numerator = divmod(numerator, denominator)
  38.             result += str(now)
  39.             if numerator:
  40.                 numerator *= 10
  41.                 result += '.'
  42.                 point = True
  43.     else:#除尽了,但是没找到循环节
  44.         for each in memory:
  45.             result += str(each[0])
  46.         return result

  47. if __name__ == "__main__":
  48.     print('例1 输出:',newdiv(1,2))
  49.     print('例2 输出:',newdiv(2,1))
  50.     print('例3 输出:',newdiv(2,3))
  51.     print('纠错(应为"-6.25") 输出:',newdiv(-50,8))
复制代码

评分

参与人数 1荣誉 +1 鱼币 +1 贡献 +1 收起 理由
zltzlt + 1 + 1 + 1

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-10-19 08:23:53 | 显示全部楼层
阴阳神万物主 发表于 2019-10-19 08:21
改了一小点,应该OK了

恭喜通过!

执行用时:56 ms
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-10-19 09:28:07 | 显示全部楼层
def print_num(numerator, denominator):
    conten = str(numerator/denominator)

    strerator, strminator = conten.split('.')
    strminator = list(strminator)
    copstrminator = strminator.copy()
    setminator = list(set(strminator))

    if len(setminator) < len(strminator)//2:
        for each_chr in setminator:
            copstrminator.pop(strminator.index(each_chr))

        #print(strminator, copstrminator)

        strminator = ''.join(strminator).replace(''.join(copstrminator), '')
        minator = ''.join(set(copstrminator))

        return '\n\n{}.{}({})'.format(strerator, strminator.replace(minator, ''), minator)

    else:
        return str(conten)


if __name__ == '__main__':
    while True:
        conten = input('\n\n.\w退出请输入两个整数按空格分隔:')

        numtor, detor = conten.split(' ')
        # int('as')

        try:
            print(print_num(int(numtor), int(detor)))
        except Exception as r:
            print('输入错误', r)



效果非常完美
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 21:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表