0% found this document useful (0 votes)
4 views14 pages

Python

The document contains various Python code snippets demonstrating basic programming concepts such as input handling, loops, conditionals, list operations, and string manipulations. It also includes a project that utilizes machine learning to detect islanding events in voltage signals using wavelet transforms and a RandomForestClassifier. Key features of Python, its classification as a programming language, and PEP 8 guidelines for code formatting are also discussed.

Uploaded by

ABC abcd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views14 pages

Python

The document contains various Python code snippets demonstrating basic programming concepts such as input handling, loops, conditionals, list operations, and string manipulations. It also includes a project that utilizes machine learning to detect islanding events in voltage signals using wavelet transforms and a RandomForestClassifier. Key features of Python, its classification as a programming language, and PEP 8 guidelines for code formatting are also discussed.

Uploaded by

ABC abcd
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python

[Link]=int(input(“enter the total no of books:”))

Cost_per book=int(input(“enter the cost:”))

Book_sale=int(input(“enter the selling price:”))

Exp=Book*Cost_per book

Profit=Book*Book_sale

Topr=(profit-exp)-100

Print(Topr)

1. l=int(input(“enter the length:”)


b=int(input(“enter the breadth:”)
rope_len=2(l+b)
carpet_quantity=l*b
print(f”rope_len:{rope_len}m\n carpet _quantity:{carpet _quantity}sqm\n”)

3.num1=int(input(“enter an integer “))

If(num1<0 or num1>100):

Print(“invalid matrix”)

else if(num1>=30 and num1<=70):

print(“b”)

else if(num1>=70 and num1<=100):

print(“a”)

else:

print(“c”)
[Link]=int(input(“enter an interger:”))

if(num=<10 or num>=99):

print(“invalid matric”)

elif( num%10==7 or num/10 ==7):

print(“lucky number”)

elif(num%10 ==4 or num/10 ==4):

print(“lucky number”)

else:

print(“unlucky number”)

[Link]=0

For i in range(2,11,2):

Sum+=i

Print(sum)

6. caps into small

name=”Guru”

string =””

for i in name:

if(ord(i) >= 65 and ord(i) <= 90):

string = string+chr(ord(i)+32)

elif(ord(i) >= 97 and ord(i) <= 122):

string = string+chr(ord(i)-32)

print(string)
while loop

1. i=0
while(i<=10):
print(i)
i+=1

2. reverse integer
i=12345
rev =0
while(i!=0):
temp=i%10
rev=rev*10+temp
i//=10
print(rev)

3. sum until single digit


i=976592
sum=0
if(i>10):
while(i!=0):
temp=i%10
sum=sum+temp
i//=10
i=sum
return i
print(sum)

[Link] a list and find the even numbers


li = []
n= int(input("enter the size of the list:"))
for i in range(0,n):
[Link](int(input("enter the elements:")))
for i in range(0,len(li)):
if(li[i]%2==0):
print(li[i])
[Link] a list and append other string
li = []
n= int(input("enter the size of the list:"))
for i in range(0,n):
[Link](str(input("enter the colours:")))
print(li)
[Link]("green")
print(li)

6. create a list and sum the list data

li = []

n= int(input("enter the size of the list:"))

for i in range(0,n):

[Link](int(input("enter the elements:")))

sum=0

for i in range(0,li[i]):

sum+=li[i]

print(sum)

7. create a string and delete last string

li = []

n= int(input("enter the size of the list:"))

for i in range(0,n):

[Link](str(input("enter the elements:")))

[Link](-1)

print(li)

[Link] avg of the test marks

li = []
n= int(input("enter the size of the list:"))

for i in range(0,n):

[Link](int(input("enter the elements:")))

sum=0

for i in li:

sum+=i

avg=sum/n

print(sum)

print(avg)

[Link] a program to print the list and to replace all the occurance of number 5 with number 10

li = []

n = int(input("enter the size of the list:"))

for i in range(0,n):

[Link](int(input("enter the elements:")))

print(li)

for i in range(0,len(li)):

if(li[i]==5 or li[i]%10==5 or li[i]//10==5):

li[i]=10

print(li)

key features of Python?

 Python is an interpreted language. That means that, unlike languages like C and its variants,
Python does not need to be compiled before it is run.
 Python is dynamically typed, this means that you don’t need to state the types of variables
when you declare them or anything like that. You can do things like x=111 and then x="I'm a
string" without error
 Python finds use in many spheres – web applications, automation, scientific modeling, big data
applications and many more.

What type of language is python? Programming or scripting?

Ans: Python is capable of scripting, but in general sense, it is considered as a general-purpose


programming language.

What is pep 8?

Ans: PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format Python
code for maximum readability.

1. Write a python code to get a string from the user and print it in reverse order.

Ans:

n=str(input("enter the string:"))

rev=n[::-1]

print("reverse:",rev)

2. Write a python code to count the number of characters(incl spaces) in a string

Ans:

n=str(input("enter the string:"))

count=0

for char in n:

count+=1

#space_count=[Link](" ")

print(f" string:{count}")

3. Write a python code to check if a string is a palindrome or not.

Ans:
n=str(input("enter the string:"))

original=n

rev=n[::-1]

if(rev==original):

print(f"palindrom:{rev}")

else:

print(f" not a palindrome:{rev}")

4. Write a python code to remove all the vowels from a string

Ans:

a=input()

b=['a','e','i','o','u']

c=a

for i in range(0,len(a)):

if(a[i] in b):

c=[Link](a[i],"")

print(c)

5. Write a python code to find the most occurring character in a string.


6. Write a python code to remove all spaces from in a string (leading and trailing)
7. Write a python code to replace all occurance of a given character in astring with another
character.
8.

2. Write a python to print the string length in single digit number…

string=input("enter the string")

list=list([Link](" "))
length=0

for i in range(0,len(list)):

length+=len(list[i])

sum=0

while(length!=0):

temp=length%10

sum+=temp

length//=10

print(sum)

6. write a python program to calculate the string weight and remove the vowels

a=input("enter string:")

b=['a','e','i','o','u']

c=a

for i in range(0,len(a)):

if(a[i] in b):

c=[Link](" ","")

c=[Link](a[i],"")

c=[Link]()

print(c)

total_weight=0

for i in c:

total_weight=total_weight+(ord(i)-96)

print(total_weight)

1. Write a python code to capitalize the first letter of the [Link]

n=str(input("enter the string:"))


first_letter = n[0].upper()+n[1:]

print(first_letter)

total_weight=0

for i in first_letter:

total_weight=total_weight+(ord(i)-96)

print(total_weight)

sum=0

while(total_weight!=0):

temp=total_weight%10

sum+=temp

total_weight//=10

print(sum)

b={'a','e','i','o','u'}

c=n

for char in first_letter:

if(char in b):

c=[Link](char,"")

print([Link]())

QUS: replace the value of ? in 0 or 1..in binary form…

n="1?0?1"

result=['']

for char in n:

temp_result=[]

for binary_string in result:


if(char=='?'):

temp_result.append(binary_string+'0')

temp_result.append(binary_string+'1')

else:

temp_result.append(binary_string+char)

result=temp_result

for binary_string in result:

print(binary_string)

QUESTUION:write a python code to print the sum of give arr elememts is match to the given sum is
x=16.

Ans: arr=[1,4,45,6,10,8]

x=16

seen = set()

result = False

for num in arr:

c = x-num

if c in seen:

result = True

break

[Link](num)

if result:

print("true")

else:

print("false")
project

import numpy as np

import pandas as pd

import pywt

import [Link] as plt

from sklearn.model_selection import train_test_split

from [Link] import RandomForestClassifier

from [Link] import accuracy_score, classification_report

# Generate synthetic voltage data

[Link](42)

n_samples = 1000

time = [Link](0, 1, n_samples)

# Generate non-islanding voltage signal (normal operation)

normal_voltage = [Link](2 * [Link] * 50 * time) + 0.5 * [Link](size=n_samples)

# Generate islanding voltage signal (abnormal operation)

islanding_voltage = [Link](2 * [Link] * 50 * time) + 0.8 * [Link](size=n_samples)

# Create labels (0 for normal, 1 for islanding)

labels = [Link]([0] * (n_samples // 2) + [1] * (n_samples // 2))

# Combine the data

data = [Link]([normal_voltage, islanding_voltage])


# Reshape for model input

data = [Link](-1, 1)

# Plot the signals

[Link](figsize=(14, 6))

[Link](time, normal_voltage, label='Normal Voltage')

[Link](time, islanding_voltage, label='Islanding Voltage')

[Link]()

[Link]('Time')

[Link]('Voltage')

[Link]('Synthetic Voltage Signals')

[Link]()

# Function to perform wavelet transform and extract features

def extract_wavelet_features(signal, wavelet='db4', level=4):

coeffs = [Link](signal, wavelet, level=level)

features = []

for coeff in coeffs:

[Link](coeff)

return features

# Extract features for each sample

features = []

for i in range(n_samples):
signal = data[i]

wavelet_features = extract_wavelet_features(signal)

[Link](wavelet_features)

features = [Link](features)

# Split data into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.3, random_state=42)

# Train a RandomForestClassifier

clf = RandomForestClassifier(n_estimators=100, random_state=42)

[Link](X_train, y_train)

# Make predictions

y_pred = [Link](X_test)

# Evaluate the model

accuracy = accuracy_score(y_test, y_pred)

print(f'Accuracy: {accuracy * 100:.2f}%')

print(classification_report(y_test, y_pred))

# Function to simulate breaker operation

def open_breaker():

print("Breaker opened: Islanding event detected!")


# Detect islanding events and open breakers automatically

for i, prediction in enumerate(y_pred):

if prediction == 1: # Islanding event detected

open_breaker()

You might also like