Department numbers: Difference between revisions

→‎Python :: List comprehension notation: added an LC translation of the nested bind expression
(→‎{{header|Python}}: Updated bind, pylinted for Python 3, added subheaders.)
(→‎Python :: List comprehension notation: added an LC translation of the nested bind expression)
Line 2,036:
multiple of two.'''
return 0 == x % 2
 
 
if __name__ == '__main__':
main()</lang>
{{Out}}
<pre>('Police', 'Sanitation', 'Fire')
(2, 3, 7)
(2, 4, 6)
(2, 6, 4)
(2, 7, 3)
(4, 1, 7)
(4, 2, 6)
(4, 3, 5)
(4, 5, 3)
(4, 6, 2)
(4, 7, 1)
(6, 1, 5)
(6, 2, 4)
(6, 4, 2)
(6, 5, 1)
 
No. of options: 14</pre>
 
===List comprehension===
 
Nested ''bind'' (or ''concatMap'') expressions like those above, can also be written in list comprehension notation:
{{Works with|Python|3.7}}
<lang python>'''Department numbers'''
 
 
# options :: Int -> Int -> Int -> [(Int, Int, Int)]
def options(lo, hi, total):
'''Eligible triples.'''
ds = enumFromTo(lo)(hi)
return [
(x, y, z)
for x in ds
for y in ds
for z in [total - (x + y)]
if even(x) and y not in [x, z] and lo <= z <= hi
]
 
 
# GENERIC -------------------------------------------------
 
 
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: list(range(m, 1 + n))
 
 
# even :: Int -> Bool
def even(x):
'''True if x is an integer
multiple of two.'''
return 0 == x % 2
 
 
# TEST ----------------------------------------------------
# main :: IO ()
def main():
'''Test'''
 
xs = options(1, 7, 12)
print(('Police', 'Sanitation', 'Fire'))
for tpl in xs:
print(tpl)
print('\nNo. of options: ' + str(len(xs)))
 
 
9,659

edits