Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Friday, January 20, 2017

Python programs

1. Primefactor

#!/usr/bin/python

def primefactor_small(n):
        if n > 0:
                p = 2
                while n >= p*p:
                        if n%p == 0:
                                n = n / p
                                print str(p) + "*"
                        else:
                                p = p+1

                return n


if __name__=='__main__':
        import sys
        print primefactor_small(int(sys.argv[1]))

Reference:

 

Execution



2. Fibnoacci series with only even numbers

#!/usr/bin/python

def Fibonacci(num):
        ''' Fibonacci series '''
        if num < 1:
                print "No fibonacci"
        else:
                fiblist = [1,2]
                fibtotal = 3
                sum=0
                #for i in range(2, num):
                while fiblist[-1] < 4000000:
                        fiblist.append(fiblist[-1] + fiblist[-2])
                        fibtotal+=fiblist[-1]
                        if fiblist[-1] > 4000000:
                                fiblist.pop(-1)
                                for i in range(0, len(fiblist)):
                                        if fiblist[i] % 2 == 0:
                                                sum+=fiblist[i]
                                return fiblist, sum,fibtotal
                        else:
                                pass

        return fiblist, sum,fibtotal


if __name__=='__main__':
        import sys
        print Fibonacci(int(sys.argv[1])


Execution:

 vallikkv@vallikkv:~/My Programs/Python/Problem_Solving$ python 2_fibaonnci_even.py 100
([1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578], 4613732, 14930350)


3. Write a program where a there are multiple users logging into the system or file and I want to know the login Occurrences of the each user . Note : The file is separated by the commas. ex: User1 , User2, user1 , user3.........


ef conusers():
        inp = []
        oup = []
        Sum = {}

        ''' Reading file contents and assign to a list'''
        with open('file.csv') as f:
                lines = f.read().splitlines()


        '''Converting all the names in lowercase Split the line contents using comma '''
        inp = [x.lower() for x in lines]
        for i in range(len(inp)):
                oup =  inp[i].split(",")
                for j in range(len(oup)):
                        if oup[j] not in Sum:
                                Sum[oup[j]] = 1
                        else:
                                Sum[oup[j]] += 1


        return Sum


if __name__=='__main__':
        print conusers()


4. Write a program to remove duplicates numbers from the list and display the duplicates ?

def duplicate(input_list):
        a = input_list
        b= [ ]
        for i in range(len(a)):
                if a[i] not in b:
                        b.append(a[i])
        return b


if __name__=='__main__':
        print duplicate([1,2,3,4,5,4,3,2,'Hello','World','Hello'])






Saturday, January 2, 2016

Python File handling

Python scripting:  Search and replace a string in file.

def Main():
    with open("E:\Softwares\Sample.txt") as f:
        for x, line in enumerate(f):
            if "Valli" in line:
                print line.replace("Valli", "Nayagam", -1),


if __name__ == "__main__":
    Main()

Monday, October 26, 2015

Python requests and grab values from json response

__author__ = 'valli_000'

import requests

r = requests.get('http://api.fixer.io/latest?base=USD')
data = r.json()
dict = data['rates']
for key,value in dict.iteritems():
    print "US Dollar Conversion of " + str(key) + " is " + str(value)

Wednesday, October 14, 2015

Sikuli: check multiple of the same/duplicate images and choose the image to perform action

def by_y(match):

   return match.y


icons = findAll("Capture.PNG")



# sort the icons by their y coordinates and put them into a new variable sorted_icons

sorted_icons = sorted(icons, key=by_y)

# another shorter version is using lambda.

print sorted_icons[3]


# Iterate the images and hover it - To confirm

for icon in list(sorted_icons)[:2]:

    hover(icon)


#Click the 4th image from the list.

click(list(sorted_icons)[4])

Wednesday, June 24, 2015

Sikuli + Robotframework + jybot - Execution with screenshot

Sample code:

Created on Jun 24, 2015

@author: vallikkv @ Vallinayagam.K
'''

from robot.api import *
import org.sikuli.basics.SikuliXforJython
from sikuli import *
from Screenshot import *

##Screenshot.py is copied and available in the location "C:\Python27\Lib\site-packages", or declare ##the path where screenshot.py is located.


class Notepad(object):
    ROBOT_CONTINUE_ON_FAILURE = True
    myImagePath = "C:\\sikuli\\Tests.sikuli\Notepad"
    addImagePath(myImagePath)

    def __init__(self):
        self.screen = Screenshot()

    def click_window(self):
        try:
            find("WindowsIcon.PNG")
            click("WindowsIcon.PNG")
        except Exception:
            print "Error in the click window"

    def Type_in_run_and_enter(self):
        try:
            wait("Runwindow.PNG", 5)
            type("notepad.exed"+ Key.ENTER)
        except Exception:
            print "Problem in second step"

    def verify_result(self):
        if not exists("Notepad.PNG"):
            self.screen.take_screenshot()
            raise AssertionError("Error, Failed")
        else:
            pass



Command used to execuet - jython C:\Python27\Lib\site-packages\robot\run.py C:\sikuli\Tests.sikuli\Notepad\Robot.txt


It will embeed screenshots when failed, I've used only for the verify_result method, It should be included for all the methods.

Thursday, June 18, 2015

How to install jython in windows?

How to install jython in windows?

1. Download jython installer jar file from http://www.jython.org/downloads.html

          jython-installer-2.5.3.jar

2. Open command prompt and go to that downloaded location and execute

         java -jar jython-installer-2.5.3.jar

3. It will open a installer window, follow the instructions and install it.

4. Now open a  new command prompt and type "jython" and check it opens the interpreter window.


Note: To set path in environment variable, use path where the jython folder is available, in my case it's "C:\jython2.5.3"