In: Computer Science
PYTHON CODE
- Write the body of a function second_instance(s, c) which consumes a string s and a length 1 string c that is contained at least twice in s and returns the index of the second location of c.
second_instance: Str Str -> Nat
Requires:
len(c) == 1
c occurs at least twice in s
Examples:
second_instance("banana", "a") => 3
second_instance("bb", "b") => 1
- Write the body of a function make_list(n) which consumes a natural number n and returns a list of strings where in position , the number is repeated as a string times. You must use loops in your solution. Do not use recursion or abstract list functions.
Returns the list of strings formed by in position i,
repeating i a total of i times
make_list: Nat -> (listof Str)
Examples:
make_list(0) => ['']
make_list(3) => ['', '1', '22', '333']
- Write the body of a function niven(n) using recursion that consumes a natural number n and returns True if and only if n is a Niven number and False otherwise. A Niven number is a number which is divisible by the sum of its digits.
Returns True if and only if n is a Niven number.
niven: Nat -> Bool
Examples:
niven(0) => False
niven(1) => True
niven(132) => True
niven(143) => False
- Write the body of a function find_max(L) using loops that returns the maximum of a non-empty list of integers L. Do not use recursion, abstract list functions, or the command max.
Returns the maximum in a non-empty list of integers L
find_max: (listof Int) -> Int
Examples:
find_max([1]) => 1
find_max([-10,-1,-5]) => -1
program plan:
second_instance():
make_list():
nivel(n):
find_max()
program:
def second_instance(s, c):
count = 0
for i in range(len(s)):
if c == s[i]:
count+=1
if count == 2:
return i
def make_list(n):
l = ['']*(n+1)
for i in range(1,n+1):
l[i] = str(i)*i
return l
def niven(n):
total = 0
n1 = n
while n1>0:
total += n1%10
n1 = n1//10
return n%total == 0
def find_max(L):
m = L[0]
for x in L:
if m < x:
m = x
return m
print(second_instance("banana","a"))
print(make_list(3))
print(niven(18))
print(find_max([-10,-1,-5]))
output: