gpt4 book ai didi

language-agnostic - 文件中的随机行

转载 作者:行者123 更新时间:2023-12-04 18:47:33 25 4
gpt4 key购买 nike

这个问题是在面试的时候问的。面试已经结束了,但我仍在思考 hte 问题及其困扰着我:

您的语言包含以下工具:rand()功能,whilefor循环,if声明和 readline()方法(类似于 python 的 readline() )。给定这些工具,编写一个算法,返回文件中的随机行。您不知道文件的大小,并且只能循环遍历文件的内容一次。

最佳答案

我不知道想要的答案,但我的解决方案如下:

chosen_line = ""
lines = 0

while (current_line = readline()):
if (rand(0, lines) == 0):
chosen_line = current_line

lines++

return chosen_line

编辑:一个很好的解释为什么这个作品被张贴在 this comment .

关于language-agnostic - 文件中的随机行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11784213/

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