Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
81 views

Programs Py

The document contains 10 programming questions related to Python strings and lists. It provides sample code to: 1) Summarize strings and lists in various ways like counting characters, reversing strings/words, merging strings, and sorting lists. 2) Manipulate strings by accessing characters, finding substrings, and removing duplicates. 3) Traverse lists using for and while loops and perform operations like filtering even/odd numbers. 4) Use list comprehensions to transform lists in various ways.

Uploaded by

manish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

Programs Py

The document contains 10 programming questions related to Python strings and lists. It provides sample code to: 1) Summarize strings and lists in various ways like counting characters, reversing strings/words, merging strings, and sorting lists. 2) Manipulate strings by accessing characters, finding substrings, and removing duplicates. 3) Traverse lists using for and while loops and perform operations like filtering even/odd numbers. 4) Use list comprehensions to transform lists in various ways.

Uploaded by

manish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

#Q.

Write a program to dispaly *'s in Right angled triangled form


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

n = int(input("Enter number of rows:"))


for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()

#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

=========================================

Counting substring in the given String:

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)
======================================

Q2. Program to reverse order of words.


1) input: Learning Python is very Easy
2) output: Easy Very is Python Learning
3)
4) s=input("Enter Some String:")
5) l=s.split()
6) l1=[]
7) i=len(l)-1
8) while i>=0:
9) l1.append(l[i])
10) i=i-1
11) output=' '.join(l1)
12) print(output)
Output:
Enter Some String:Learning Python is very easy!!
easy!!! very is Python Learning

=====================

Q3. Program to reverse internal content of each word.


input: Durga Software Solutions
output:agruD erawtfoS snoituloS
1) s=input("Enter Some String:")
2) l=s.split()
3) l1=[]
4) i=0
5) while i<len(l):
6) l1.append(l[i][::-1])
7) i=i+1
8) output=' '.join(l1)
9) print(output)

==============================

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

1) s1=input("Enter First String:")


2) s2=input("Enter Second String:")
3) output=''
4) i,j=0,0
5) while i<len(s1) or j<len(s2):
6) if i<len(s1):
7) output=output+s1[i]
8) i+=1
9) if j<len(s2):
10) output=output+s2[j]
11) j+=1
12) print(output)

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:

1. By using while loop:


1) n=[0,1,2,3,4,5,6,7,8,9,10]
2) i=0
3) while i<len(n):
4) print(n[i])
5) i=i+1

----------
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) s=[ x*x for x in range(1,11)]


2) print(s)
3) v=[2**x for x in range(1,6)]
4) print(v)
5) m=[x for x in s if x%2==0]
6) print(m)
7)
8) Output
9) D:\Python_classes>py test.py
10) [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
11) [2, 4, 8, 16, 32]
12) [4, 16, 36, 64, 100]

==========================
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

13) Enter the word to search for vowels: durgasoftwaresolutions


14) ['u', 'a', 'o', 'e', 'i']
15) The number of different vowels present in durgasoftwaresolutions is 5

================================

Q.Write a program to eliminate duplicates present in the list?


Approach-1:
1. l=eval(input("Enter List of values: "))
2. s=set(l)
3. print(s)
4.
5. Output
6. D:\Python_classes>py test.py
7. Enter List of values: [10,20,30,10,20,40]
8. {40, 10, 20, 30}

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

Q. Lambda function to find sum of 2 given numbers


1) s=lambda a,b:a+b
2) print("The Sum of 10,20 is:",s(10,20))
3) print("The Sum of 100,200 is:",s(100,200))
4)
5) Output
6) The Sum of 10,20 is: 30
7) The Sum of 100,200 is: 300

Q. Lambda Function to find biggest of given values.


1) s=lambda a,b:a if a>b else b
2) print("The Biggest of 10,20 is:",s(10,20))
3) print("The Biggest of 100,200 is:",s(100,200))
4)
5) Output
6) The Biggest of 10,20 is: 20
7) The Biggest of 100,200 is: 200
=================================
Q. Program to filter only even numbers from the list by using filter()
function?

without lambda Function:


1) def isEven(x):
2) if x%2==0:
3) return True
4) else:
5) return False
6) l=[0,5,10,15,20,25,30]
7) l1=list(filter(isEven,l))
8) print(l1) #[0,10,20,30]

with lambda Function:


1) l=[0,5,10,15,20,25,30]
2) l1=list(filter(lambda x:x%2==0,l))
3) print(l1) #[0,10,20,30]
4) l2=list(filter(lambda x:x%2!=0,l))
5) print(l2) #[5,15,25]
---
Eg: Without lambda
1) l=[1,2,3,4,5]
2) def doubleIt(x):
3) return 2*x
4) l1=list(map(doubleIt,l))
5) print(l1) #[2, 4, 6, 8, 10]
with lambda
1) l=[1,2,3,4,5]
2) l1=list(map(lambda x:2*x,l))
3) print(l1) #[2, 4, 6, 8, 10]

Eg 2: To find square of given numbers


1. l=[1,2,3,4,5]
2. l1=list(map(lambda x:x*x,l))
3. print(l1) #[1, 4, 9, 16, 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()

Eg 1: To read total data from the file


1) f=open("abc.txt",'r')
2) data=f.read()
3) print(data)
4) f.close()
5)
6) Output
7) sunny
8) bunny
9) chinny
10) vinny
Eg 2: To read only first 10 characters:
1) f=open("abc.txt",'r')
2) data=f.read(10)
3) print(data)
4) f.close()

Eg 3: To read data line by line:


1) f=open("abc.txt",'r')
2) line1=f.readline()
3) print(line1,end='')
4) line2=f.readline()
5) print(line2,end='')
6) line3=f.readline()
7) print(line3,end='')
8) f.close()
9)
10) Output
11) sunny
12) bunny
13) chinny
Eg 4: To read all lines into list:
1) f=open("abc.txt",'r')
2) lines=f.readlines()
3) for line in lines:
4) print(line,end='')
5) f.close()
6)
7) Output
8) sunny
9) bunny
10) chinny
11) vinny
Eg 5:
1) f=open("abc.txt","r")
2) print(f.read(3))
3) print(f.readline())
4) print(f.read(4))
5) print("Remaining data")
6) print(f.read())
====================================
Q. Program to print the number of lines,words and characters present in the
given file?
1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("File exists:",fname)
5) f=open(fname,"r")
6) else:
7) print("File does not exist:",fname)
8) sys.exit(0)
9) lcount=wcount=ccount=0
10) for line in f:
11) lcount=lcount+1
12) ccount=ccount+len(line)
13) words=line.split()
14) wcount=wcount+len(words)
15) print("The number of Lines:",lcount)
16) print("The number of Words:",wcount)
17) print("The number of Characters:",ccount)
18)
19) Output
20) D:\Python_classes>py test.py
21) Enter File Name: durga.txt
22) File does not exist: durga.txt
23)
24) D:\Python_classes>py test.py
25) Enter File Name: abc.txt
26) File exists: abc.txt
27) The number of Lines: 6
28) The number of Words: 24
29) The number of Characters: 149
abc.txt:
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
====================================================
Writing data to csv file:
1) import csv
2) with open("emp.csv","w",newline='') as f:
3) w=csv.writer(f) # returns csv writer object
4) w.writerow(["ENO","ENAME","ESAL","EADDR"])
5) n=int(input("Enter Number of Employees:"))
6) for i in range(n):
7) eno=input("Enter Employee No:")
8) ename=input("Enter Employee Name:")
9) esal=input("Enter Employee Salary:")
10) eaddr=input("Enter Employee Address:")
11) w.writerow([eno,ename,esal,eaddr])
12) print("Total Employees data written to csv file successfully")
Note: Observe the difference with newline attribute and without
with open("emp.csv","w",newline='') as f:
with open("emp.csv","w") as f:

Reading Data from csv file:


1) import csv
2) f=open("emp.csv",'r')
3) r=csv.reader(f) #returns csv reader object
4) data=list(r)
5) #print(data)
6) for line in data:
7) for word in line:
8) print(word,"\t",end='')
9) print()
10)
11) Output
12) D:\Python_classes>py test.py
13) ENO ENAME ESAL EADDR
14) 100 Durga 1000 Hyd
15) 200 Sachin 2000 Mumbai
16) 300 Dhoni 3000 Ranchi
=========================================

Q. Write a Python Program to check whether the given mail id is


valid gmail id or not?
1) import re
2) s=input("Enter Mail id:")
3) m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s)
4) if m!=None:
5) print("Valid Mail Id");
6) else:
7) print("Invalid Mail id")
Output:
D:\python_classes>py test.py
Enter Mail id:durgatoc@gmail.com
Valid Mail Id

You might also like