42

This question came up on the python tutor list:

What is the most convincing way to mimick this in Python?
#include <stdio .h>

#define SIX 1 + 5
#define NINE 8 + 1

int main(void) {
  printf("What do you get if you multiply six by nine: %d\n", SIX *
	NINE);
  return 0;
}

I dutifully came up with this answer…

class define:
... 	def __init__(self, strnumexpr):
... 		self.val = strnumexpr
... 	def __mul__(self, x):
... 		answer = self.val + '*' + x.val
... 		return eval(answer)
... 	def __repr__(self):
... 		return str(eval(self.val))
...
>>> SIX = define('1 + 5')
>>> NINE = define('8 + 1')
>>> SIX
6
>>> NINE
9
>>> SIX * NINE
42

You could hide the define class in a module which might make it more convincing…

>>> from hhgtg import define
>>> SIX = define('1 + 5')
>>> NINE = define('8 + 1')
>>> SIX
6
>>> NINE
9
>>> SIX * NINE
42

If you are confused, check the wikiPedia.

2 Responses to “42”

  1. Blake Winton Says:

    I think your mult function should return a new define, instead of evalling it, for the following reason:

    >>> class define:
    def __init__(self, strnumexpr):
    self.val = strnumexpr
    def __mul__(self, x):
    answer = self.val + ‘*’ + x.val
    return eval(answer)
    def __repr__(self):
    return str(eval(self.val))

    >>> SIX = define(’1 + 5′)
    >>> NINE = define(’8 + 1′)
    >>> SIX
    6
    >>> NINE
    9
    >>> SIX * NINE
    42
    >>> SIX * SIX * SIX

    Traceback (most recent call last):
    File “”, line 1, in -toplevel-
    SIX * SIX * SIX
    TypeError: unsupported operand type(s) for *: ‘int’ and ‘instance’
    >>> class define:
    def __init__(self, strnumexpr):
    self.val = strnumexpr
    def __mul__(self, x):
    answer = self.val + ‘*’ + x.val
    return define(answer)
    def __repr__(self):
    return str(eval(self.val))

    >>> SIX = define(’1 + 5′)
    >>> NINE = define(’8 + 1′)
    >>> SIX
    6
    >>> NINE
    9
    >>> SIX * NINE
    42
    >>> SIX * SIX * SIX
    16

  2. christian Says:

    Good call. I didn’t think of weird math beyond the 42 trick! Thanks for the post.

Leave a Reply