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

For each of the tasks below, write a one-line Python expression that will achiev

ID: 3923161 • Letter: F

Question

For each of the tasks below, write a one-line Python expression that will achieve the result. Code the Python way; the simpler, the better. Retrieve the n largest items from a list or a tuple of numbers 1t e.g., n, 1t = 3, [1, 6, 3, 11, 14, 7, 0, 2, 19, 10] rightarrow [11, 14, 19] Create a new string with the words of string s in reverse order e.g., s = 'dog bird cow ant' rightarrow 'ant cow bird dog' Add all the comma-separated numbers contained in a string e.g., s= "1.7, 5, 3.3" rightarrow 10 Use list comprehension to realize each of the tasks below. Create a list of all the divisors of a given number n (excl, 1 and n) e.g., n = 99 rightarrow [3, 9, 11, 33] Create a list of cubes of the numbers in list 1, discarding non-numbers e.g., 1 = [(), 2, 'tr', (4-7j), int('5'), 22//3, (3**2), 10] rightarrow [8, 125, 343, 729, 1000] Create a list of unique triples (a, b, c) such that a^2 + b^2 = c^2, 0 lessthanorequalto a, b, c lessthanorequalto N. e.g., N = 16 rightarrow [(3, 4, 5), (5, 12, 13), (6, 8, 10), (9, 12, 15)]

Explanation / Answer

import heapq

#answers for question a)
#Retrieving n largest numbers
print heapq.nlargest(2, [11, 13, 12, 14, 15])

#Reversing the order of words in a string
print " ".join(reversed("Now the words are reversed".split()))

#Adding the comma separated numbers
print sum([int(x) for x in '3 ,2 ,6 '.split(',')])

#answers for question b)
#divisors for a number
#assuming that question b) does not need logic in ONE-LINE. I have used a function for this.
def divisors(number):
return [(i) for i in xrange(1, int(number*0.5) + 1) if number % i == 0]

print divisors(36)

#list of cubes of numbers after omitting the non-numeric characters
l = [(), 2, 'tr', (4-7j), int('5'), 22//3, (3**2), 10]
print [(i**3) for i in l if str(i).isdigit()]

#unique triples(a,b,c)
def triples(n):
   #return [(i) for i in xrange(0, n) if i**2]
   print [(a,b,c) for a in range(1, n) for b in range(a, n) for c in range(b, ) if a**2 + b**2 == c**2]
                  
triples(16)

OUTPUT: