我如何修改此函数,以便使用特定算法输出1与其参数之间的整数? [英] How do I amend this function so that it prints integers between 1 and its parameter, using a particular algorithm?
问题描述
我已进行了以下练习:
使用1个参数创建一个函数 MyFunction,该函数将打印
Create a function "MyFunction" with 1 parameter, that will print integers between 1 and its parameter, using a particular algorithm:
MyFunction(25)
1, 2, 3, 7, 8, 9, 13, 14, 15, 19, 20, 21, 25
MyFunction(29)
1, 2, 3, 7, 8, 9, 13, 14, 15, 19, 20, 21, 25, 26, 27
我设法创建了一个输出1到其参数之间的数字的函数,但是如何修改它以打印该特定算法?
I have managed to create a function which prints numbers between 1 and its parameter but how do I amend it to print that specific algorithm?
从我的观察看来,每打印3个数字,它就不会打印接下来的3个数字,但我不知道该如何用代码编写。我也尝试过在线查看是否可以合并但没有成功的某种算法的公式或名称。
From my observation, it seems that for every 3 numbers it prints, it doesn't print the next 3 but I don't know how to write this in code. I have also tried to look online if there is some kind of formula or name of this algorithm which I can incorporate but haven't been successful.
def my_function(n):
for index in range(n):
print (index + 1)
my_function(25)
my_function(29)
我的代码打印出1到参数之间的整数,但是我不知道如何打印算法。
My code prints out integers between 1 and the parameter but I don't know how to print out the algorithm.
此外,请注意:我如何使用代码修饰符以备将来使用?
Also, side note: how do I use the code prettifier for future use?
推荐答案
类似的东西应该可以解决问题:
Something like this should do the trick:
def my_function(n):
i = 1
while i <= n:
print(i)
if i % 3 == 0:
i += 3
i += 1
基本上,每次您要进入不可打印的整数,您只需跳过
他们到下一个可打印的。如您所知,您始终希望打印3个数字,而不要打印接下来的3个项目。可以明确显示的版本可以编码为:
Basically, every time you were about to step into non-printable integers you just jump over
them to the next printable one. As you have noticed, you always want to print 3 numbers and than don't print next 3 items. Version that makes this explicit could be coded as:
def my_function(n):
should_print = True
i = 1
while i <= n:
if should_print:
print(i)
if i % 3 == 0:
should_print = not should_print
i += 1
表达式 i %3 == 0
是每第三次迭代 True
,这恰好是我们在可打印模式和不可打印模式之间交换时的情况
Expression i % 3 == 0
is True
every 3rd iteration which is exactly when we swap between printable and non-printable mode
这篇关于我如何修改此函数,以便使用特定算法输出1与其参数之间的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!