gpt4 book ai didi

python - 计算一个字符串中有多少个整数,Python 3

转载 作者:行者123 更新时间:2023-11-28 22:52:41 24 4
gpt4 key购买 nike

我需要的是显示有多少个小于 N 且不能被 2,3 或 5 整除的整数。我设法得到了小于 N 且不能被 2,3 整除的数字列表或 5,但我终其一生都无法让 Python 真正计算出有多少个整数。到目前为止我所拥有的是

N = int(input("\nPlease input a Number "))
if N < 0:
print("\nThere are no answers")
else:
for a in range(1,N+1,2):
if a%3 !=0:
if a%5 !=0:

最佳答案

试试这个:

N = 20

counter = 0
for a in range(1, N):
if a%2 and a%3 and a%5:
counter += 1

结果将在循环结束时保存在 counter 中。或者对于更高级的版本,改编自@iCodez 的回答:

sum(1 for x in range(1, N) if all((x%2, x%3, x%5)))
=> 6

关于python - 计算一个字符串中有多少个整数,Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20227831/

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