In Python 3.6, we want to write a function that takes a list L of integers and r
ID: 3591190 • Letter: I
Question
In Python 3.6, we want to write a function that takes a list L of integers and returns the second smallest integer in the list and the smallest index at which that number occurs.A. Write a version of the function using loops and indices
B. Write a function using python builtin methods (e.g., list methods) In Python 3.6, we want to write a function that takes a list L of integers and returns the second smallest integer in the list and the smallest index at which that number occurs.
A. Write a version of the function using loops and indices
B. Write a function using python builtin methods (e.g., list methods)
A. Write a version of the function using loops and indices
B. Write a function using python builtin methods (e.g., list methods) A. Write a version of the function using loops and indices
B. Write a function using python builtin methods (e.g., list methods)
Explanation / Answer
from math import inf
import heapq
def second_smallest(numbers):
m1, m2 = inf, inf
m1i, m2i = -1, -1
for i in range(len(numbers)):
if numbers[i] < m1:
m1, m2 = numbers[i], m1
m1i, m2i = i, m1i
elif numbers[i] < m2:
m2 = numbers[i]
m2i = i
return (m2, m2i)
numbers = [1,5,9,0,6,-1,8]
print(second_smallest(numbers))
second_smallest_by_list_method = min([(numbers[i], i) if numbers[i] != min(numbers) else (float('inf'), i) for i in range(len(numbers))])
print(second_smallest_by_list_method)
# code link: # code link: https://paste.ee/p/HRBYM
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.