Paste number 40703: adjacental

Index of paste annotations: 3 | 2 | 1

Paste number 40703: adjacental
Pasted by: sbp
When:2 years, 2 months ago
Share:Tweet this! | http://paste.lisp.org/+VEN
Channel:#swhack
Paste contents:
Raw Source | XML | Display As
>>> def adjacental(num): 
...    num = str(num)
...    digit = num[0]
...    for newdigit in num[1:]: 
...       if abs(int(digit) - int(newdigit)) != 1: 
...          if list(sorted([digit, newdigit])) != ['0', '9']: 
...             return False
...       digit = newdigit
...    return True
... 
>>> adjacental('098765434567876543234567898')
True
>>> adjacental('0981374918')
False
>>> 

Annotations for this paste:

Annotation number 3: adjacental with sets
Pasted by: bpt
When:2 years, 2 months ago
Share:Tweet this! | http://paste.lisp.org/+VEN#3
Paste contents:
Raw Source | Display As
pairs = map(lambda *r: frozenset(r), range(1,10), range(2,10)+[0])
adj = lambda *r: pairs.count(frozenset(map(int,r))) != 0
adjacental = lambda s: all([adj(s[i],s[i+1]) for i in xrange(len(s)-1)])

Annotation number 2: reductionist's version
Pasted by: kpreid
When:2 years, 2 months ago
Share:Tweet this! | http://paste.lisp.org/+VEN#2
Paste contents:
Raw Source | Display As
def op(value, item):
  (prev, ok) = value
  if ok:
    if prev is None:
      return (item, True)
    else:
      return (item, abs(prev - item) in [1, 9])
  else:
    return (None, False)

def adjacental(num):
  (j, r) = reduce(op, [int(digit) for digit in str(num)], (None, True))
  return r

Annotation number 1: better adjacental(...)
Pasted by: sbp
When:2 years, 2 months ago
Share:Tweet this! | http://paste.lisp.org/+VEN#1
Paste contents:
Raw Source | Display As
>>> def adjacental(num): 
...    seq = [int(digit) for digit in str(num)]
...    for i in xrange(len(seq) - 1): 
...       diff = abs(seq[i] - seq[i + 1])
...       if (diff != 1) and (diff != 9): 
...          return False
...    return True
... 
>>> adjacental('098765434567876543234567898')
True
>>> adjacental('0981374918')
False
>>> 

Colorize as:
Show Line Numbers
Index of paste annotations: 3 | 2 | 1

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.