# Translating python code to mathematica code

I am working on a program that does some stuff with the collatz conjecture. I originally wrote it in Python as that is the language I am most familiar with:

n = []
mod = []
step = 0

def lstfill(nb,ne,lst):
while nb <= ne:
lst.append(nb)
nb+=1

def collatz(n, s):
for i in n:
s = 0
print "starting #", i
while i != 1:
if i%2==0:
i=i/2
s+=1
print i
mod.append(i%2)
else:
i=3*i+1
s+=1
print i
mod.append(i%2)
print "mod:", mod
print "steps:", s

lstfill(3,6,n)
collatz(n, step)


However, there are some things I need to do that I can't really do without downloading libraries and I can't do that. So I thought I'd switch to Mathematica. Except I looked at my code and realized I had no idea how to write this code in the Mathematica language. How would I manipulate lists, or create functions, or anything like that? And what is the equivalent of the modulo operator?

Any help would be appreciated. Thanks!

• Did you look up Mod[] already? Have you also searched the site for "collatz"? – J. M.'s ennui Oct 13 '16 at 1:54
• @J.M., thank you for the Mod[] command! I guess I kind of wanted to be able to use my own code that I wrote in Python, just translate it, and I didn't know quite how to write a function or manipulate lists. – heather Oct 13 '16 at 1:57
• Btw, for this application you can - and should - easily add memoization. Simulation of Collatz over a set of initial conditions will inevitably overlap previous computed values. – alancalvitti Oct 13 '16 at 4:18

## 1 Answer

This question demonstrates one of the best things I love about Mathematica; mathematical notation as code.

Using Esc+pw+Esc and Ctrl+Enter you can enter the function in Piecewise mathematical notation. or by code

f[n_Integer] := Piecewise[{{n/2, Mod[n, 2] == 0}, {3*n + 1, Mod[n, 2] == 1}}]


Then with NestWhileList and the Pure Function # != 1 & for stopping,

NestWhileList[f, 8, # != 1 &]

{8, 4, 2, 1}


and with an odd number start,

NestWhileList[f, 11, # != 1 &]

{11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1}


I much prefer these two lines of code to the alternative.

Hope this helps.

• It's what I like about Mathematica too: you can often say a lot with much less. :) – J. M.'s ennui Oct 13 '16 at 2:26
• @heather You can use f[n_Integer/;Positive[n]] to be more strict on the the integers f will accept. I left that out for simplicity as you are just starting. – Edmund Oct 13 '16 at 2:33
• I would've done that as f[n_Integer?Positive] myself. ;) – J. M.'s ennui Oct 13 '16 at 2:59
• Wow, thanks! I didn't realize how much shorter the Mathematica code would be. =) I'm now working on expanding the code and I think I get the general-ish idea of the functions and while loops, so thank you very much! – heather Oct 13 '16 at 11:22
• to be fair, the python version could be made a lot shorter too. – george2079 Oct 13 '16 at 21:18