gpt4 book ai didi

python - 我的问题是编写一个 python 程序来从文件中读取 2 个数字,并将这 2 个数字的 gcd 和 lcm 写入第二个文件。这是我的代码

转载 作者:行者123 更新时间:2023-12-01 08:29:42 25 4
gpt4 key购买 nike

with open ("source.txt","r") as file:

line=file.readlines()
a=line[0].strip()
a=int(a)
b=line[1].strip()
b=int(b)

def gcd(c,d):

if d==0:
return c
else:
return gcd(d,c%d)

e=gcd(a,b)
gcd=("GCD of", a,"and", b,"is",e)
Lcm=("LCM of", a,"and", b,"is",a*b//e)

with open ("Finaldes1.txt","w") as Finaldes:
line1="{0}\n{1}".format(gcd,Lcm)
linaldes.write(line1)

但是当我打开最终文件时,数据会写入这样的引号内('GCD of', 4, 'and', 6, 'is', 2)('LCM of', 4, 'and', 6, 'is', 12)。我不需要在结尾和中间加引号。该怎么办?

最佳答案

那是因为您将元组保存到文件中。您可以将它们转换为如下字符串:

gcd_string = "".join(str(x) for x in gcd)

然后像这样保存:

line1="{0}\n{1}".format(gcd_string,Lcm_string)

或者首先您可以将它们保存为字符串

gcd = "{0} 和 {1} 的 GCD 为 {2}".format(a, b, e)

关于python - 我的问题是编写一个 python 程序来从文件中读取 2 个数字,并将这 2 个数字的 gcd 和 lcm 写入第二个文件。这是我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53969803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com