Python code examples for generating sequences

Here is some Python 2 code which generates the sequence of all mulitples of 7 (A008589).


import math

for n in range(1,1000000):
	if ((n%7)==0):
		print n

Here is some Python 2 code which generates the sequence of integers whose digits sum is 12 ( A235151).

import math

def digitSum(n): # returns sum of digits of n; assumes n is a non-negative integer
	sum=0;
	while(n>0):
		sum=sum+(n%10)
		n=int(n/10)
	return(sum)

for n in range(1,1000000):
	if (digitSum(n)==12):
		print n

Here is some Python 2 code which generates the Ulam sequence (A002858). (There is probably faster code out there: it took 25 minutes for my old laptop to generate the terms up to 106 with this code.)


import math

ulams=[]
ulams.append(1)
ulams.append(2)

limit=1000000

sums=[0 for i in range(2*limit)]

newUlam=2
sumIndex=1

while(newUlam <limit):
	for i in ulams:
		if (i<newUlam):
			sums[i+newUlam] += 1
	while(sums[sumIndex]!=1):
		sumIndex += 1
	newUlam = sumIndex
	sumIndex += 1
	ulams.append(newUlam)
	
for i in ulams:
	print i