gpt4 book ai didi

Python-从函数中的文本文件中读取数字

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:54 24 4
gpt4 key购买 nike

我正在尝试编写一个程序,确保在文本文件中写入查找给定数字和限制之间的素数。如果该数字存在于文件中,它会尝试写入与给定(输入)数字互质的另一个数字。然后将其写入文本文件。 我的问题是检查文本文件中的数字是否存在。我该如何写它?所以,我从早上就开始研究,但是我找不到该问题的有用答案。我认为 Python 相对于 C 来说有很大的改变。

示例:输入的数字为 12,限制为 3

生成的数字是 1,5,7

第二个运行 1,5,7 存在于文本文件中,然后生成 11,13,17 并打印它们。

def coprime(x,y):
"""Returns True if the number is copime
else False."""
if x % y == 0:
return False
else:
return True


"""

def text_file() function will be here
if number searching number exists on the text file return True
else return False


"""

f = open("numbers.txt","a+")
i = 0
j = 0

num = int(raw_input("Please enter number "))
limit = int(raw_input("Please enter limit "))

while i < limit:
if text_check(file,j) == False and coprime(num,j) == True:
f.write(str(j))
i += 1
j += 1
print "%d is written on the text file" % j

else:
j += 1

f.close()

最佳答案

假设所有数字都位于单独的行上,如下所示:

1
5
7



from fractions import gcd

def coprime(n1, n2):
return gcd(n1, n2) == 1 # same as if gcd(n1, n2) == 1:return True else: return False



with open("out.txt","a+") as f: # with automatically closes your files
# add all previous numbers into a set, casting to int using map
# map(int, f) equivalent to [int(ele) for ele in f] in python2
nums_set = set(map(int, f)) # with 1 5 and 7 in the file nums_set = set([1, 5, 7])
i = 0
j = 0

num = int(raw_input("Please enter number "))
limit = int(raw_input("Please enter limit "))

while i < limit:
if j not in nums_set and coprime(num,j):
f.write("{}\n".format(j))
print "{} is written on the text file.".format(j)
i += 1
j += 1
# add current j's from this run to the set to avoid reopening and rechecking he file
nums_set.add(j)
else:
j += 1

关于Python-从函数中的文本文件中读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27705944/

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