Sunday, December 13, 2015

Printing alternate lines using python

for i, line in enumerate(file('myfile.txt')):

   if i % 5 in (0, 1):
       print line

f = open('filename.txt', 'r')
for index, line in enumerate(f.readlines()):
    if index%5 <= 1:
       print(line)

Regular expressions

Username:
/^[a-z0-9_-]{3,16}$/

 Password:
/^[a-z0-9_-]{6,18}$/

 Matchign an email:
/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/

 Matching a phone numeber:
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$
123-456-7890
(123) 456-7890
123 456 7890
123.456.7890
+91 (123) 456-7890

 IP address
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

Friday, December 11, 2015

print specific lines from files

searchquery = 'am'

with open('Test.txt') as f1:
    with open('Output.txt', 'a') as f2:
        lines = f1.readlines()
        for i, line in enumerate(lines):
            if line.startswith(searchquery):
                f2.write(line)
                f2.write(lines[i + 1])
                f2.write(lines[i + 2]

Wednesday, October 28, 2015

generate permutations of [1,2,3]

import itertools
print list(itertools.permutations([1,2,3]))

compress test using zlib in python


import zlib
s = 'hello world!hello world!hello world!hello world!'
t = zlib.compress(s)
print t
print zlib.decompress(t)

Convert a list to tuple

#Question:
#Write a program to generate and print another tuple2 ==0 
#whose values are even numbers in the given tuple (1,2,3,4,5,6,7,8,9,10).

#a=tuple()
tp=(1,2,3,4,5,6,7,8,9,10)
li=list()
for i in tp:
    if i%2==0:
        li.append(i)

tp2=tuple(li)
print tp2

list comprehension to square each odd number in a list.

#Question 16
#Level 2
#Question:
#Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers.
#Suppose the following input is supplied to the program:
#1,2,3,4,5,6,7,8,9
#Then, the output should be:
#1,3,5,7,9
#Hints:
#In case of input data being supplied to the question, it should be assumed to be a console input.
values=[]
values=raw_input()
numbers=[x for x in values.split(",")if int(x)%2 !=0 ]
print numbers