gpt4 book ai didi

ruby - 我的代码可以运行,但它很草率,我确信它有额外的语法。有什么建议吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:44:40 24 4
gpt4 key购买 nike

这是我要解决的问题:

Write a function lucky_sevens?(numbers), which takes in an array of integers and returns true if any three consecutive elements sum to 7.

lucky_sevens?([2,1,5,1,0]) == true # 1 + 5 + 1 == 7
lucky_sevens?([0,-2,1,8]) == true # -2 + 1 + 8 == 7
lucky_sevens?([7,7,7,7]) == false
lucky_sevens?([3,4,3,4]) == false

Make sure your code correctly checks for edge cases (i.e. the first and last elements of the array).

def lucky_sevens?(numbers)
i = 0
while i < numbers.length - 2

if numbers[i] + numbers[i + 1] + numbers[i + 2] == 7
puts true
return true
end
i+=1
end
puts false
return false
end

虽然我的代码看起来确实有效(我做了一些测试用例),但我知道它可以改进。没有理由同时使用 putsreturn 语句。我还想知道是否对语法本身进行了一般性改进以使其更具可读性。

最佳答案

如果您在 block 外使用索引,通常可以对其进行改进。这是一个正统的方法。

def lucky_sevens?(numbers)
numbers.each_cons(3).any?{|x, y, z| x + y + z == 7}
end

关于ruby - 我的代码可以运行,但它很草率,我确信它有额外的语法。有什么建议吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246842/

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