Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 3

7)Classes and instances

Find the three elements that sum to zero from


a set of n real numbers
class py_solution:
def threeSum(self, nums):
nums, result, i = sorted(nums), [], 0
while i < len(nums) - 2:
j, k = i + 1, len(nums) - 1
while j < k:
if nums[i] + nums[j] + nums[k] < 0:
j += 1
elif nums[i] + nums[j] + nums[k] > 0:
k -= 1
else:
result.append([nums[i], nums[j], nums[k]])
j, k = j + 1, k - 1
while j < k and nums[j] == nums[j - 1]:
j += 1
while j < k and nums[k] == nums[k + 1]:
k -= 1
i += 1
while i < len(nums) - 2 and nums[i] == nums[i - 1]:
i += 1
return result

print(py_solution().threeSum([-25, -10, -7, -3, 2, 4, 8, 10]))

Sample Output:

[[-10, 2, 8], [-7, -3, 10]]

8)Regular expression

Write a Python program to search a literals string in a string and also find the location within the original
string where the pattern occurs.

import re
pattern = 'fox'
text = 'The quick brown fox jumps over the lazy dog.'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "%s" in "%s" from %d to %d ' % \
(match.re.pattern, match.string, s, e))
9)Implementing file concepts
Write a Python program to create a file where all letters of English alphabet are listed by specified
number of letters on each line.
import string
def letters_file_line(n):
with open("words1.txt", "w") as f:
alphabet = string.ascii_uppercase
letters = [alphabet[i:i + n] + "\n" for i in range(0, len(alphabet),
n)]
f.writelines(letters)
letters_file_line(3)

Output:
words1.txt
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ

Write a python program to find the longest words.

def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]

print(longest_word('test.txt'))

Output:

['w3resource.com.']

5)Excersice using apply() filter().map() reduce()


# Python code to illustrate
# filter() with lambda()
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(filter(lambda x: (x%2 != 0) , li))
print(final_list)

o/p:

[5, 7, 97, 77, 23, 73, 61]


# Python code to illustrate cube of a number 
# showing difference between def() and lambda().
def cube(y):
    return y*y*y;
  
g = lambda x: x*x*x
print(g(7))
  
print(cube(5))

Op:

343
125

# Python code to illustrate 


# reduce() with lambda()
# to get sum of a list
from functools import reduce
li = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), li)
print (sum)

o/p

193

# Python code to illustrate 


# map() with lambda() 
# to get double of a list.
li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]
final_list = list(map(lambda x: x*2 , li))
print(final_list)

o/p:

[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]

You might also like