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

Write a program that accepts a sentence and calculate the number of letters and digits.

#Question 13
#Level 2

#Question:
#Write a program that accepts a sentence and calculate the number of letters and digits.
#Suppose the following input is supplied to the program:
#hello world! 123
#Then, the output should be:
#LETTERS 10
#DIGITS 3

a=raw_input()
letters=0
digits=0
for c in a:
    if c.isdigit():
        digits = digits + 1
    else:
        letters=letters + 1

print "Letters s" ,letters
print "Digits" ,digits

Write a program, which will find all such numbers between 1000 and 3000

#Question:
#Write a program, which will find all such numbers between 1000 and 3000
#(both included) such that each digit of the number is an even number.
#The numbers obtained should be printed in a comma-separated sequence on a single line.

values=[]
for x in range(1000,3000):
    s=str(x)
    if (int(s[0]) %2 == 0) and (int(s[1]) %2 == 0) and (int(s[2]) %2 == 0) and (int(s[3]) %2 == 0):
        values.append(s)
print "-".join(values)

4 digit binary numbers as its input and then check whether they are divisible by 5 or not.

#Question:
#rite a program which accepts a sequence of comma separated
#4 digit binary numbers as its input and then check whether they are divisible by 5 or not.
#The numbers that are divisible by 5 are to be printed in a comma separated sequence.
#Example:
#0100,0011,1010,1001
#Then the output should be:
#1010
#Notes: Assume the data is input by console.
#
#
#Hints:
#In case of input data being supplied to the question, it should be assumed to be a console input.

#Solution:
value = []
items=[x for x in raw_input().split(',')]
for p in items:
    print p
    intp = int(p, 2)
    print intp
    if not intp%5:
        value.append(p)

print ','.join(val

Lowercase to Uppercase

#Question
#Write a program that accepts sequence of lines as input and prints the lines after making all characters in the sentence capitalized.
#Suppose the following input is supplied to the program:
#Hello world
#Practice makes perfect
#Then, the output should be:
#HELLO WORLD
#PRACTICE MAKES PERFECT

##Hints:
#In case of input data being supplied to the question, it should be assumed to be a console input.

stopword=""
while True:
    str=raw_input()
    if str.strip()==stopword:
        break
print str.upper()
   

Dictionaries

#Question:
#With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.
#Suppose the following input is supplied to the program:
#8
#Then, the output should be:
#{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}

def createdict(n):
    dictofnumber=dict()
    for i in range(1,n):
        dictofnumber[i]=i * i
    return dictofnumber
   
a=createdict(100)
print a
   

program which will find all such numbers which are divisible by 7 but are not a multiple of 5

#Question:
#Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,


def mat():
    mylist=[]
    for i in range(2000,3000):
        count=0   
        if (i % 7 == 0) and (i % 5 != 0):
            count=count + 1
            mylist.append(i)
    return mylist

a=mat()
print a
   

Sunday, October 18, 2015

send mail from python

import smtplib

def send_email(sender, receiver, subject, body):
    msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s"
        %(sender, receiver, subject, body))
    s = smtplib.SMTP('smtp.gmail.com')
    s.starttls()
    s.login('user@gmail.com','pass')
    s.sendmail(sender, [receiver], msg)
    s.quit()
   
send_email('user@gmail.com','user@gmail','Test mail from script','Regards,Parag')

Draw circle using python

import turtle

 
           
def drawPolygon(t, sideLength, numSides):
    turnAngle = 360 / numSides
    for i in range(numSides):
        t.forward(sideLength)
        t.right(turnAngle)

def drawCircle(anyTurtle, radius):
    circumference = 10 * 3.1415 * radius
    sideLength = circumference / 360
    drawPolygon(anyTurtle, sideLength, 360)


wn = turtle.Screen()
wheel = turtle.Turtle()
turtle.pen(fillcolor="black", pencolor="red", pensize=10)
drawCircle(wheel, 20)
turtle.fillcolor('red')

wn.exitonclick()

Stars Patterns

*
**
***
****
*****
 

1
1 2
1 2 3
1 2 3 4

 

* * * * *
* * *
* *
*

     * 
     **
    ***
  ****
 *****
 
 
         1
       232
      34543
     4567654
    567898765  
 
 
1
121
12321
1234321
123454321



1234
5678
9012
3456
7890
 
 
         *
      *  *
   *  *  *
*  *  *  *
 
*                         *
* * *              * * *
* * * * *   * * * * *
* * * * * * * * * * *
 
 
 
*                         *
   *                   *
*     *             *     *
   *     *       *     *
*     *      *      *     *
   *     *       *     *
*     *             *     *
   *                   *
*                         *
 
 
  *   *   *   *   *
      *   *   *   *
        *   *   *
          *   *
            *
          *   *
        *   *   *
      *   *   *   *
    *   *   *   *   *
 
 
                *
            * * *
          * * * * *
        * * * * * * *
      * * * * * * * * *
        * * * * * * *
          * * * * *
            * * *
              *
            * * *
          * * * * *
 
 


     *
       * *
         * * *
           * * * *
         * * *
       * *
     *
 
 
 
 
* * * * * * * * *
* * * *   * * * *
* * *       * * *
* *           * *
*               *
* *           * *
* * *       * * *
* * * *   * * * *
* * * * * * * * *
 
 
 
 
* * * * * * * * * * * * * * * * *
  * * * * * * *   * * * * * * *
    * * * * *       * * * * *
      * * *           * * *
        * * * * * * * * *
          * * * * * * *
            * * * * *
              * * *
                *
 
 
 
 
      *
    * * *
  * * * * *
* * * * * * *
*           *
* *       * *
* * *   * * *
* * * * * * *
* * *   * * *
* *       * *
*           *
* * * * * * *
  * * * * *
    * * *
      *
 
 
 
* * * * * * * * * * * * * * * * * * * * * * * * *
  *           *   *           *   *           *
    *       *       *       *       *       *
      *   *           *   *           *   *
        *               *               *
      *   *           *   *           *   *
    *       *       *       *       *       *
  *           *   *           *   *           *
* * * * * * * * * * * * * * * * * * * * * * * * *
 
 
 
 
 
 5
 5 4
 5 4 3
 5 4 3 2
 5 4 3 2 1
 
 
 
333
22
1
 
 
 1
 22
 333
 4444
 55555
 
 
 1 2 3 4 5
 2 3 4 5
 3 4 5
 4 5
 5
 
 
            *
          *   *
        *       *
      *           *
    *               *
 
 
 
 
1
01
101
0101
10101
 
 
 
1 
1 0 
0 1 0 
0 1 0 1 
1 0 1 0 1 
# # # # #
 # # # #
  # # #
   # #
    #
 
 
 
55555
54444
54333
54322
54321
 
 
 
      
 
 
  
 
        
 
 
 
 
 
     

 
  
 

 

 

Check if a string contains unique characters

def isuniq(string1):
    uchars=set()
    for c in string1:
        if c  in uchars:
            return False
        else:
            uchars.add(c)
    return True
   
print isuniq('parag')
   

Matrix Multiplication

3 * 3 matrix multiplication

matrix1=[[2]*3] * 3
matrix2=[[10] * 3] * 3
matrix3=[[0] * 3] * 3
print matrix1
print matrix2

for i in range(3):
    for j in range(3):
        matrix3[i][j]=matrix1[i][j] * matrix2[i][j]
print matrix3

__main__

When you run a python script directly (example: $ python script.py), you want to set a starting point of the script. Python scripts are interpreted from the first line, then goes to the second line and so on ...

import module

def my_function():
  # code here

x = my_function()

But you want to make your code more structured, so you come up with this:

import module

def my_function():
  # code here

def main():
  x = my_function()

# the program starts from here
main()

This is good, but problem is, if you import the script from another script (from module import *), the main() function gets executed, but you may not want to do this. You want to call the main() function only when this script is exclusively executed. And you can do this using __name__ == "__main__".

import module

def my_function():
   # code here

def main():
   x = my_function()

# the program starts from here
if __name__ == "__main__":
   main()

Thus you can make your script to make it a reusable script (import from another script) and a standalone script as well.

concatenate two dictionaries

>>> dict_1 = {1: 'a', 2: 'b', 3: 'c'}
>>> dict_2 = {4: 'd', 5: 'e', 6: 'f'}
>>> dict_1
{1: 'a', 2: 'b', 3: 'c'}
>>> dict_2
{4: 'd', 5: 'e', 6: 'f'}
>>> dict_1.update(dict_2)
>>> dict_2
{4: 'd', 5: 'e', 6: 'f'}
>>> dict_1
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f'}
>>>

Retrive tweets using tweepy in Python

import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from tweepy.streaming import StreamListener
from tweepy import Stream
from tweepy.streaming import StreamListener
tweets=[]

#Variables that contains the user credentials to access Twitter API
access_token = "access token
access_token_secret = "access token secret"
consumer_key = "consumer key "
consumer_secret ="consumer secret"

auth=tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)

api=tweepy.API(auth)
public_tweets=api.home_timeline()

for tweets in public_tweets:
    print tweets.text.encode('utf-8', 'ignore')

Matrix addition in Python


3 * 3 matrix addition

matrix1=[[2]*3] * 3
matrix2=[[10] * 3] * 3
matrix3=[[0] * 3] * 3
print matrix1
print matrix2

for i in range(3):
    for j in range(3):
        matrix3[i][j]=matrix1[i][j] + matrix2[i][j]
print matrix3