Home > Net >  How to impement set-theoretic definition of natural numbers>
How to impement set-theoretic definition of natural numbers>

Time:10-26

How would i go about passing this unit test?

fenc(4)==[[[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]], [[[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]]]]

Im completely stumped, this is my only context.

  • f(0) = [] (0 maps to the empty list)
  • f(n 1) = [f(n),[f(n)]] (n 1 maps to the list that contains f(n) and singleton f(n))

Close as ive got:

def fenc(i):
    arr = []
    if i > 1:
        arr.append([])
        arr.append(fenc(i - 1))
    return arr

fenc(4) outputs:

[[], [[], [[], []]]]

Im not looking for a complete sloution, just some strong pointers. If possible please dont include anything that might "gut the question" as i need to understand the fundamentals behind it.

CodePudding user response:

Figured it out, acctually quite simple.

def fenc(i):
    if i == 0:
        return []
    else:
        return [fenc(i-1), [fenc(i-1)]]

CodePudding user response:

A recursive approach is suggested if you want follow the truth mathematical definition of natural number. My implementation uses strings and not lists.

Generating natural numbers:

  1. following the mathematical set-theoretical definition
def natural_number(n):
    def natural_number_(n):    
        if n == 0: return '[]'
        return '{N}, [{N}]'.format(N=natural_number_(n-1))
    return '[{}]'.format(natural_number_(n))

for i in range(4):
    print(i, natural_number(i))

Output

   0 []
   1 [[]]
   2 [[], [[]]]
   3 [[], [[]], [[], [[]]]]
   4 [[], [[]], [[], [[]]], [[], [[]], [[], [[]]]]]
  1. following the unit test ( the unnatural natural numbers):
def unnatural_number(n):    
    if n == 0: return '[]'
    return '[{N}, [{N}]]'.format(N=unnatural_number(n-1))

for i in range(4):
    print(i, unnatural_number(i))

Output

   0 []
   1 [[], [[]]]
   2 [[[], [[]]], [[[], [[]]]]]
   3 [[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]]
   4 [[[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]], [[[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]]]]

Check if the unnatural_number satisfies the requirements

check = unnatural_number(4) == '[[[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]], [[[[[], [[]]], [[[], [[]]]]], [[[[], [[]]], [[[], [[]]]]]]]]]'
print(check)
# True

Considerations

  1. the difference between the natural_number and unnatural_number is the most outside bracket:
    • '{N}, [{N}]'
    • '[{N}, [{N}]]' <- not really natural!
  2. such construction of natural numbers was originally pointed out by von Neumann
  • Related