Friday, July 31, 2015

Python Program to Add digits of a given number



number=input("Enter a number :)
sum=0

while number > 0 :
 rem=number % 10
 sum =sum + rem
 number=number /10

print sum

Wednesday, July 15, 2015

Program to remove duplicate elements from list


list=[1,2,3,4,5,1,2,3,4,5,99,99]
newlist=[]

j=0
def removeduplicate(list):
    for item in list:
        if item not in newlist:
            newlist.append(item)
          
removeduplicate(list)
print newlist

Friday, July 10, 2015

Program to create separate even and odd numbers from a list



num_list = [1,21,53,84,50,66,7,38,9]


  odd=[]
 even=[]
 for i in num_list:

 if i%2==0:
    even.append(i)
 else 
    odd.append(i)

print odd
print even

Wednesday, July 8, 2015

Python program to Copy a line containing a word to other file

with open("test.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "Python" in l]
     with open("out.txt", "w") as f1:

        f1.writelines(lines)

File handlign in python



Reading ,Writing to a file in Python

fo = open("test.txt","w")
str1="This is a Test file written from Python Program"
fo.write(str1)
fo.close()
fo = open("test.txt","r")
str=fo.read(100)
print str
fo.close

Print the sum of digits of numbers starting from 1 to 100 (inclusive of both)



print sum(range(1,101))


Create a new list that converts the following list of number strings to a list of numbers.
num_strings = ['1','21','53','84','50','66','7','38','9']

[int(i) for i in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]

Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word.



s = ‘aaa bbb ccc ddd eee’
''.join(s.split())
Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word. for example
{‘one’:2, ‘two’:2, ‘three’:2}
Ans:
 def dic(words):
  a = {}
  for i in words:
    try:
      a[i] += 1
    except KeyError:
      a[i] = 1   
  return a

Python program to check if the String is Palindrome



s = 'abc'
revs = s[::-1]
print s

if cmp(s,revs):
          print "Palindrome"
else:
          print "Not a Plaindrome"

Python Program to reverse a string without using built-in functions

def reverse(text):
     count=1
     mylist=[]
     for i in range(0,len(text)):
          mylist.append(text[len(text) - count])
          count=count +1
       return mylist

if__name__=="__main__":
      print reverse('parag')

Program to reverse a string in python

s = 'abc'
s = s[::-1]
print s

python program to compare two strings



a = raw_input('Please enter the first string to compare:')
b = raw_input('Please enter the second string to compare: ')

count = 0
if len(a) == len(b):
    while count < len(a):
        if a[count] != b[count]:         
            print ('Strings don\'t match! ')
            break
        else:                             
            count = count + 1
else:
    print "Strings are not of equal length"

Program Find length of String



strlen = 0
myString='This is a test string'
for c in myString:
  strlen += 1

print strlen

Count number of letter occurence


Solution 1:
list1=[1,2,1,3]
count={}

for item in list1 :
 print item
 if item not in count: #check if item is in list
  count[item]=0 #if no then set item key value 
  print count[item]
 count[item]+=1 #yes increment  
 print count[item]
print count 

Python: map of sequence



def cube(x): return x*x*x

res=map(cube, range(1, 11))

print res
#! python

# reduce(func, sequence)" returns a single value constructed by
# calling the binary function func on the first two items of the sequence, 
# then on the result and the next item, and so on

def add(x,y): return x+y

r=reduce(add, range(1, 11))
print r # 55

List comprehensions :


  provide a concise way to create lists.

  squares = []
  for x in range(10):
  squares.append(x**2)
  squares
  [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

  Delete element from list

 a = [-1, 1, 66.25, 333, 333, 1234.5]
 del a[0]

Using Lists as Queues

queue = ["Eric", "John", "Michael"] queue.append("Terry") # Terry arrives queue.append("Graham") # Graham arrives print queue s=queue.pop(0) print s s=queue.pop(0) print s print queue [deleting elements from list] a = [-1, 1, 66.6, 333, 333, 1234.5] del a[0] print a del a[2:4] print a

Program to Merge and Sort Elements of 2 different list


Python Program to Read an list and Search for an Element

list=[1,2,3,4,5]
print "Enter element to find"
num=raw_input("Enter number")

for item in list:
    if item == int(num):
        print "Element found"
        break
    else:
        print "Element not found"
        break

Program to Sort Names in an Alphabetical Order


Program to Split an Array from Specified Position & Add First Part to the End


Program to Delete the Specified Integer from an list


Program to Find the Second Largest & Smallest Elements in an list


python program to Sort a list in ascending order

with inbuilt functions :

list1=[1,2,3]
list1.sort()

without inbuilt functions :

def sortlist(list):
    for i in range(len(list)):
        for j in range(len(list) - 1):
            if list[j] < list[j+1]:
                t=list[j]
                list[j]=list[j+1]
                list[j+1]=t
            

list1=[2,12,1,21,2,12,1,2]
sortlist(list1)
print list1 

Program to Sort the List in an Ascending list

with inbuilt functions :

list1=[1,2,3]
list1.sort()

without inbuilt functions :

def sortlist(list):
    for i in range(len(list)):
        for j in range(len(list) - 1):
            if list[j] > list[j+1]:
                t=list[j]
                list[j]=list[j+1]
                list[j+1]=t
           

list1=[2,12,1,21,2,12,1,2]
sortlist(list1)
print list1
        

Program to Cyclically Permute the Elements of an list


Program to Insert an Element in a Specified Position in a given list


Program to Put Even & Odd Elements of an Array in 2 Separate list


Program to Calculate the Sum of the Array Elements using list


Program to Find the Largest Two Numbers in a given list


Program to Calculate Sum & Average of an list


[Using Lists as Stacks]



#! python
stack = [3, 4, 5]
stack.append(6)
stack.append(7)
print stack

x=stack.pop()
print "popped ",x
print stack

x=stack.pop()
print "popped ",x
x=stack.pop()
print "popped ",x
print stack

Lists in Python


a = [66.6, 333, 333, 1, 1234.5] 
print a.count(333)
a.count(66.6)
a.count('x') 
a.insert(2, -1) 
print a a.append(333) 
print a 
print a.index(333) 
a.remove(333) 
print a 
a.reverse() 
print a a.sort() 
print a  
print a 

Max number in list



def minmax1 (x):
    # this function fails if the list length is 0
    minimum = maximum = x[0]
    for i in x[1:]:
        if i < minimum:
            minimum = i
        else:
             if > maximum: 
             maximum = i

    return (minimum,maximum)

Prime Number



def is_prime(a):
    x = True
    for i in range(2, a):
       if a%i == 0:
           x = False
           break # ends the for loop
       # no else block because it does nothing ...


    if x:
        print "prime"
    else:
        print "not prime"

[Fibonacci series]



n=input("Which number fibonacci upto")
first=0
second=1
i=0

while i <= n:
 nextno =first + second
 first=second
 second=nextno
 i=i+1
 print nextno

[Reverse number]



number=input("Enter a")
reverse =0
while number >0 :
 reverse=reverse * 10
 reverse = reverse + number % 10
 number=number / 10
print "Reversed Number"
print reverse

Swap using 2 variables



a=input("Enter a")
b=input("Enter b")

a=a+b
b=a-b
a=a-b


print a
print b

Swap using 3 variables



a=input("Enter a")
b=input("Enter b")
c=a
a=b
b=c
print a
print b

Addition of n numbers



numbers=[]
sum=0

print "How many inputs do you want"
n = input()

for i in range (0,n):
 print "Enter number"
 a=input()
 numbers.append(a)

 sum = sum + a

Program to find Factorial of a number in python




number=input("Enter a character")
fact=1
c=1

while  c <= number:
 fact = fact * c
 c=c + 1
 print fact