Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1. Specify whether an iteration loop or a counter loop should be used to write e

ID: 3785199 • Letter: 1

Question

1. Specify whether an iteration loop or a counter loop should be used to write each function below. Also, specify if an accumulator variable should be used. You do not need to write complete code for these problems.

a) A function a positive integer x and returns a list [0, 1, 2, ... x]

b) A function is passed a string and returns True if any 2 consecutive letters in the string are the same, or False otherwise

c) A function is passed a list of strings and returns the length of the shortest string.

2.Explain why the Python list class has a sort method, whereas the set class does not.

3. Assume that the variable d is a Python dictionary. What is the difference between the following statements:

>>> d['abc']

Explanation / Answer

Que 1.

a)

We need to use counter loop, as we need to count the number of ierations so that we can insert particular number into output list, please see the code below.

Accumulator variable needs to be used for storing the output list.

Python code:

def f1(x):
   out = []
   for i in range(0,x+1):
       out.append(i)
   return out
print f1(5)

b)

We need to use iterator loop since we just need to iterate through the string, please see the code below.

No need to use Accumulator variable.

Python code:

def f2(s):
   for i in range(0,len(s) - 1):
       if(s[i] == s[i+1]):
           return True
       else:
           pass
   return False
print f2("akashh")

c)

We need to use iterator loop since we just need to iterate through the list, please see the code below.

Accumulator variable needs to be used for length of smallest string.

Python code:

def f3(l):
   minl = len(l[0])
   for i in range(0,len(l)):
       minl = min(minl,len(l[i]))
   return minl
print f3(["aaa","aaaa","a"])

Que 2.

The main purpose of set class in python is to provide unordered collection of unique elements. So, set does not support indexing, so order of elements does not matter. This is the main reason why set does not support sort methode in python.

Whereas lists supports indexing, so order of elements does matter, and hence list class have sort methode.

Que 3.