python求解LeetCode习题Fraction to Recurring Decimal

来源:互联网 发布:2017云计算企业百强榜 编辑:程序博客网 时间:2024/06/06 18:45

1、题目

Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.

If the fractional part is repeating, enclose the repeating part in parentheses.

For example,

  • Given numerator = 1, denominator = 2, return "0.5".
  • Given numerator = 2, denominator = 1, return "2".
  • Given numerator = 2, denominator = 3, return "0.(6)".
翻译:
给定两个数字,前者除以后者,如果结果:
1.正好整除但是是小数的话直接输出即可
2.正好整除,但是是整数的话直接输出即可
3.无法整除,但是结果是无限循环小数的时候按照题目要求输出整数位和循环的模式位用括号包括即可
思路:
前两步直接按照要求实现即可,对于第三步需要判断一下是否是循环序列
具体实现如下:
#!usr/bin/env python#encoding:utf-8from __future__ import division'''__Author__:沂水寒城功能:Fraction to Recurring Decimal '''def division_test(num1, num2):    '''    Given numerator = 1, denominator = 2, return "0.5".    Given numerator = 4, denominator = 2, return "2".    Given numerator = 2, denominator = 3, return "0.(6)".    '''    mod=num1/num2    if mod-round(mod, 5)==0:        print mod    else:        integer=str(mod).split('.')[0]        num_sequence=str(mod).split('.')[-1]        if judge_is_repeat(num_sequence):            print integer+'.('+num_sequence[0]+')'        else:            print '不符合要求'def judge_is_repeat(num_sequence):    '''    判断是否是小数点后面的序列是循环序列    '''    one_char=num_sequence[0]    num_list=list(num_sequence[:-1])    if len(num_list)==num_list.count(one_char):        return True     else:        return Falseif __name__ == '__main__':    division_test(1,2)    division_test(4,2)    division_test(2,3)    division_test(211,367)

结果如下:

0.52.00.(6)不符合要求[Finished in 0.2s]



原创粉丝点击