Question

In: Computer Science

def myLength(mylist):    count = 0    for index in range(len(myList)):        print(myList[index])       ...

def myLength(mylist):
   count = 0
   for index in range(len(myList)):
       print(myList[index])
       count = count + 1
   return count

def myLength2(mylist):
   count = 0
   for element in myList:
       print(element)
       count = count + 1
   return count
  
  
Use these two functions as examples to write your Python function below!

Function 1: Write a function called myCount that takes in two parameters (a list and an item) like this:
def myCount(myList,item):
The function should returns an integer representing how many times the given item is in the given list. Could be from zero up to infinity. You cannot use the list method list.count() to impelement this function.

Function 2: Write a function called myIndex that takes in two parameters (a list and an item) like this:
def myIndex(myList,item):
The function should return an integer representing the index of the first occurrence of the given item in the given list. Returns from zero up to inifinity if the item is found. Returns -1 if it is not in the list.You cannot use the list method list.index() to impelement this function.

Function 3: Write a function called contains that takes in two parameters (a list and an item) like this:
def contains(myList,item):
The function should return True if the item is present in the list and False if it is not. You cannot use the operator "in" to implement this function, like:
if item in myList: #not allowed!
Instead, you should write a loop to look through each element, one at a time, to determine if an item is in the list. This is allowed:
for element in myList: #allowed!

Function 4: Write a function called myInsert that takes in three parameters (a list, an index position, and an item) like this:
def myInsert(myList,index,item):
The function should return a new list consisting of everything from the old list but with the new item inserted at the given index. If index is not valid (less than zero), then the function returns the original list with no changes. You cannot use the list method list.insert() to impelement this function.

Solutions

Expert Solution

Function 1 -

def myCount(myList,item):
count=0
for element in myList:
if element==item:
count=count+1
return count

print(myCount([1,4,5,1,1,5,'apple','cat','cat'],1))

Explanation :

1.We define a function named myCount which accepts myList and item as parameters.

2.we define a variable count with value 0.

3.we then iterate through element in the myList and check if myList element is equal to item . if yes then we increase count value by1 which represents nothing but the count of item in myList. After running for loop , return the count value.

4.Finally call the function by passing arguments , i have used myList = [1,4,5,1,1,5,'apple','cat','cat'] and item =1 in above example. It return value 3 since 1 has 3 occurences in myList.

Function 2 -

def myIndex(myList,item):
count=0
for index in range(len(myList)):
if myList[index]==item:
return index
else:
count=count+1
  
if count==len(myList):
return -1
  
  
print(myIndex([1,4,5,1,1,5,'apple','cat','cat'],'cat'))

Explanation :

1.We define a function named myIndex which accepts myList and item as parameters.

2.we define a variable count with value 0.

3.we then use for loop with iterations equal to len(myList) using range function.Here index takes value from 0 till len(myList) minus 1. if len(myList) = 5 then index takes value from 0 till 4.

if mylist value at index equal to item then we return index else we increment count by 1.

4.After the completion of for loop , if count value is equal to len(myList) it means no item was found in the list.Hence we return -1.

5.Finally call the function by passing arguments , i have used myList = [1,4,5,1,1,5,'apple','cat','cat'] and item ='cat' in above example. It return value 7 since first occurence of item 'cat' is at 7th index.

Function 3 -

def contains(myList,item):
count=0
for element in myList:
if element==item:
return True
else:
count=count+1
  
if count==len(myList):
return False   
  
print(contains([1,4,5,1,1,5,'apple','cat','cat'],3))

Explanation :

1.We define a function named contains which accepts myList and item as parameters.

2.we define a variable count with value 0.

3.we then iterate through element in the myList and check if myList element is equal to item . if yes then we return True else we increase count value by1 .

4.After the completion of for loop , if count value is equal to len(myList) it means no item was found in the list.Hence we return False.

5.Finally call the function by passing arguments , i have used myList = [1,4,5,1,1,5,'apple','cat','cat'] and item =3  in above example. It return False since f3 is not present in myList.

Function 4 -

def myInsert(myList,index,item):
new_list=[]
if index<0:
return myList
for i in range(len(myList)):
if i != index:
new_list.append(myList[i])
else:
new_list.append(item)
new_list.append(myList[i])
return new_list
  
print(myInsert([1,4,5,3,'apple','cat'],4,6))
  

Explanation :

1.We define a function named myInsert which accepts myList,index and item as parameters.

2.we define am empty list named new_list

3.We check if index is less than zero then we return original list which is myList.

3.we use for loop with iterations equal to len(myList) using range function.Here i takes value from 0 till len(myList) minus 1. if len(myList) = 5 then i takes value from 0 till 4.

if i is not equal to index passed in function then we append myList element at index i to new_list

4.But if i equal to index passed in function then we append item passed in function to new_list and after that we append myList element at index i to new_list since we have to insert new element not replace new element with old element in list.

5.Finally call the function by passing arguments , i have used myList =[1,4,5,3,'apple','cat'] , index=4 and item =6 in above example. It return new_list = [1, 4, 5, 3, 6, 'apple', 'cat'] we have insert item 6 at index 4.


Related Solutions

PYTHON CODE: def square_matrix_multiplication(matrix1,matrix2): C=[[0 for i in range(len(matrix1))] for i in range(len(matrix2))] for i in...
PYTHON CODE: def square_matrix_multiplication(matrix1,matrix2): C=[[0 for i in range(len(matrix1))] for i in range(len(matrix2))] for i in range(len(matrix1)): for j in range(len(matrix2[0])): C[i][j]=0 for k in range(len(matrix2)): C[i][j] += matrix1[i][k]*matrix2[k][j]    return C I use that function in my code. When I type like "return C", It does not work. If I type print(C), then my code works. Why is it happening? I created two user-entered matrices above the function, then I called the function.
The functions are tested in the following main(): def recSum1(somelist): if len(somelist) == 1: return somelist[0]...
The functions are tested in the following main(): def recSum1(somelist): if len(somelist) == 1: return somelist[0] else: a = recSum1(somelist[:len(somelist)//2]) b = recSum1(somelist[len(somelist)//2:]) return a + b def recSum2(somelist): if len(somelist) == 1: return somelist[0] else: return somelist[0] + recSum2(somelist[1:]) import random def main(): N = 100 myList = [random.randint(-500, 500) for i in range(N)] print(myList) print("The sum of the numbers is: " + str(sum(myList))) print("The sum of the numbers using recSum1 is: " + str(recSum1(myList))) print("The sum of the...
def annoying_valley(n): if n == 0: print() elif n == 1: print("*") elif n == 2:...
def annoying_valley(n): if n == 0: print() elif n == 1: print("*") elif n == 2: print("./") print("*") print(".\\") elif n == 3: print("../") print("./") print("*") print(".\\") print("..\\") elif n == 4: print(".../") annoying_valley(3) print("...\\") elif n == 5: print("..../") annoying_valley(4) print("....\\") elif n == 6: print("...../") annoying_valley(5) print(".....\\") else: print("." * (n - 1) + "/") annoying_valley(n - 1) print("." * (n - 1) + "\\") def annoying_int_sequence(n): if n == 0: return [] elif n == 1: return...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and...
def anagramSolution1(s1,s2): alist = list(s2) pos1 = 0 stillOK = True while pos1 < len(s1) and stillOK: pos2 = 0 found = False while pos2 < len(alist) and not found: if s1[pos1] == alist[pos2]: found = True else: pos2 = pos2 + 1 if found: alist[pos2] = None else: stillOK = False pos1 = pos1 + 1 return stillOK include all operations and calculate the Big-O and the values for c and n0.
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def...
class Board: def __init__(self): self.pieces = [[None for i in range(8)] for j in range(8)] def __str__(self): s = "" for j in range(7, -1, -1): #for each row for i in range(8): # for each column if self.pieces[j][i] is None: # if self.pieces[j][i] is None s += "." # populate the row with '.' val for each column else: s += self.pieces [j][i].get_symbol() s += "\n" #after each row add a new line return s # return after iterating...
def check(s): #Conditions applied 1,5,6 if len(s)=9 and s[0].isupper() and s[-1].isdigit(): upper_count = sum(1 for c...
def check(s): #Conditions applied 1,5,6 if len(s)=9 and s[0].isupper() and s[-1].isdigit(): upper_count = sum(1 for c in s if c.isupper()) lower_count = sum(1 for c in s if c.islower()) number_count = sum(1 for c in s if c.isdigit()) #Conditions 2,3,4 if upper_count=3 and lower_count==3 and number_count==3: #Condition 7 { Two consecutive alphabets can’t be small } for i in range(1,len(s)): if s[i-1].islower() and s[i].islower() : return 'reject' else: return 'reject' #All conditions satisfies here, so accept return 'accept' else: return...
Consider the following code segment:    count = 1    while count <= 10:       print(count,...
Consider the following code segment:    count = 1    while count <= 10:       print(count, end=" ") Which of the following describes the error in this code? The loop control variable is not properly initialized. The comparison points the wrong way. The loop is infinite. The loop is off by 1. Does this code contain an error? If so, what line is the error on? 0: ans = input("Yes/No? ") 1: if ans == "Yes": 2: print("Confirmed!") 3: else...
def longest(string): start=0;end=1;i=0; while i<len(string): j=i+1 while j<len(string) and string[j]>string[j-1]: j+=1 if end-start<j-i: #update if current...
def longest(string): start=0;end=1;i=0; while i<len(string): j=i+1 while j<len(string) and string[j]>string[j-1]: j+=1 if end-start<j-i: #update if current string has greater length than #max start and end end=j start=i i=j; avg=0 for i in string[start:end]: avg+=int(i) print('The longest string in ascending order is',string[start:end]) print('Teh average is',avg/(end-start)) s=input('Enter a string') longest(s) i need a definition and explanation of this code that how it works?
In Python: def _nodeAtIndex(self, index): """Returns the reference to the node at the given index; If...
In Python: def _nodeAtIndex(self, index): """Returns the reference to the node at the given index; If index is out of range, raise IndexError """ # PROBLEM 2 # You can assume that index is non-negative. # You need to traverse the list and stop at the required index. # YOUR CODE HERE (THIS IS WHAT I HAVE CURRENTLY WRITTEN BUT I"M STUCK AND DON"T KNOW WHAT TO DO) while current != None: # use a while-loop. plist.append(current._element) # process the...
pyramid.py program for i in range(1,6): for j in range(i): print("*",end=' ') print("\n",end='') Exercise: Create the...
pyramid.py program for i in range(1,6): for j in range(i): print("*",end=' ') print("\n",end='') Exercise: Create the pyramid similar to the above pyramid.py program using a while loop. Name your program whilepyramid.py and submit it on blackboard.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT