![](/img/trans.png)
[英]python program, Write a program to print first x terms of the series 3N + 2 which are not multiples of 4
[英]Write a program to print first x terms of the series 3N + 2 which are not multiples of 4
n = int (input())
for x in range (1, n + 1, 1):
for y in range (1, 100, 1):
z = 3 * y + 2
if z % 4 != 0:
print(z, end=' ')
此代码可以打印不是 4 的倍数的数字,但是如何在打印不是 4 的倍数的前 'n' 个数字 (z) 后停止?
输入: 10
预期 output: 5 11 14 17 23 26 29 35 38 41
Actual Output: 5 11 14 17 23 26 29 35 38 41 47 50 53 59 62 65 71 74 77 83 86 89 95 98 101 107 110 113 119 122 125 131 134 137 143 146 149 155 158 161 167 170 173 179 182 185 191 194 197 203 206 209 215 218 221 227 230 233 239 242 245 251 254 257 263 266 269 275 278 281 287 290 293 299
使用发电机保持简单高效。
使用itertools.islice
和itertools.count
:
from itertools import islice, count
N = 10
l = list(islice((x for i in count(start=1) if (x:=3*i+2)%4), N))
output: [5, 11, 14, 17, 23, 26, 29, 35, 38, 41]
引入一个反变量:
n = int (input())
counter = 0
for x in range (1, n + 1, 1):
for y in range (1, 100, 1):
z = 3 * y + 2
if counter >= 10:
break
if z % 4 != 0:
print(z, end=' ')
counter += 1
limit = 10
counter = 0
n = 0
while counter != limit:
n += 1
statement = (3*n)+2
if (statement % 4 != 0) and (statement > 4):
print(statement)
counter += 1
n= int(input())
count=0
x=1
while(count<n):
y=3*x+2
if(y%4!=0):
print(y, end=' ')
count=count+1
x=x+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.