Programs Py
Programs Py
#Alternative way:
n = int(input("Enter number of rows:"))
for i in range(1,n+1):
print("* " * i)
===========================
Q. Write a program to display *'s in pyramid style(also known as equivalent triangle)
1) *
2) * *
3) * * *
4) * * * *
5) * * * * *
6) * * * * * *
7) * * * * * * *
8)
9) n = int(input("Enter number of rows:"))
10) for i in range(1,n+1):
11) print(" " * (n-i),end="")
12) print("* "*i)
======================================
# To print odd numbers in the range 0 to 9
1) for i in range(10):
2) if i%2==0:
3) continue
4) print(i)
=================================
Q. Write a program to access each character of string in forward and backward
direction
by using while loop?
1) s="Learning Python is very easy !!!"
2) n=len(s)
3) i=0
4) print("Forward direction")
5) while i<n:
6) print(s[i],end=' ')
7) i +=1
8) print("Backward direction")
9) i=-1
10) while i>=-n:
11) print(s[i],end=' ')
12) i=i-1
Alternative ways:
1) s="Learning Python is very easy !!!"
2) print("Forward direction")
3) for i in s:
4) print(i,end=' ')
5)
6) print("Forward direction")
7) for i in s[::]:
8) print(i,end=' ')
9)
10) print("Backward direction")
11) for i in s[::-1]:
12) print(i,end=' ')
======================================
Q. Program to display all positions of substring in a given main string
1) s=input("Enter main string:")
2) subs=input("Enter sub string:")
3) flag=False
4) pos=-1
5) n=len(s)
6) while True:
7) pos=s.find(subs,pos+1,n)
8) if pos==-1:
9) break
10) print("Found at position",pos)
11) flag=True
12) if flag==False:
13) print("Not Found")
Output:
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:bb
Found at position 1
=========================================
1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
========================================
Q1. Write a program to reverse the given String
input: durga
output:agrud
1
st Way:
s=input("Enter Some String:")
print(s[::-1])
2
nd Way:
s=input("Enter Some String:")
print(''.join(reversed(s)))
3
rd Way:
s=input("Enter Some String:")
i=len(s)-1
target=''
while i>=0:
target=target+s[i]
i=i-1
print(target)
======================================
=====================
==============================
Q4. Write a program to print characters at odd position and even position for the given
String?
1
st Way:
s=input("Enter Some String:")
print("Characters at Even Position:",s[0::2])
print("Characters at Odd Position:",s[1::2])
2
nd Way:
1) s=input("Enter Some String:")
2) i=0
3) print("Characters at Even Position:")
4) while i< len(s):
5) print(s[i],end=',')
6) i=i+2
7) print()
8) print("Characters at Odd Position:")
9) i=1
10) while i< len(s):
11) print(s[i],end=',')
12) i=i+2
=================================================
Q5. Program to merge characters of 2 strings into a single string by taking characters
alternatively.
s1="ravi"
s2="reja"
output: rtaevjia
Output:
Enter First String:durga
Enter Second String:ravisoft
druarvgiasoft
===========================
Q6. Write a program to sort the characters of the string and first alphabet symbols
followed by numeric values
input: B4A1D3
Output: ABD134
1) s=input("Enter Some String:")
2) s1=s2=output=''
3) for x in s:
4) if x.isalpha():
5) s1=s1+x
6) else:
7) s2=s2+x
8) for x in sorted(s1):
9) output=output+x
10) for x in sorted(s2):
11) output=output+x
12) print(output)
===============================
Q7. Write a program for the following requirement
input: a4b3c2
output: aaaabbbcc
1) s=input("Enter Some String:")
2) output=''
3) for x in s:
4) if x.isalpha():
5) output=output+x
6) previous=x
7) else:
8) output=output+previous*(int(x)-1)
9) print(output)
============================
Q8. Write a program to perform the following activity
input: a4k3b2
output:aeknbd
1) s=input("Enter Some String:")
2) output=''
3) for x in s:
4) if x.isalpha():
5) output=output+x
6) previous=x
7) else:
8) output=output+chr(ord(previous)+int(x))
9) print(output)
====================================================
Q9. Write a program to remove duplicate characters from the given input string?
input: ABCDABBCDABBBCCCDDEEEF
output: ABCDEF
1) s=input("Enter Some String:")
2) l=[]
3) for x in s:
4) if x not in l:
5) l.append(x)
6) output=''.join(l)
================================================
Q10. Write a program to find the number of occurrences of each character present in
the
given String?
input: ABCABCABBCDE
output: A-3,B-4,C-3,D-1,E-1
1) s=input("Enter the Some String:")
2) d={}
3) for x in s:
4) if x in d.keys():
5) d[x]=d[x]+1
6) else:
7) d[x]=1
8) for k,v in d.items():
9) print("{} = {} Times".format(k,v))
=====================================================
==================================
Traversing the elements of List:
----------
By using for loop:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) print(n1)
===============================
To display only even numbers:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) for n1 in n:
3) if n1%2==0:
4) print(n1)
=======================
To add all elements to list upto 100 which are divisible by 10
1) list=[]
2) for i in range(101):
3) if i%10==0:
4) list.append(i)
5) print(list)
6)
7)
8) D:\Python_classes>py test.py
9) [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
=============================================
1) n=[20,5,15,10,0]
2) n.sort()
3) print(n) #[0,5,10,15,20]
4)
5) s=["Dog","Banana","Cat","Apple"]
6) s.sort()
7) print(s) #['Apple','Banana','Cat','Dog']
============================================
List Comprehensions:
==========================
1) words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
2) l=[w[0] for w in words]
3) print(l)
4)
5) Output['B', 'N', 'V', 'C']
Eg:
1) num1=[10,20,30,40]
2) num2=[30,40,50,60]
3) num3=[ i for i in num1 if i not in num2]
4) print(num3) [10,20]
5)
6) common elements present in num1 and num2
7) num4=[i for i in num1 if i in num2]
8) print(num4) [30, 40]
Eg:
1) words="the quick brown fox jumps over the lazy dog".split()
2) print(words)
3) l=[[w.upper(),len(w)] for w in words]
4) print(l)
5)
6) Output
7) ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
8) [['THE', 3], ['QUICK', 5], ['BROWN',
=================================================
Q. Write a program to display unique vowels present in the given word?
1) vowels=['a','e','i','o','u']
2) word=input("Enter the word to search for vowels: ")
3) found=[]
4) for letter in word:
5) if letter in vowels:
6) if letter not in found:
7) found.append(letter)
8) print(found)
9) print("The number of different vowels present in",word,"is",len(found))
10)
11)
12) D:\Python_classes>py test.py
================================
Approach-2:
1. l=eval(input("Enter List of values: "))
2. l1=[]
3. for x in l:
4. if x not in l1:
5. l1.append(x)
6. print(l1)
7.
8. Output
9. D:\Python_classes>py test.py
10. Enter List of value [10,20,30,10,20,40]
11. [10, 20, 30, 40]
============================================
Q. Write a program to enter name and percentage marks in a dictionary and
display information on the screen
1) rec={}
2) n=int(input("Enter number of students: "))
3) i=1
4) while i <=n:
5) name=input("Enter Student Name: ")
6) marks=input("Enter % of Marks of Student: ")
7) rec[name]=marks
8) i=i+1
9) print("Name of Student","\t","% of marks")
10) for x in rec:
11) print("\t",x,"\t\t",rec[x])
12)
13) Output
14) D:\Python_classes>py test.py
15) Enter number of students: 3
16) Enter Student Name: durga
17) Enter % of Marks of Student: 60%
18) Enter Student Name: ravi
19) Enter % of Marks of Student: 70%
20) Enter Student Name: shiva
21) Enter % of Marks of Student: 80%
22) Name of Student % of marks
23) durga 60%
24) ravi 70 %
25) shiva 80%
========================
Q. Write a program to take dictionary from the keyboard and print the sum
of values?
1. d=eval(input("Enter dictionary:"))
2. s=sum(d.values())
3. print("Sum= ",s)
4.
5. Output
6. D:\Python_classes>py test.py
7. Enter dictionary:{'A':100,'B':200,'C':300}
8. Sum= 600
Q. Write a program to find number of occurrences of each letter present in
the given string?
1. word=input("Enter any word: ")
2. d={}
3. for x in word:
4. d[x]=d.get(x,0)+1
5. for k,v in d.items():
6. print(k,"occurred ",v," times")
7.
8. Output
9. D:\Python_classes>py test.py
10. Enter any word: mississippi
11. m occurred 1 times
12. i occurred 4 times
13. s occurred 4 times
14. p occurred 2 times
=======================================
Q. Write a program to find number of occurrences of each vowel present in
the given string?
1. word=input("Enter any word: ")
2. vowels={'a','e','i','o','u'}
3. d={}
4. for x in word:
5. if x in vowels:
6. d[x]=d.get(x,0)+1
7. for k,v in sorted(d.items()):
8. print(k,"occurred ",v," times")
9.
10. Output
11. D:\Python_classes>py test.py
12. Enter any word: doganimaldoganimal
13. a occurred 4 times
14. i occurred 2 times
15. o occurred 2 times
==============================
Q. Write a program to accept student name and marks from the keyboard
and creates a dictionary. Also display student marks by taking student name
as input?
1) n=int(input("Enter the number of students: "))
2) d={}
3) for i in range(n):
4) name=input("Enter Student Name: ")
5) marks=input("Enter Student Marks: ")
6) d[name]=marks
7) while True:
8) name=input("Enter Student Name to get Marks: ")
9) marks=d.get(name,-1)
10) if marks== -1:
11) print("Student Not Found")
12) else:
13) print("The Marks of",name,"are",marks)
14) option=input("Do you want to find another student marks[Yes|No]")
15) if option=="No":
16) break
17) print("Thanks for using our application")
18)
19) Output
20) D:\Python_classes>py test.py
21) Enter the number of students: 5
22) Enter Student Name: sunny
23) Enter Student Marks: 90
===========================
Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
1. squares={x:x*x for x in range(1,6)}
2. print(squares)
3. doubles={x:2*x for x in range(1,6)}
4. print(doubles)
5.
6. Output
7. {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
8. {1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
=============================
Q. Write a function to find factorial of given number?
1) def fact(num):
2) result=1
3) while num>=1:
4) result=result*num
5) num=num-1
6) return result
7) for i in range(1,5):
8) print("The Factorial of",i,"is :",fact(i))
9)
10) Output
11) D:\Python_classes>py test.py
12) The Factorial of 1 is : 1
13) The Factorial of 2 is : 2
14) The Factorial of 3 is : 6
15) The Factorial of 4 is : 24
Alternative
1) def factorial(n):
2) if n==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) return result
7) print("Factorial of 4 is :",factorial(4))
8) print("Factorial of 5 is :",factorial(5))
9)
10) Output
11) Factorial of 4 is : 24
12) Factorial of 5 is : 120
=================================
Q. Write a program to create a lambda function to find square of given
number?
1) s=lambda n:n*n
2) print("The Square of 4 is :",s(4))
3) print("The Square of 5 is :",s(5))
4)
5) Output
6) The Square of 4 is : 16
7) The Square of 5 is : 25
========================
File Handling
1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()