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

AS Level Record Programs (Student Copy)

The document provides an overview of Python programming, covering basic operations, data types, loops, and functions. It includes examples of sequential, decision-making, and iterative program flows, as well as string manipulation and array handling. Additionally, it presents various programming tasks and sample programs to demonstrate the application of Python concepts.
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 views37 pages

AS Level Record Programs (Student Copy)

The document provides an overview of Python programming, covering basic operations, data types, loops, and functions. It includes examples of sequential, decision-making, and iterative program flows, as well as string manipulation and array handling. Additionally, it presents various programming tasks and sample programs to demonstrate the application of Python concepts.
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
You are on page 1/ 37

AS Level Record Programs

Programming language Python:


IDE to execute the program:
https://www.onlinegdb.com/online_python_compiler (does not require installation)
or Install Pycharm Or IDLE
Basic Operations:

Supports lots of math functions:


Example - math.sqrt(9), math.ceil(9.8)-10, math.floor(9.8) 9, math.pow(3,4) etc…

Data types:
int, float ,String/Text or Date/Time

Simple input commands:


r=int(input("Enter amount in rupees"))
p= float(input("Enter weight inpounds"))
name=input(“Enter name”)

Types of program flow:


1. Sequential
2. Decision making
3. Iteration/loop

Python support 2 types of loops:


for: fixed number of iteration/you know the number of iterations
while: unfixed/ you don't know how many times the loop runs

The for Loop The while Loop


With the for loop we can execute a set of statements With the while loop we can execute a
as long as a condition is true set of statements as long as a condition
is true.
Entry controlled
Entry controlled

for i in range(6):
print(“arnav”) i=1
print(“manav”)
while i < 6:

Note that range(6) is not the values of 0 to 6, but the print(i)


values 0 to 5.
i =i + 1

Output:

for i in range(2, 6): i=1


print(i) while i < 6:
print(i)
Output: if i == 3:
2 break
3 i += 1
4
5

for x in range(2, 30, 3):


print(x)

output: excluding 30
2
5
8

fruits = ["apple", "banana", "cherry"]

for i in fruits:
print(i)

Output:
apple
banana
cherry

for x in "banana":
print(x)

Output:
b
a
n
a
n
a

The break Statement

With the break statement we can stop the loop


before it has looped through all the items

fruits = ["apple",”mango”, "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

print(‘done’)
Output:
apple
mango
banana
done

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)

Output:
apple

The continue Statement

With the continue statement we can stop the current


iteration of the loop, and continue with the next

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue not executed
print(x) executed

print(‘done’)
Output:
apple
cherry
done

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for i in adj:
for j in fruits:
print(i,j)

Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

Hint: Random function in Python


Example 1: The randrange() method returns a randomly selected element from the specified
range.
import random
cnt5=0 cnt25=0
for i in range(1,21):
n =random.randrange(1,50))
if(n==5):
cnt5=cnt5+1
if(n==25):
cnt25=cnt25+1
Example 2:
The random() method returns a random floating number between 0 and 1
import random
r = random.random() r=0.25464*100 r=int(25.464)

Arrays:
Method 1: Single dimensional array
size = 10
a= [0] * size
for i in range(0,10):
a[i]= int(input("Enter array element"))

for i in range(0,10):
print(a[i])
or print(a)

Method 2: using 2D array

Method 1: assign data to 2d array Method 2: creating a 2d array of size 16X3


a=[ [15,15,15], #row=0, column=0,1,2 a= [] # empty array with no size
[24,28,24], #row=1, column=0,1,2 for i in range(0,16): add 16 rows
[28,32,28], #row=2, column=0,1,2
a.append([]) # adds one more row
……] # end here

Above initializationAutomatically makes a 2d for row in range(0,16): to each row we add 3


array of size 16 X3 columns
for column in range(0,3):
a[row].append([])
Print(a)
Or
for row in range(0,16):
for column in range(0,3):
a[row][column]=int(input(“enter age of the dog”))

print(a)

Strings
Some important String related operations
Functions: ord and chr
A-Z 65-90 a-z 97-122 0-9 47-58
n = chr(67) print(n) C
m= ord(‘B’) 66

String functions String s an array of chars s=’ha ppy’ 012345


#string delared
a = "star." a[0]=s a[1]=t a[2]=a a[3]=r a[4]=.

#getting number of characters of the string


print(len(a)) 5

#printing the third character


print(a[2]) ‘a’

#reading characters of the string one by one


l=len(a)
for i in range(0,5):
print(a[i])
s
t
a
r
.

#string
s="stardom"
0 1 2 3 4 5 6
s t a r d o m

n1=s[1:4]
n2=s[1:]
n3=s[:-1]
print(n1) # tar
print(n2) # tardom
print(n3) # stardo

Functions/Subroutines/Procedure
Features of a Function:
Functions are basically used for modularity and reusability
● A function is a block of code which only runs when it is called.
● You can pass data, known as parameters, into a function.
● A function can return data as a result.

Function code Output

def my_function1(): Hello from a function1


print("Hello from a function1") Hello from a function2

def my_function2():
print("Hello from a function2")

my_function1()
my_function2()

def my_function(fname): Emil Refsnes


print(fname + " Refsnes") Tobias Refsnes
Linus Refsnes
my_function("Emil")
my_function("Tobias")
my_function("Linus")

def my_function(fname, lname): Emil Refsnes


print(fname + " " + lname)

my_function("Emil", "Refsnes")

def my_function(fname, lname): Error


print(fname + " " + lname)

my_function("Emil")

Taking a default value: I am from Norway


def my_function(country=”Norway”): I am from Norway
print("I am from " + country) I am from Norway
I am from Norway
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")

[apple],[banana],[cherry]
Passing a List/Array as an Argument
def my_function(food):
for i in range(0,len(food)):
print(food[i])

# function ends here


fruits = ["apple", "banana", "cherry"]
my_function(fruits)

To let a function return a value, use the return


statement:
def my_function(x):
print 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

2 types of Functions
def fact(n): Non -returnable
Returbable
p=1

return p # also exits out of the function

for i in range(1,n+1):

p=p*i

return p

end def

#calling part of the pgm

v = fact(3) + fact(4) + fact(2) # 6+ 24 + 2

print(v) output(32)

Functions/Procedure/Subroutines AS Paper 2
Python: def

Java: functions

VB: Subroutines

Why do we need functions?

Assume you are writing a program to design a Game(Pubg)

Characters there do many things: running, firing, jump, hide etc..

You could write the entire pgm as 10000 lines

Or

Write each part of the pgm as separate modules/functions where we could put the code
related to a particular task as one function/def

def move()

#end of def

def jump()

#end of def

def shoot()

#end of def

def move()

#end of def

Advantages:

Each module could coded and tested separately

We could reuse the function as when req

Let’s code them:


def my_function1():

print(“hi”)

def my_function2():

print(“bye”)

def my_function3():

print(“smile”)

my_function1()

Functions:

Sample 1:

Write a program to create a function which inputs 3 numbers and then return the total
def sum(a,b,c): # data type s:int
s= a+b+c
return s

s1=sum(10,20,30)
s2= sum(45,67,89)
s=s1 + s2
print(s)

Sample 2:

Write a program in Python to create function to find the sum of the elements in an array

def sum(arr) #automatically assigns the value to arr


L= len(arr) s=0
for i in range(0,L):
s= s + arr[i]
return s
a=[1,2,3,45,6,7]
b=[30,40,20,70]
c=[45,34]
s= sum(a) + sum(b) + sum(c)

print(s)

Sample 3:

Write a program in python to create function which inputs a word and return num of vowels
in the given word

def vowel(w ):
L= len(w) v=0
for i in range(0,L):
c=w[i]
if(c==’a’) or (c==’e’)………..
v=v +1
return (v)
#end def

V1= vowel(“abei”)
V2= vowel(“vaibhav”)

print(V1)

print(V2)

Program: Decision making command- if command


1.
BESCOM is proposing a change in their electricity tariff. Write a program to ask a consumer
their usual units of consumption and then calculate their charges for the old and the new tariff.

Program: Iterations(for loop)


2. Update Program 1 to generate the bill for 100 customers

3.
Program using for/while loop:
For loop: if you know the length
while loop: if you don’t know the length

4) Write a program to input a number(any number of digits) and find the sum of the digits of
the number.
Example: Input: 2534 4+3+5+2
Output: 14
5) Write a program to input a number(any number of digits) find the product of the digits of the
number
Example: Input: 1234
Output: 24
6) Write a program to input a number(any number of digits) find the reverse of the digits of the
number
Example: Input: 2145
Output: 5412
7) Write a program to input a number(any number of digits) find the sum of the even and the
odd digits in the given number
Example: Input: 21459
Output: sum_even 6 sum_odd 15

8) Write a program to input a 5 digit number and then multiply each digit as given below with
its pos starting from backwards
Input: 56843
Process:
9 6 8 4 3
5 4 3 2 1

5X9 4X6 3X8 2X4 1X3

Find : sum
Divide sum by 10, if the remainder is 0, display it as a special number

9) Write a program to input a 5 digit number and then multiply each digit as given below with
its pos starting from front
Input: 56843
Process:
9 6 8 4 3
1 2 3 4 5

1X9 2X6 3X8 2X4 5X3

Find : sum
Divide sum by 10, if the remainder is 0, display it as a special number

10) The IMEI (15 decimal digits: 14 digits plus a check digit) includes information on the origin,
model, and serial number of the device.

11)Write a program in Python to input the first 14 digits of an IMEI number and find the check
(last) digit of it.

The check digit (x) is obtained by computing the sum of digits then computing 9 times that
value modulo 10.

In algorithm form:

1. Compute the sum of the digits (52 in this case).


2. Multiply the sum by 9 (9*52 = 468).
3. Divide the result by 10 and note down the remainder (468 % 10)
4. The last digit, 8, is the check digit.

12)

a) Write a program to input a number and then display if it a prime number or not

b) Write a program to display all the prime numbers between 1 and 100

c) Write a Program in Python to print all the Twin Prime numbers within a given range.

Note: Twin Prime numbers are a pair of numbers which are both prime and their difference is 2

Example: Twin Prime numbers in the range 1 to 100 are :

(3,5) (5,7) (11,13) (17,19) (29,31) (41,43) (59,61) (71,73)

13.
Write a Program in Python to input a number and check whether it is a Harshad Number
Harshad Number : In recreational mathematics, a Harshad number (or Niven number), is an
integer (in base 10) that is divisible by the sum of its digits.
Let’s understand the concept of Harshad Number through the following example:
•The number 18 is a Harshad number in base 10, because the sum of the digits 1 and 8 is 9
(1 + 8 = 9), and 18 is divisible by 9 (since 18 % 9 = 0)
•The number 1729 is a Harshad number in base 10, because the sum of the digits 1 ,7, 2 and 9
is 19 (1 + 7 + 2 + 9 = 19), and 1729 is divisible by 19 (1729 = 19 * 91)
•The number 19 is not a Harshad number in base 10, because the sum of the digits 1 and 9 is 10
(1 + 9 = 10), and 19 is not divisible by 10 (since 19 % 10 = 9)

Programs - Arrays:
Sample program using arrays
The weather department of Bangalore has set up many temperature measuring units at
strategic points. It measures the temperature in Fahrenheit on a daily basis . You are required
to convert it to Celsius, and tabulate it in an array. Display them in the following order

Day Celsius fahrenheit


1 _____ ______
2 _____ ______(HINT: c=(5/9)*(f-32) )

f=[0]*6 size:6 index: 0-5


c=[0]*6

for i in range(0,6):
f[i]=int(input("Enter temp in Fahrenheit"))

for i in range(0,6):
c[i]=(5/9)*(f[i]-32)

print("Day Fahrenheit celcius") # header


for i in range(0,6):
print( (i+1) ," ", c[i], " ", f[i])

Sample 2:
WAP to input the sales for each day for a complete month. Assume 30 days
i) Print the sales for all the days of the month
ii) Print the sales on all the days where it was more than 5000, with the day and the sales
value
iii) Print the sales on days where it was less than 5000, with the day and the sales value
iv) Print the total and the average sales for the whole month.
size=30 0-29
A=[]*size # empty memory locations
t=0

for i in range(0,30): #0-29


A[i]=int(input("Enter sale value for the day"))
t = t + A[i]

for i in range(0,30):
print(A[i]) # display the sales for 30 days

for i in range(0,30):
if(A[i]>5000):
print("days with sales above 5000:","day=",i,"sales=",A[i])

for i in range(0,30):
if(A[i]<5000):
print("days with sales below 5000:","day=",i,"sales=",A[i])

a=t/30
print("Total sales=",t))
print("avg sales=",a)

Sample 3:
WAP to input 10 elements in to an array and find the largest and smallest
a=[]*10
for i in range(0,10):
a[i]=int(input('enter an element'))
largest=a[0]
smallest=a[0]
for i in range(0,10):
if(a[i] >largest):
largest=a[i]
if(a[i] <smallest):
smallest=a[i]
print(largest)
print(smalle)

Sample 4:
a=[]*10
for i in range(0,10):
a[i]=int(input('enter an element'))
src=int(input('enter ur search ele")) 45
cnt=0
for i in range(0,10): i=9
if(src==a[i]) 45==5 False
cnt=cnt+1 cnt=1
if(cnt==0): False
print("not found")
else:
print("found", cnt, "times")

14
a) initialize or create an int array of size 10, add 5 to each element, display updated array
b) initialize or create an String array of size 10, input and concate a new letter to each
element, display updated array

15. An algorithm is needed to input a list of numbers representing test marks for a class of 30
students. The algorithm will output the number of students who have a mark greater than 75. It
will also output the average mark for the class.

16. Assume that you are purchasing provision from a shop like
Wheat, Rice, Pasta on a regular basis.
WAP to input the item name, price per kg, qty purchased and then calculate the subtotal for
each item for all 10 items and also print the grand total in the following order along with the
Date and the customer name
A value of 12% vat is charged on the total bill.

Output:
Date:
Customer name:
Sl. No Item_name Qty Price Subtotal
1 _____ ____ _____ ______
2 _____ ____ _____ ______
Total:
VAT 12%:
Grand total =

17. A chocolate factory produces bars of chocolate. A computer program controls the process.
The weight of each bar is stored in an array, BarWeight. The array contains 100
elements,representing the weights of 100 bars that make up one shipping box.
A procedure, CheckWeight(), is required to:
1. examine each array element and count how many times the weight has exceeded
MaxWeight
2. compare the count obtained with a limit value, Threshold. Call procedure ServiceCheck() if
the count exceeds the Threshold
3. output a message if the count does not exceed the Threshold. For example:
"ShippingBox OK – maximum weight exceeded 3 times."

18. A global 1D array, Contact, of type STRING is used to store a list of names and email
addresses.
There are 1000 elements in the array. Each element stores one data item. The format of each
data item is as follows:
<Name>':'<EmailAddress>
Name and EmailAddress are both variable-length strings.
For example:
"Wan Zhu:zwan99@mymail.com"
A function, Extract(), is part of the program that processes the array. A string data item is
passed to the function as a parameter. The function will return the Name part. Validation is
not necessary.

19. A student is developing an algorithm to count the number of times a given string,
SearchString, appears in a 2D array. The array, Item, consists of 100 elements organised as 50
rows of 2 columns. SearchString could appear in any row or column. The array is declared in
pseudocode as follows: DECLARE Item : ARRAY [1:50, 1:2] OF STRING

20. A company has sales in 3 branches, store the data for monthly sales over a period of 1
year, find the total monthly sales for each month, display those months where the total sales
is above 5000.
Also create a function to input branch, month and sales for a particular cell and update it

21.
The team wants a computer program to input and record the player data for one of the players.
a. Write the code here:
b. The team wants the program to produce a report, with the following specification.
The program outputs the total number of player scores that are:
• 50 and over but less than 100
• 100 or higher.
You can assume that before the section runs, the program has assigned all eight player scores
to the PlayerScore data structure

22.
A company hires out rowing boats on a lake. The company has 20 boats, numbered
from 1 to 20.
For safety reasons, the boats have to be serviced (checked and any damage repaired)
regularly.
The company is developing a program to help manage the servicing of the boats.
Every time a boat is serviced, details are added to a 2D array of size 100 called Service
The format of each line is as follows:
<BoatNumber><Date>
BoatNumber and Date are as follows:
• BoatNumber is a two-digit numeric string in the range "01" to "20"
• Date is an 8-digit numeric string in the format YYYYMMDD
Hint: Standard comparison operators may be used with dates in this format. For example:
"20200813" > "20200812" would evaluate to TRUE

Task 1: input a boat number and then count how many times this particular boat was
serviced.
Task 2: Input a Service date and then display all those boats which were services after this
date

23. Modify the above program to find the row value of each row, by assuming a value for
each row as given below

Task 3: Modify the above program to display the number of black pixel in each row
Task 4: Modify the above program to display the number of black pixel in each column

24. In a bus there are 15 seats in 3 rows and each row has 5 seats. All the empty seats are
represented by 0 and occupied seats by 1. To get a seat the passenger gives the seat number by
specifying the row and the column number. If the specified seat is empty then it is given to the
passenger. The process of filling the seat is done until all the seats are full. Write a program for
the above.
Change the above program to input names, use do-while to fill as many seats as you want,

25.
The student is interested in how simple encryption could be applied to a text message.
One of the simplest forms of encryption is a method of ‘substitution’ where each character
has a unique substitute character.
The student uses this method with the following character substitutions:

The programming language allows reference to individual characters, starting with index
1 as the first character.
E.g. MessageString ← “YESICAN”
MessageString[3] = ‘S’
Write the algorithm in pseudocode to input a message string and output the encrypted
string. Your algorithm will search the Alphabet array for each of the characters in
MessageString.
You may need to use additional variables to those already given in the identifier table.

26.
Write a Python program to calculate a dog's age in dog's years.

Task 1: Initialize a 2D array to store the data or Create a 2D array and ask the user to input the
data

Task 2:
Input size of the size and age of the dog and display its human equivalent age by looking thru
array
Example: Input small and 9
The dog's age 52 years

Random function:
27. A lottery game draws six numbers between 1 and 50, which are all different. A computer
program is to be developed to simulate the drawing of the six numbers.
The program needs a function, GetNumber(), to return a valid membership number. A valid
membership number is a four-digit numeric string between “1111” and “9999”.
The structured English representing the algorithm for this function is as follows:
1. Prompt and input a membership number.
2. Validate the membership number.
3. Repeat from step 1 if the membership number is invalid.
4. Return the valid membership number as a string.
An example of the function call in pseudocode is:
MembershipNumber GetNumber()
Write program code for the GetNumber() function.

28.

Task 1:

A bitmap image is saved using black and white pixels using a 2D array

WAP to input the color code in every pixel and then display the number of black and white
pixels in the given image

Problem

Rows =8 columns=8
Assign: 0 black 1 white Input:
b=[ [ 0,0,0,0,0,0,0,0 ], b=[]
[ 0,0,0,0,0,0,0,0 ], for i in range(0,8):
[ 1,00,1,1,0,0,1], b.append([])
[ 1,00,1,1,0,0,1 ],
[ ], …….. for i in range(0,8):
[ ], for j in range(0,8):
[ ], b[i].append([]) # empty grid of 8,8
[ ]
] for i in range(0,8): # this is the cod for
input
black=0 white=0 for j in range(0,8):
b[i][j]=int(input(‘enter 0-black,1-white’))
# code to find num of black and white pixels
for i in range(0,8): # code to find num of black and white pixels
for j in range(0,8): for i in range(0,8):
if(b[i][j]==0): for j in range(0,8):
white=white+1 if(b[i][j]==0):
else: white=white+1
black=black+1 else:
black=black+1
print(“num of black pixels”, black)
print(“num of white pixels”, white) print(“num of black pixels”, black)
print(“num of white pixels”, white)

Task 2:

Modify the above program to find the row value of each row, by assuming a value for each
row as given below

Task 3: Modify the above program to display the number of black pixels in each row

Task 4: Modify the above program to display the number of black pixels in each column
29.
A 2D array, Picture, contains data representing a bitmap image. Each element of the array
represents one pixel of the image. The image is grey-scale encoded where the value of each
pixel ranges from 0 (representing black) to 255 (representing white) with intermediate values
representing different levels of grey.
A graphics program needs a procedure, Flip(), to flip (reflect) the image. An example of an
image before and after the function is:

String Handling
30.
Write a Python program to check the validity of password input by users.
Validation :

● At least 1 letter between [a-z] and 1 letter between [A-Z].


● At least 1 number between [0-9].
● At least 1 character from [$#@].
● Minimum length 6 characters.
● Maximum length 16 characters.
List of programs for a Word input
31.
a) WAP to input a word and then display each char on a new line

w=input("Enter a word")
l=len(w)
for i in range (0,l):
print(w[i])

WAP to input a word and then display the ASCII value of each char on a new line
w=input("Enter a word")
l=len(w)
for i in range(0,l):
a=ord(w[i])
print(a)

b) WAP to input a word and then display the number of vowels from the given word

w=input("Enter a word")
l=len(w)
v=0
for i in range(0,l):
ch=w[i]
if (ch=="a" or ch=="i" or ch=="e" or ch=="o" or ch=="u"):
v=v+1

print(v)

c) WAP to input a word and then display the number of letters, digits and special
characters

w=input("Enter a word") w =”ha1234ppy.$#”


L=len(w)
l=0
d=0
s=0
for i in range(0,L):
ch=w[i] A-Z 65-90 a-z 97-122 0-9 47 -58
if (ch>="A" and ch<="Z") or (ch >="a" and ch<="z" ):
l=l+1
elif (ch >="0" and ch <="9"):
d=d+1
else:
s=s+1

print("number of letters=" ,l)


print("number of digits=" , d)
print("number of special characters=" , s)

d) WAP to input a word and then display only alternate chars from the word

w=input("Enter a word") w=”happy” 0 1 2 3 4


L=len(w) L = 5
newword = ""

for i in range(0,L):
if(i%2==0):
newword = newword + w[i]

print(newword) # only once hpy

OR

w=input("Enter a word")
a=len(w)
ch = ""
for i in range(0,a,2):
ch = ch + w[i]
print(ch)

e) WAP to input a word and then convert alternate chars to capital


w=input("Enter a word") w=”happy”

a=len(w)
nw=""

for i in range(0,a):
s=w[i]
if(i%2==0):
nw=nw+ s.upper()
else:
nw=nw+ s

print(nw)
f) WAP to input a word and then display the word in the reverse order. Also check if it is a
palindrome Ex: Input : mom
a. Output : mom………..It is a palindrome

w=input("Enter a word") w=”tree” 0123 tree


a=len(w)
nw=""

for i in range ((a-1) , -1 , -1 ):


nw = nw + w[i]

print (nw) nw=eert w=tree

if (nw==w):
print("the word is a palindrome")
else:
print("the word isn't a palindrome")

List of programs to work on a Sentence


32.
a) WAP to input a sentence and then display each word on a new line. Also display the
number of words in the sentence.

s= input ("Enter a sentence") s=”You are happy because you are good”

w =s.split(" ")
L=len(w)
for i in range(0,len(w)):
print(w[i])

b) WAP to input a sentence and then display how many times the word “the” appears in
the sentence.
s = input ("Enter a sentence")
w = s.split(" ")
l=0
for i in range(0,len(w)):
if(w[i]=="the"):
l=l+1

print(l)

c) WAP to input a sentence and the search word, then display how many times the search
word appears in the sentence.

s = input ("Enter a sentence")


w = s.split(" ")
x = input (“Enter search word”)
cnt=0
for i in range(0,len(w)):
if(w[i]==x):
cnt=cnt+1

print(cnt)

d) WAP to input a sentence and then display the 1st letter of each word on a new line.

s = input ("Enter a sentence")


w = s.split(" ")

for i in range(0,len(w)):
print(w[i][0])
e) WAP to input a sentence and then display the length of each word

s = input ("Enter a sentence")


w = s.split(" ")

l=0
for i in range(0,len(w)):
print(len(w[i]))
.

f) WAP to input a sentence and then display the last letter of each word on a new line.

s = input ("Enter a sentence")


w = s.split(" ")

for i in range(0,len(w)):
print(w[i][(len(w[i])-1)])

g) WAP to input a sentence and then check if the 1st letter of a word is a vowel. Display all
the words which starts with a vowel

s = input ("Enter a sentence")


w = s.split(" ")

for i in range(0,len(w)):
if (w[i][0]=="a" or w[i][0]=="e" or w[i][0]=="i" or w[i][0]=="o" or w[i][0]=="u" or w[i]
[0]=="A" or w[i][0]=="E" or w[i][0]=="I" or w[i][0]=="O" or w[i][0]=="U"):
print(w[i])

h) WAP in Python to accept a string and then find the longest word present in the sentence
Example: Input: Tata steel is one of the steel manufacturing companies of the
country
Output: manufacturing
s = input ("Enter a sentence")
w = s.split(" ")
nw = ""
a=0
for i in range(0,len(w)):
if (len(w[i]) > a):
a = len(w[i])
nw = w[i]
print(nw)
i)WAP in Python to accept a string in Python and then display the same in reverse order
Ex: Input : computer is fun
Output: fun is computer
s = input ("Enter a sentence")
w = s.split(" ")

for i in range(len(w) - 1 , -1 , -1):


print(w[i] , end=" ")
print()

Special String programs:

33. WAP to accept string and change the case of each character

Input: ComputerApplication
Output: cOMPUTERaPPLICATION

34.
WAP to input a word and then print it in the following order
Input: BlueJ or MADAM (try both)
Output:
B MADAM
Bl MADA
Blu MAD
Blue MA
BlueJ M
35.
WAP to accept a sentence in Python and then display each word in a reverse order
Ex: Input : India is my country
Output: aidni si ym yrtnuoc

36.
You can encode and decode a string in many ways. One of the simplest way to do that is to
replace each letter by a letter at a fixed distance ahead of or behind in the alphabet , where the
alphabet is assumed to wrap around (ie ‘A’ follows ‘Z’ )
Ex: Given string “COMPUTER” and encode = 3 means each character moves three characters
ahead. Thus , new string : FRPSXWHU

37. WAP to remove all the vowels from a given string


Sample input: computerapplications

Sample output : cmptrpplctns

38.
WAP to input a word in java and then display the Pig Latin word form
Input: trouble Output: oubletray
(A word is said to be a pig latin by framing the new word with the first vowel present in
the word with the remaining words present before the first vowel and ended with “ay”)

39.
Write a program to input a string and then display only if they are consecutive characters
Ex: String n = “UNDERSTANDING COMPUTER APPLICATION”
40.
WAP to input a string in uppercase and print the frequency of each character.
Ex: COMPUTERHARDWARE
Output:
Characters Freque
ncy
A 2
C 1
D 1

41:
Write a program to input a string and then display only if they are consecutive characters
DABC

n = “ABJKCDE”

AB

CD

DE

42. A string encryption function is needed. The encryption uses a simple character-
substitution method.
In this method, a new character substitutes for each character in the original string. This will
create the encrypted string.
The substitution uses the 7-bit ASCII value for each character. This value is used as an index
for a 1D array, Lookup, which contains the substitute characters.
Lookup contains an entry for each of the ASCII characters. It may be assumed that the original
string and the substitute characters are all printable.
For example:
• ‘A’ has ASCII value 65
• Array element with index 65 contains the character ‘Y’ (the substitute character)
• Therefore, ‘Y’ substitutes for ‘A’
• There is a different substitute character for every ASCII value
The programmer writes a function, EncryptString, to return the encrypted string. This
function will receive two parameters, the original, PlainText string and the 1D array.

43. A computer program is to simulate the reading and processing of a string of characters
from an
input device.
The character string consists of:
• a number of digit characters
• one or more <*> characters, each used as a separator
• a final <#> character.
A typical input character sequence, stored as InputString is:
13*156*9*86*1463*18*#
44.
A country has a number of banks. There are cash dispensers all over the country. Each bank is
responsible for a number of dispensers.
• banks have a three digit code in the range 001 – 999
• each dispenser has a five digit code in the range 00001 – 99999(unique code)
A text file, bank.txt , is to be created. It has one line of text for each dispenser.
For example: 00342,007.
This line in the file is the data for dispenser 00342 which belongs to bank 007.
A Part bank.txt file looks like

Write 3 functions:
Function 1:
def ADD( ) # add a new record bank.txt has 0 records

End def

Function 2:
The program will:
• add new dispenser to a bank
• input a bank number and then display list of all the dispensers which belong to this bank
• input the bank and the dispenser number and delete that record from the file
def add():
f= open("bank.txt", "a")
bank_code=input("enter the bank code")
dsp= input('enter the dispenser num')
s= bank_code+ ","+ dsp
f.write(s)
f.close()
#end of def

def display_class():
f= open("bank.txt", "r") # read only view mode
src=input("enter bank code")

while True:
# read a single line
s = f.readline() # 001
if (s==""):
break
else:
w=[]
w=s.split(',') #002, 20001
b=w[0] #b=001
d=w[1] #d=20000

if(b==src): #001==001
print(s)
#end of the loop

f.close()
#end of def

display_class()

#End def

Function 3:
Delete a particular record by inputting the bank code and the dispenser number

def delete():
f = open("bank.txt", "r")

new_f = open("new_file.txt", "w")

src_b = input("enter bank number of record you'd like to delete")

src_d = input("enter dispenser number of record you'd like to delete")

while True:

r = f.readline()

if (r == ""):

break

else:

re = r.split(",")

if not((re[0] == src_d) and (re[1] == src_b)):

new_f.write(r)

f.close()

new_f.close()

os.remove("bank.txt")

os.rename("new_file.txt", "bank.txt")

add()

search()

delete()

45. Sample program for sorting


Write a program in python to input 10 numbers and sort them using bubble sort
def sort(a):
for i in range(0,10):
for j in range(0,10-1-i):
if (a[j] > a[j+1]):
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp

a = []
for i in range(0,10):
a.append([])
a[i] = int(input("Enter element"))

sort(a)
print(a)

a) Define a class and store the given city names in a single dimensional array, Sort these names
in alphabetical order using the Bubble sort technique only.
b) WAP to input name and telephone numbers of 10 people in 2 different arrays
Sort the data based on the name array

46. Write a Function to validate a pwd. A pwd is said to be valid if it has at least 2 chars, 1
digits and a $ sign
def validate(pwd ): pwd=”AB56$”
L = len(pwd) c=0 d=0 sp=0
pwd=pwd.upper()
for i in range(0,L):
ch=pwd[i]
if (ch>=’A’) and (ch<=’Z’):
c=c+1
elif (ch>=’0’) and (ch<=’9’):
d= d+1
elif (ch==’$)
sp=sp+1

if(c>=2) and (d>=1) and (sp>=1):


return “valid”
else: return “Invalid”
#end of def
v= validate(“HG78$”)
print(v)
47: Fact: Chelating agents such as ethylenediamine tetraacetic acid (EDTA) have been used in
different situations in phytoremediation to enhance the extraction of heavy metals by plants
from soil.
There was an experiment conducted to check the impact of water, EDTA(25mM and 5mM)
and a Miracle Gro fertilizer on Pea plants.
Write a program in Python to check which one had the maximum impact on growth of the
plants. Consider 10 saplings for each type of treatment.
Sample Picture

Sample of the expected Output:

Pre release material to be solved:


May/June 2018
May/June 2020
June 2021

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy