Question

Write a single Python statement that calls silly2 and results in the output: 2 2 We're...

Write a single Python statement that calls silly2 and results in the output: 2 2 We're dead, Fred

def silly2(nums, indices, extra=None):
print(len(nums), len(indices))

new_indices = []
for i in indices:
if i >= 0 and i < len(nums):
new_indices.append(i)

if extra:
new_indices.append(extra)

try:
for index in new_indices:
if index < len(nums):
print(nums[index])
except IndexError:
print("We're dead, Fred")
  
silly2([1, 2], [0, -1])

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

silly2( [1,2] , [-2, -1] , -3 )

Explanation:

Since we need 2 2 at the output and we can find a statement print(len(nums), len(indices)), it is obvious that the size/length of both list we pass to the function should be 2 such that len(nums) = 2 and len(indices) = 2 .

Now the question is what should be the nums list and indices list.

First consider nums list. Since we are not using any values in nums list, it doesn't matter which values we give to that list. (Note that there is a print statement which prints the values of nums, but we don't want that statement to execute as per given output. That print statement is controlled by other aspects which we will consider below)

Now what should be the indices list.

For this, we should have a greater understanding of what the program does.

The program basically selects some indices from the indices list such that these indices are less than the size/length of nums list and greater than 0. (Alternatively we are selecting some valid indices for nums list).

These indices are then added to a new list( new_indices ). An extra is also added if present. The program then prints the values present in nums list at valid positions specified by new_indices. (ie.., for each index value in new_indices , the program print value present index position of nums list if index is less than size of nums list)

Now, from output specification, we can find that we don't want to print any values of nums list, but wants an exception Indexerror which happens when a invalid index is tried with a list. ie.., the new_indices must not contain any valid indices for nums list and must contain at least one invalid index such that it is less that size/length of nums. Now since, when adding elements from from indices to new_indices, we are checking both conditions (i>=0 and i< len(nums) ), only valid indices will get added to new_indices. But we don't want that (we don't want to print any values in numslist). Therefore indices must contains two elements such that the are not valid (either less than 0 or greater than or equal to length of nums) for nums list. Therefore -2,-1 which are less than 0.

Now the new_indices must contain an invalid index which is less than length of nums list. The only way of adding this is through extra. Instead of taking default value for extra, we need to give some value that satisfies our condition. So which value for extra.

We can give any invalid index value less than length of nums list. Since python allows to index using negative number (eg -1 for last element, -2 for second last element ) we need to give to give a negative number such that nums list gets out of bound. ie..., a negative value less than negative of number of elements in nums list ( < - len(nums) ) and hence choose -3.

Now -3 will be added to new_indices and since it is less than size/length of nums list, it will try to print nums[-3] which results in a index error and it will output: We're dead, Fred. Therefore after combining previous output, it will print 2 2 We're dead, Fred.

Add a comment
Know the answer?
Add Answer to:
Write a single Python statement that calls silly2 and results in the output: 2 2 We're...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • What are the outputs for each question PYTHON Question 6 bools = [True, 0>-1, not not...

    What are the outputs for each question PYTHON Question 6 bools = [True, 0>-1, not not True, 2%2 == 0, True and False] index = 0 while bools[index]: index += 1 print(index) a) 0 b) 1 c) 2 d) 3 e) none of the above Question 7 for i in range(2): for j in range(1): print(i, j, end = " ") a) no output b) 0 0 1 0 2 0 c) 0 0 0 1 1 0 1 1...

  • need help on all parts please and thank you (e) What is the correct output of...

    need help on all parts please and thank you (e) What is the correct output of this code? (2 pts) >>> def func(x): >>> res = 0 >>> for i in range (len (x)): res i >>> return res >>> print (func(4)) ( 4 5 ) 6 ()7 ( What could be described as an immutable list? (2 pts) () a dimple ( ) a tuple ( ) a truffle () a dictionary (g) What is the result of the...

  • Write a python program write a function numDigits(num) which counts the digits in int num. Answer...

    Write a python program write a function numDigits(num) which counts the digits in int num. Answer code is given in the Answer tab (and starting code), which converts num to a str, then uses the len() function to count and return the number of digits. Note that this does NOT work correctly for num < 0. (Try it and see.) Fix this in two different ways, by creating new functions numDigits2(num) and numDigits3(num) that each return the correct number of...

  • Starting out with Python 4th edition I need help I followed a tutorial and have messed...

    Starting out with Python 4th edition I need help I followed a tutorial and have messed up also how does one include IOError and IndexError exception handling? I'm getting errors: Traceback (most recent call last): File, line 42, in <module> main() File , line 37, in main winning_times = years_won(user_winning_team_name, winning_teams_list) File , line 17, in years_won for winning_team_Index in range(len(list_of_teams)): TypeError: object of type '_io.TextIOWrapper' has no len() Write program champions.py to solve problem 7.10. Include IOError and IndexError...

  • IN PYTHON ''' Helper func 3: checksum_ISBN Input: a list with 9 single digit number in...

    IN PYTHON ''' Helper func 3: checksum_ISBN Input: a list with 9 single digit number in it (first 9 digit in ISBN) Output: print out: "The correct checksum digit is:__. Now we have a legit ISBN: _____" Hint: just loop through 0-9, test every one with helper func1 to find out the one checksum that forms a legit ISBN with the correct ISBN in lis (10 numbers), call helper func2 to format it correctly. Then print the final result. '''...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • Write in Python This program: 1. Correct the compute_cells_state function which receives as parameter an array...

    Write in Python This program: 1. Correct the compute_cells_state function which receives as parameter an array of 2-dimensional booleans. The table is indexed online then in column.    A cell is called "alive" if the Boolean is true otherwise it is said that it is "dead".    Each cell to 8 "neighbors" (the 4 adjacent cells and the 4 cells diagonally)    The function modifies each cell according to the following rule:      - if the cell has 2 or 3 living neighbors she...

  • Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in...

    Python 12.10 LAB: Sorting TV Shows (dictionaries and lists) Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since...

  • Task 4: for Loops (PROGRAM IS IN PYTHON) SHOW INPUT AND OUTPUT SCREEN SHOTS #!/usr/bin/python3 # ...

    Task 4: for Loops (PROGRAM IS IN PYTHON) SHOW INPUT AND OUTPUT SCREEN SHOTS #!/usr/bin/python3 # Measure some strings: words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) #!/usr/bin/python3 # Measure some strings: words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) forvar in list(range(5)): print (var) for letter in 'Python': # traversal of a string sequence print ('Current Letter :', letter) print() fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # traversal of List...

  • Greeting! Kindly help me to solve my finals in PYTHON, I don't have a knowledge in...

    Greeting! Kindly help me to solve my finals in PYTHON, I don't have a knowledge in PYTHON, new student. Please, please, I'm begging, Kindly answers all the questions. I'm hoping to grant my request. Thanks in advanced. 1.) What is the output of the following snippet? l1 = [1,2] for v in range(2): l1.insert(-1,l1[v]) print(l1)        a.) [1, 2, 2, 2]        b.) [1, 1, 1, 2]        c.) [1, 2, 1, 2]        d.) [1,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT