AS Level Record Programs (Student Copy)
AS Level Record Programs (Student Copy)
Data types:
int, float ,String/Text or Date/Time
for i in range(6):
print(“arnav”) i=1
print(“manav”)
while i < 6:
Output:
output: excluding 30
2
5
8
for i in fruits:
print(i)
Output:
apple
banana
cherry
for x in "banana":
print(x)
Output:
b
a
n
a
n
a
print(‘done’)
Output:
apple
mango
banana
done
Output:
apple
print(‘done’)
Output:
apple
cherry
done
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
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)
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
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.
def my_function2():
print("Hello from a function2")
my_function1()
my_function2()
my_function("Emil", "Refsnes")
my_function("Emil")
[apple],[banana],[cherry]
Passing a List/Array as an Argument
def my_function(food):
for i in range(0,len(food)):
print(food[i])
print(my_function(3))
print(my_function(5))
print(my_function(9))
2 types of Functions
def fact(n): Non -returnable
Returbable
p=1
for i in range(1,n+1):
p=p*i
return p
end def
print(v) output(32)
Functions/Procedure/Subroutines AS Paper 2
Python: def
Java: functions
VB: Subroutines
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:
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
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)
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
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
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:
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
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
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)
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):
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 :
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
d) WAP to input a word and then display only alternate chars from the word
for i in range(0,L):
if(i%2==0):
newword = newword + w[i]
OR
w=input("Enter a word")
a=len(w)
ch = ""
for i in range(0,a,2):
ch = ch + w[i]
print(ch)
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
if (nw==w):
print("the word is a palindrome")
else:
print("the word isn't a palindrome")
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.
print(cnt)
d) WAP to input a sentence and then display the 1st letter of each word on a new line.
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
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.
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
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(" ")
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
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")
while True:
r = f.readline()
if (r == ""):
break
else:
re = r.split(",")
new_f.write(r)
f.close()
new_f.close()
os.remove("bank.txt")
os.rename("new_file.txt", "bank.txt")
add()
search()
delete()
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