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

标签 python file-io

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

相关文章:

python - 具有动态路径的Django自定义图片上传字段

python - 在 BeautifulSoup 中查找不同的字符串并返回包含标签

python - 即使没有限制,Flask-Uploads 也总是抛出 'UploadNotAllowed' 错误

java - 在文件中有效地存储 float 和 short 值的数组

javascript - 关闭Excel而不提示javascript

python - 与其他代码并行执行 python Web 服务器

python - Dato-Graphlab 检查 Edge 是否存在

python - 分割所有空白后重写回文件?

linux - 如何从 Haskell 为所有用户设置文件权限

c++ - 如何在循环中表示不再输入字符串 ss while (cin >> ss)