Python-基于值范围分配类别



已解决

我正试图弄清楚为什么我的解决方案是错误的。两者都做了,第二个是正确的。我更喜欢第一个,因为间隔更容易管理,也更适合我糟糕的编程大脑。坦率地说,我有点不知道从pH值8(中性(到更高(溶液2(会发生什么。因此,我想在未来的任务中继续以这种风格工作,而不是解决方案2(正确(。然而,我更喜欢的解决方案1是错误的,并返回,尽管它应该是强酸性为什么会这样,如何解决?

Def:根据pH(2.3(分配类别

pH&类别
0–2强酸性
3–5弱酸性
6–8中性
9–11弱碱性
12–14强碱性
其他任何低于pH值范围的

def pH2Category(pH):
if pH < 0 or pH > 14:
category = "pH out of range"
elif (pH >=0) and (pH < 3):
category = "Strongly acidic"
elif (pH >=3) and (pH < 6):
category = "Weakly acidic"
elif  (pH >=5) and (pH < 9):
category = "Neutral"
elif (pH >=9) and (pH < 12):
category = "Weakly basic"
else:
category = "Strongly basic"
return category
print(pH2Category(2.3))
def pH2Category(pH):
if pH < 0 or pH > 14:
category = "pH out of range"
elif pH < 3:
category = "Strongly acidic"
elif pH < 6:
category = "Weakly acidic"
elif pH <= 8:
category = "Neutral"
elif pH <= 11:
category = "Weakly basic"
else:
category = "Strongly basic"
return category
print(pH2Category(2.3)) 

如果你想坚持类似于你所知道的模式,下面的方法应该有效:

def pH2Category(pH):
if pH < 0 or pH > 14:
return "pH out of range"
elif (pH >= 0) and (pH < 3):
return "Strongly acidic"
elif (pH >= 3) and (pH < 6):
return "Weakly acidic"
elif  (pH >= 6) and (pH < 9):
return "Neutral"
elif (pH >= 9) and (pH < 12):
return "Weakly basic"
else:
return "Strongly basic"
print(pH2Category(2.3))

请注意,上面会a(返回"pH超出范围",所以如果你只想打印而不返回,请用print语句替换第一个if中的return,b(正如评论中提到的@quqa,你在5-6中有重叠的范围,所以我解决了这个问题。

有很多方法可以做到你所做的,但这里有一种可以帮助你从python开始,让你的生活更轻松

# dictionary of (min_value, max_value): 'Description of Ph'
# just fill out for your needs
table = {
(0, 3): 'Strongly Acidic',
(3, 6): 'Wakly Acidic',
(6, 9): 'Neutral',
...
}
def check_ph(ph):

for ph_range, ph_description in table.items():
# for every pair that you see in table
if ph_range[0] <= ph < ph_range[1]:
# if ph is greater or eqaual than min_value
# and lesser than max_value
print(ph_description)
# return the ph description
return ph_description

# if the value is outside the table range just print it out
print('ph out of range')

如果您想要可扩展的东西,您应该考虑分段树(日志速度查找(。

对于只有几个类别的东西来说,进行浪费的比较是很便宜的,但即使是5个类别,你也可以进行10次比较,而3-4次就可以了。

https://en.wikipedia.org/wiki/Segment_tree

您可能对portion感兴趣,这是我编写的一个库,它为间隔提供结构和操作。它分布在PyPI上,因此您可以使用pip install portion轻松安装它。

除此之外,它提供了一个IntervalDict类,该类的作用类似于Pythondict,但接受范围作为键。

应用于您的示例:

>>> import portion as P
>>> d = P.IntervalDict()
>>> d[P.open(-P.inf, P.inf)] = 'pH out of range'
>>> d[P.closed(0, 2)] = 'Strongly acidic'
>>> d[P.closed(3, 5)] = 'Weakly acidic'
>>> ...
>>> d[1]
'Strongly acidic'
>>> d[300]
'pH out of range'

最新更新