Python mid 2

Table of contents

No heading

No headings in the article.

Programs

21.Write a python program that generates a set of prime numbers and another set of odd numbers. Demonstrate the result of union, intersection, difference and symmetric difference operations on these sets.
CODE:
n=int(input("Enter a number: ")) primeset=set() oddset=set() for i in range(2,n+1):
j=2 c=0 while j<i:
if i%j==0:
c=c+1
j=j+1
if c==0: primeset.add(i)
print("\nSet of Prime nos. is: ",primeset) for i in range(n+1): if i%2!=0: oddset.add(i)
print("\nSet of Odd nos. is: ",oddset) print("\nUnion is:",oddset.union(primeset)) print("\nIntersection is:",oddset.intersection(primeset)) print("\nDifference is:",oddset.difference(primeset))
print("\nSymmetric Difference is:",oddset.symmetric_difference(primeset))
OUTPUT:
Enter a number: 13
Set of Prime nos. is:  {2, 3, 5, 7, 11, 13}
Set of Odd nos. is:  {1, 3, 5, 7, 9, 11, 13}
Union is: {1, 2, 3, 5, 7, 9, 11, 13}
Intersection is: {3, 5, 7, 11, 13}
Difference is: {1, 9}
Symmetric Difference is: {1, 2, 9}
22. Write a python program that creates a dictionary of radius of circle and its circumference.
CODE:
d={} print("\nEnter a radius or press -1 to exit") while(True): r=float(input("\nEnter the radius of the circle: ")) if r==-1:
break
d[r]=2*3.14*r
print(d)
OUTPUT:
Enter a radius or press -1 to exit
Enter the radius of the circle: 1
Enter the radius of the circle: 2
Enter the radius of the circle: -1
{1.0: 6.28, 2.0: 12.56}
23. Program to read students details like sno sname and 3 sub marks then calculate tot and write them into result.txt file and also read from file result.txt
CODE:
data = open('result.txt','w') data.write("Sno\tName\tm1\tm2\tm3\tTotal\n") print("Enter student details\n") while True: sno=input("Enter the Student ID: ") name=input("Enter the student Name: ") m1=input("Enter m1 marks:") m2=input("Enter m2 marks:") m3=input("Enter m3 marks:") total=str(float(m1)+float(m2)+float(m3)) data.write(sno+'\t'+name+'\t'+m1+'\t'+m2+'\t'+m3+'\t'+total+'\n') ask = input("Enter next student info, y or n?") if ask == "n":
break
data.close() display=open('result.txt','r') '''Reading the whole file print(f.read())'''
#reading line by line for x in display: print(x)
display.close
OUTPUT:
Enter student details
Enter the Student ID: 1
Enter the student Name: Ram
Enter m1 marks:1
Enter m2 marks:2
Enter m3 marks:3
Enter next student info, y or n?y
Enter the Student ID: 2
Enter the student Name: Sam
Enter m1 marks:1
Enter m2 marks:2
Enter m3 marks:3
Enter next student info, y or n?n
Sno    Name    m1    m2    m3    Total
1    Ram 1    2    3    6.0    
2    Sam 1    2    3    6.0    
24. Program to copy the contents of one file into another file
CODE:
sf = open("original.txt","w") content = input("Enter a sentence: ") sf.write(content) sf.close()
data_sf = open("original.txt", "r") store = data_sf.readline() data_sf.close()
df = open("duplicate.txt", "w") for s in store:
df.write(s)
df.close() print("\nFile Copied Successfully!")
OUTPUT:
Enter a sentence: Good Morning, Welcome to CBIT
File Copied Successfully!
25.Python Program to perform seeking file positions in Binary Files
CODE:
rs=open("names.dat","wb") content=input("Enter content in binary file: ") rs.write(content.encode("utf-8")) rs.close()
rs=open("names.dat","rb") pos=int(input("Enter position to seek from the binary file: ")) rs.seek(pos-1) data=rs.read(1) print(data)
OUTPUT:
Enter content in binary file: lenovo
Enter position to seek from the binary file: 2 b'e'
26. Create a DataFrame with 3 subject marks of Random Numbers generated in the range of 40 to100 with column names as Marks1, Marks2 and Marks3 for given N number of Students and display along with description of each column using describe().
CODE:
import numpy as np import pandas as pd n=int(input("Enter number of students: ")) array=np.random.randint(40,101,size=(n,3)) heading = ["Marks1","Marks2","Marks3"]
df= pd.DataFrame(array,columns=heading) print(df) print(df.describe())
OUTPUT:
Enter number of students: 5 Marks1  Marks2  Marks3
0    93      91      69
1    94      73      78
2    83      96      77
3    78      99      59
4    54      82      81
Marks1    Marks2     Marks3 count   5.000000   5.00000   5.000000 mean   80.400000  88.20000  72.800000 std    16.226522  10.66302   8.899438 min    54.000000  73.00000  59.000000 25%    78.000000  82.00000  69.000000
50%    83.000000  91.00000  77.000000 75%    93.000000  96.00000  78.000000 max    94.000000  99.00000  81.000000
27. Write a Python program to feature scale using MinMax Scaler
CODE:
import pandas as pd from sklearn import preprocessing as pre data = pd.read_csv("Age-salary.csv")
print("Age and Salary before scaling: ") df_age_salary = pd.DataFrame(data.iloc[:,[2,3]]) print(df_age_salary.head()) minmax=pre.MinMaxScaler().fit_transform(df_age_salary) df_scaled = pd.DataFrame(minmax,columns=["Age","Salary"]) print("Age and Salary after scaling: ") print(df_scaled.head())
OUTPUT:
Age and Salary before scaling:
Age  Salary
0    21   21000
1    37   22000
2    28   45000
3    29   59000
4    21   78000
Age and Salary after scaling:
Age    Salary
0    0.024390  0.029630
1    0.414634  0.037037
2    0.195122  0.2074073  0.219512  0.311111
4  0.024390  0.451852
28. Write a Python program to feature scale using Standard Scaler
CODE:
import pandas as pd from sklearn import preprocessing as pre data=pd.read_csv("Age-salary.csv")
print("Age and Salary before Scaling: ") df_scale=pd.DataFrame(data.iloc[:,[2,3]]) print(df_scale.head(3)) standard = pre.StandardScaler().fit_transform(df_scale) df_scaled=pd.DataFrame(standard,columns=["Age","Salary"]) print("Age and Salary after Scaling: ") print(df_scaled.head(3))
OUTPUT:
Age and Salary before Scaling:
Age  Salary
0    21   21000
1    37   22000
2    28   45000
Age and Salary after Scaling:
Age    Salary
0    -1.523710 -1.344798
1    0.628043 -1.312346
2    -0.582318 -0.565957
29. Write a Python program to feature scale using Normalizer
CODE:
import pandas as pd from sklearn import preprocessing as pre data=pd.read_csv("Age-salary.csv")
print("Age and Salary before Scaling: ") df_scale=pd.DataFrame(data.iloc[:,[2,3]]) print(df_scale.head(3)) standard = pre.Normalizer().fit_transform(df_scale)
df_scaled=pd.DataFrame(standard,columns=["Age","Salary"]) print("Age and Salary after Scaling: ") print(df_scaled.head(3))
OUTPUT:
Age and Salary before Scaling:
Age  Salary
0    21   21000
1    37   22000
2    28   45000
Age and Salary after Scaling:
Age    Salary
0    0.001000  1.000000
1    0.001682  0.999999
2    0.000622  1.000000
30. Write a Python program to feature scale using Binarizer
CODE:
import pandas as pd from sklearn import preprocessing as pre data=pd.read_csv("Age-salary.csv")
print("Age and Salary before Scaling: ") df_scale=pd.DataFrame(data.iloc[:,[2,3]]) print(df_scale.head(3)) standard = pre.Binarizer(threshold=25).fit_transform(df_scale)
df_scaled=pd.DataFrame(standard,columns=["Age","Salary"]) print("Age and Salary after Scaling: ") print(df_scaled.head(3))
OUTPUT:
Age and Salary before Scaling:
Age  Salary
0    21   21000
1    37   22000
2    28   45000
Age and Salary after Scaling: Age  Salary
0    0       1
1    1       1
2    1       1
31. Write a Python program to plot the data using line and scatter plot along with labels and title.
CODE:
import pandas as pd from matplotlib import pyplot as plt
data=pd.read_csv("Age-salary.csv") df=pd.DataFrame(data)
#age and salary scatter plot x=df.Age y=df.Salary plt.scatter(x,y) plt.title("age and salary scatter plot") plt.xlabel("Age") plt.ylabel("Salary") plt.show()
#line graph x=df.Age y=x.value_counts().sort_index() plt.plot(y) plt.title("Age v/s Age Frequency") plt.xlabel("Age") plt.ylabel("Age_frequency") plt.show()
OUTPUT:

32. Write a Python program to plot the data using bar graph along with labels and title.
CODE:
import pandas as pd from matplotlib import pyplot as plt
data=pd.read_csv("X_train.csv") df=pd.DataFrame(data) gender_df=df.Gender.value_counts()
gender_df.plot(kind = 'bar') plt.title("Male vs Female") plt.xlabel("Gender") plt.ylabel("Frequency") plt.show()
OUTPUT:

33.Program to display the given string in opposite case without using swapcase() method
CODE:
s=input("Enter a string: ") swapecase=" " for i in s:
if ord(i)<90:
swapecase+=i.lower()
else: swapecase+=i.upper()
print(swapecase)
OUTPUT:
Enter a string: WELcome Home welCOME hOME
34.Python Program that counts the occurrences of a char in a given string without using count() method
CODE:
s=input("Enter a string: ") d={} for i in s:
if i not in d: d[i]=1
else:
d[i]=d[i]+1
for i in d:
print("Count of",i,"is",d[i])
OUTPUT:
Enter a string: banana
Count of b is 1
Count of a is 3
Count of n is 2