我想在python(3.6.5)中编写一个程序来说明例如1/7。对于此示例,输出应类似于:“长度:6,重复数字:142857”。到目前为止,我已经知道了:
n = int(input("numerator: "))
d = int(input("denominator: "))
def t(n, d):
x = n * 9
z = x
k = 1
while z % d:
z = z * 10 + x
k += 1
print ("length:", k)
print ("repeated numbers:", t)
return k, z / d
t(n, d)
答案 0 :(得分:2)
执行print ("repeated numbers:", t)
会打印t
函数本身的表示形式,而不是其输出。
这是代码的修复版本。我使用Python 3.6+ f字符串将重复的数字转换为字符串,并在前面添加零以使其长度正确。
def find_period(n, d):
z = x = n * 9
k = 1
while z % d:
z = z * 10 + x
k += 1
digits = f"{z // d:0{k}}"
return k, digits
# Test
num, den = 1, 7
period, digits = find_period(num, den)
print('num:', num, 'den:', den, 'period:', period, 'digits:', digits)
num, den = 1, 17
period, digits = find_period(num, den)
print('num:', num, 'den:', den, 'period:', period, 'digits:', digits)
输出
num: 1 den: 7 period: 6 digits: 142857
num: 1 den: 17 period: 16 digits: 0588235294117647
这行可能有点神秘:
f"{z // d:0{k}}"
它说:找到小于或等于z
除以d
的最大整数,将其转换为字符串,并在左侧用零填充(如有必要),以得到一个整数。 k
的长度。
正如Goyo在评论中指出的那样,该算法并不完美。如果小数点包含任何非重复部分,即分母具有2或5的因数,它将陷入循环。请查看是否可以找到一种处理方式。
答案 1 :(得分:1)
这是我对https://www.geeksforgeeks.org/find-recurring-sequence-fraction/的Python实现
def fraction_to_decimal(numerator, denominator):
""" This function returns repeating sequence of a fraction.
If repeating sequence doesn't exits, then returns empty string """
# Create a map to store already seen remainders
# remainder is used as key and its position in
# result is stored as value. Note that we need
# position for cases like 1/6. In this case,
# the recurring sequence doesn't start from first
# remainder.
result = ""
mapping = {}
# Find first remainder
remainder = numerator % denominator
# Keep finding remainder until either remainder
# becomes 0 or repeats
while remainder != 0 and remainder not in mapping:
# Store this remainder
mapping[remainder] = len(result)
# Multiply remainder with 10
remainder = remainder * 10
# Append remainder / denominator to result
result_part = int(remainder / denominator)
result += str(result_part)
# print(f"Result: {result}")
# Update remainder
remainder = remainder % denominator
# print(f"Map: {mapping}")
return result
if __name__ == '__main__':
result = fraction_to_decimal(1, 7)
if result == "":
print("No recurring sequence")
else:
print(f"\nLenght of recurring sequence: {len(result)}")
print(f"\nRecurring sequence is {result}\n")