回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我最近开始学习Python。我在做一些关于课程控制结构部分的练习,一切都很顺利,直到最后一道题被难倒。我已经研究了三天了,我很确定解决办法是显而易见的。以下是练习中的描述:</p>
<blockquote>
<p>Start with any number. If the number is divisible by 3, divide it by
3. Otherwise, add 2 to the number. Eventually, no matter what number you begin with, this series will run into 1. For example, imagine we
started with the number 5: 5 is not divisible by 3, so 5 + 2 = 7 7 is
not divisible by 3, so 7 + 2 = 9 9 is divisible by 3, so 9 / 3 = 3 3
is divisible by 3, so 3 / 3 = 1</p>
<p>Start with 5, this sequence converges on 1 in 4 iterations: 5 -> 7, 7
-> 9, 9 -> 3, 3 -> 1.</p>
<p>Write a function called joyner. joyner should have one parameter, an
integer. It should return the number of iterations required to reach 1
for the first time.</p>
</blockquote>
<p>我在一个页面上运行了我写的函数,用不同的整数测试我的函数。每次它给我一个错误(说多少迭代是预期的和多少我的程序计算),我设法修复该整数的程序,但下面测试的整数会再次给我一个错误。下面的代码是我决定来这里寻求帮助之前的最后一次重写。你知道吗</p>
<pre><code>def joyner(num):
count = 0
while num % 3 != 0:
# print("num not divisible by 3")
num = num + 2
# print("added 2")
count += 1
# print(count)
if num % 3 == 0:
# print("num is divisible by 3")
num /= 3
# print("divided by 3")
count += 1
# print(count)
while num % 3 == 0:
# print("num is divisible by 3")
num /= 3
# print("divided by 3")
count += 1
# print(count)
return count
</code></pre>
<p>结果如下:</p>
<blockquote>
<p>We found the following problems with your submission:</p>
<p>We tested your code with num = 15. We expected joyner to return the
int 5. However, it returned the int 1.</p>
<p>We tested your code with num = 29. We expected joyner to return the
int 10. However, it returned the int 3.</p>
<p>We tested your code with num = 65. We expected joyner to return the
int 8. However, it returned the int 3.</p>
<p>We tested your code with num = 12. We expected joyner to return the
int 3. However, it returned the int 1.</p>
<p>We tested your code with num = 32. We expected joyner to return the
int 6. However, it returned the int 4.</p>
<p>Note that these errors may have prevented us from checking your
submission in other ways, so fixing these problems may cause other
problems to show up next time. Keep trying! This is what debugging is
all about.</p>
<hr/>
<p>The following things were correct about your submission:</p>
<p>We expected to find a function named joyner in your code, and we did.</p>
<p>We tested your code with num = 5. We expected joyner to return the int
4, and it did.</p>
<p>We tested your code with num = 27. We expected joyner to return the
int 3, and it did.</p>
<p>We tested your code with num = 16. We expected joyner to return the
int 3, and it did.</p>
</blockquote>