首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >具有无限运行时间循环的问题。

具有无限运行时间循环的问题。
EN

Stack Overflow用户
提问于 2022-01-15 13:01:38
回答 2查看 53关注 0票数 0

我有一个程序,定期下载一组随机文件并检查它们的大小,然后选择一个大小超过给定阈值的文件(当前为6KB)。

检查工作正常,但是如果文件集中没有满足阈值检查的文件,它就会一直在该集合中搜索,永远搜索。

下面是我的代码(函数chosen()是在目录上返回带有文件的random.choice,变量z_file是使用chosen() func选择的文件,size是为随机选择的文件返回get.size值的函数)-

代码语言:javascript
运行
复制
threshold = 6000
while True:  
    z_file = chosen()
    file_size = size(z_file)
    if file_size < threshold:
        print(z_file + " is too small")
    else:
        break
print(z_file , "is at least 6KB -" , file_size , "bytes ...")

正常情况下,它工作正常,但有时没有大于6KB的文件,结果循环将永远-

代码语言:javascript
运行
复制
PAGE 1 contains [1] images
PAGE 2 contains [1] images
PAGE 3 contains [3] images

pic3_3.png is too small
pic2_1.png is too small
pic3_3.png is too small
pic3_1.png is too small
pic3_2.png is too small
pic1_1.png is too small
pic3_1.png is too small
pic3_2.png is too small
pic3_2.png is too small
pic3_1.png is too small
pic3_1.png is too small
pic3_2.png is too small
pic3_1.png is too small
pic2_1.png is too small
pic3_3.png is too small
pic3_2.png is too small
pic2_1.png is too small
pic3_2.png is too small
pic3_3.png is too small
pic3_3.png is too small
pic3_3.png is too small

我确信我的while循环写得很糟糕,而且我使用but子句的方法不正确,但是我无法理解它。如有任何协助/指示,将不胜感激。

EN

回答 2

Stack Overflow用户

发布于 2022-01-15 13:04:35

代码语言:javascript
运行
复制
from collections import defaultdict
threshold = 6000
n = 0
TOTAL_FILES_NUMBER = 3
checked_files = defaultdict(int)
while True:  
    z_file = chosen()
    file_size = size(z_file)
    if checked_files[z_file] == 0:
        n += 1
        checked_files[z_file] = 1
    if file_size < threshold:
        print(z_file + " is too small")
    else:
        break
    if n == TOTAL_FILES_NUMBER:
        break
print(z_file , "is at least 6KB -" , file_size , "bytes ...")

克服这个问题的一种方法是知道目录中的文件总数(在上面的代码中,我假设它总共有3个文件),现在的问题是,您每次都选择一个随机文件,并且您不知道以前是否选择了它,所以您不能简单地在每次迭代中生成一个整数n并增加它,并且当它达到您所破坏的总数时,因为您可以检查同一个文件3次,它将从循环中中断,因为它已经检查了所有3个文件。

因此,为了解决这个问题,我们创建了一个名为dictionarychecked_files,它将跟踪每个文件,以及我们是否已经选择了它,这取决于文件键的值,如果是0,那么我们没有选择该文件,如果它是1,那么我们之前已经检查过这个文件。

根据这一点,如果我们检查了目录中的所有文件,我们可以使用上面的代码进行检查。

票数 0
EN

Stack Overflow用户

发布于 2022-01-15 13:20:55

如果您想访问所有的文件,random.choice是个坏主意,我建议random.shuffle

代码语言:javascript
运行
复制
threshold = 6000
for i in random.shuffle(file_list):  
    file_size = size(i)
    if file_size < threshold:
        print(i + " is too small")
    else:
        print(i , "is at least 6KB -" , file_size , "bytes ...")
        break
    print("no file above threshold")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70721678

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档