![](/img/trans.png)
[英]Fastest way to check if a number is divisible by another in python
[英]Most efficient way to check if numbers in a list is divisible by another number
所以我昨天剛剛完成編碼測試,我有點神經質。 我被要求創建一個類或函數來檢查列表中的元素是否可以被可伸縮的元素列表整除。 這是我能想到的最好的方法,並且想知道是否可以改進。 謝謝! 為了掌握它,我特意使用了局部變量而不是lambda。 對我來說,它更干凈,並且可以更好地重用代碼。 另外,我認為Guido強烈建議不要使用Lambda,並建議人們改用偏愛的血液。
from functools import partial
def is_divisible(mod_vals, num):
"""A partial that runs a number against the list of modulus arguments, returning a bool value"""
for mod in mod_vals:
if num%mod != 0:
return False
return True
def divisible_by_factor(*mod_vals):
"""Returns a list based off a scalable amount of modulus arguments, no range support currently"""
comparison_list = []
div_partial = partial(is_divisible, (mod_vals))
for i in range(1, 100):
if div_partial(num=i):
comparison_list.append(i)
return comparison_list
>>> def divisible_by_factor(mod_vals):
>>> return [i for i in range(1, 100) if all(i % j == 0 for j in mod_vals)]
>>> print divisible_by_factor([2, 3, 5])
[30, 60, 90]
對於每個i
測試它是否可以被所有提供的值整除。 僅保留通過此測試的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.