CoCalc Shared Fileshey.sagews
Views : 29
# 8
# define a function sum_digits(n) that takes an integer and returns the sum of its digits

def sum_digits(n):
sum = 0
while (n != 0):
sum = sum + int(n % 10)
n = int(n/10)
return sum

sum_digits(18)

9
sum_digits(98)

17


# 9
# write a program to find all triples with positive integers a, b, c <= 10 where a^2 + b^2 = c^2

for a in [1..100]:
for b in [1..100]:
c2 = a**2 + b**2
c = sqrt(c2)
if int(c + 0.5) ** 2 == c2 and c <= 10:
print "{}, {}, {}".format(a, b, c)

3, 4, 5 4, 3, 5 6, 8, 10 8, 6, 10


# 10
# define a function a_count(s) that takes a string and counts the number of occurrences of the letter "a" in the string

def a_count(s):
s = list(s) # turn string into list of characters
acount = 0
for char in s:
if char == "a":
acount = acount + 1
return acount

a_count("aaaaa")

5
a_count("b")

0


# # 11
# write a program that produces 100 random numbers from [0, 100] and stores them in separate lines of a text file

datafile = open("rand_store.txt", "w") # create a file and tell sage we are writing
for i in [1..100]: # loop through the WRITE command 100 times
datafile.write(str(randint(0, 100))) # tell sage what we want to write into the file. remember to turn randint into string
datafile.write("\n") # print each on a new line
datafile.close() # close the file once we have written the 100 lines



# 12
# define a function read_data(filename) that opens the file called filename and prints a list of the numbers in the file
filename = open("rand_store.txt", "r") # open the file and tell sage we we are doing. we are reading, so "r"
numlist = []
for i in [0..99]:
dline = int(dline.rstrip())
numlist.append(dline)
print numlist

read_data(datafile)

[68, 77, 70, 40, 90, 27, 79, 37, 99, 98, 1, 78, 82, 24, 16, 66, 55, 0, 17, 47, 44, 98, 73, 73, 21, 36, 64, 10, 67, 46, 4, 35, 19, 29, 14, 94, 0, 30, 62, 100, 41, 27, 59, 35, 28, 4, 82, 8, 86, 58, 3, 54, 50, 100, 79, 27, 68, 95, 62, 38, 46, 39, 2, 83, 19, 10, 4, 41, 87, 98, 11, 82, 30, 57, 89, 15, 46, 69, 26, 68, 44, 65, 78, 19, 70, 84, 66, 81, 57, 30, 38, 22, 28, 34, 23, 81, 16, 62, 79, 76]


# 13
# use map and an anonymous (lambda) function to produce cubes of the numbers in the list [3, 7, 2, 5]

testlist = [3, 7, 2, 5]
map(lambda x: x**3, testlist)

[27, 343, 8, 125]


# 14
# consider the following sequence defined by a function on the positive integers t(1) = 3, t(2) = 4,
# t(3) = 5, t(n) = t(n - 1) + t(n - 2) + t(n - 3)
# define a recursive function recurst(n) that takes a positive integer n and outputs t(n). find t(10)

def recurst(n):
if n == 1:
return 3
elif n == 2:
return 4
elif n == 3:
return 5
elif n > 3:
tn = recurst(n - 1) + recurst(n - 2) + recurst(n - 3)
return tn

recurst(10)

440