Professional Documents
Culture Documents
7) Classes and Instances Find The Three Elements That Sum To Zero From A Set of N Real Numbers
7) Classes and Instances Find The Three Elements That Sum To Zero From A Set of N Real Numbers
Sample Output:
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
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.']
o/p:
Op:
343
125
o/p
193
o/p:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]