[英]How do I count from a given range a number that is not divisible by any element of the array?
[英]how to count the number divisible by N in given range (A to B) for multiple cases (C) in python
所以基本上,有多種情況需要通過計算在給定范圍 A 到 B 內能被 N 整除的數字來解決。
例如,有 2 種情況。
案例 1 有 A=1, B=10, N=3
案例 2 有 A=8, B=20, N=4
但在一種情況下,輸入必須是這樣的:
2 #<-- number of cases
1 #<-- A
10 #<-- B
3 #<-- N
8 #<-- A
20 #<-- B
4 #<-- N
output 將類似於:
Case 1: 3 #because between 1 until 10, only 3,6,9 that divisible by 3
Case 2: 4 #because between 8 until 20, only 8,12,16,20 that divisible by 4
我有這個 function 供參考:
def CountDiv(A,B,N):
count = 0
for i in range(A, B+1):
if i % N == 0:
count = count + 1
return count
我的解釋很糟糕,但我只是不知道如何使它更清楚。 我希望有人能理解並啟發我這個問題。 謝謝
假設您將輸入序列放在列表中,這應該可以
seq = [ 2, #<-- number of cases
1, #<-- A
10, #<-- B
3, #<-- N
8, #<-- A
20, #<-- B
4, #<-- N
]
def slices(lst, n):
"""Yield successive n-sized chunks from lst."""
number_of_cases = lst.pop(0)
for i in range(0, n * number_of_cases, n):
yield lst[i:i + n]
def CountDiv(A,B,N):
count = 0
for i in range(A, B+1):
if i % N == 0:
count = count + 1
return count
print([CountDiv(*sub) for sub in [*slices(seq, n=3)]])
# [3, 4]
如果您想要您描述的確切 output,您可以這樣做
for idx, sub in enumerate([*slices(seq, n=3)]):
print(f"Case {idx}: {CountDiv(*sub)}")
# Case 0: 3
# Case 1: 4
您不需要遍歷所有值。 您只能從最小起點( (A+N-1)//N*N
)生成倍數:
def ndiv(A, B, N):
return len(list((A+N-1)//N*N, B+1, N)))
更好的是,使用以下方法直接計算值的數量:
def ndiv(A, B, N):
if B<A:
return 0
return (B+N-(A+N-1)//N*N)//N
例子:
>>> ndiv(8,20,4)
4
>>> ndiv(1,10,3)
3
>>> ndiv(1,1,3)
0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.