Python

Area of the Circle

Program to find the area of a circle.That program takes in a radius of a circle as a input parameter and output the Area of the circle.

def get_area(r):
    return pi * pow (r,2) 

print get_area(2)

Square Root

Program to find the Square Root of the function.In this program Input parameters are guess and the number.

def sqrt(x,guess=0.0):
    if x and guess<0:
        print None
    if good_enough(guess,x):
        return guess
    else:
        new_guess=improve_guess(guess,x)
        return sqrt(x,new_guess)


def good_enough(guess,x):
    if abs(guess*guess-x)<0.00001:
        return True
    else:
         return False

def average(x,y):
    avg=(x+y)/2.0
    return avg

def improve_guess(guess,x):
	x=x*1.0
    if guess < 1:
        return guess+5.00000
    else:
        new_guess=average(guess,x/guess)
        return new_guess

NUCES SPGA

Program to find the sgpa of the student.In this program input parameter are grades of the student and output will be sgpa of the student.

def calculate_sgpa(g1,g2,g3):
    subjects=0.0
    points=0.0
    if not g1 == "nothing":
        gpa1=score(g1)
        subjects=subjects+1
        points=points+gpa1

    if not g2 == "nothing":
        gpa2=score(g2)
        subjects=subjects+1
        points=points+gpa2

    if not g3== "nothing":
        gpa3=score(g3)
        subjects=subjects+1
        points=points+gpa3
    if subjects==0:
        return 0
    else:
        final_sgpa=(points/subjects)
        return final_sgpa


def score(n):

    if n=="A+":
        return 4.0
    elif n=="A":
        return 4.0
    elif n=="A-":
        return 3.67
    elif n=="B+":
        return 3.33
    elif n=="B":
        return 3.0
    elif n=="B-":
        return 2.67
    elif n=="C+":
        return 2.33
    elif n=="C":
        return 2.0
    elif n=="C-":
        return 1.67
    elif n=="D+":
        return 1.33
    elif n=="D":
        return 1.0
    
    elif n=="F":
        return 0.0


print calculate_sgpa('A', 'B', 'nothing')

Is Prime?

Program that takes in one number and decide that number is prime or not.

def is_prime(p):
    if prime(p):
        x=11
        while p>=x*x:
            x=x+2
            if p==x*x:
                return False
        else:
            return True
    else:
        return False


def prime(new):
    if new<=1:
        return False
    else:
        p=int(new)
        if new==p:
            if p==2 or p==3 or p==5 or p==7 or p==11:
                return True
            if p%2==0 :
                return False
            if p%3==0 :
                return False
            if p%5==0:
                return False
            if p%7==0 :
                return False
            if p%11==0 :
                return False
            else:
                return True
        else:
            return False

print is_prime(499)  # should return True

Factors of a Number

Program to find the factors of the given number. This function output the factors of the number passed as input – one factor on each line.

 

def output_factors(num):
    if num>=1:
        n=int(num)
        if n==num:
            new_num=int((num+4)/2)
            for start in range (1,new_num):
                if num%start==0:
                    print (start)
            print (n)
        else:
            print (None)
    else:
        print (None)


output_factors(10)

Largest Prime Number

Program to find the largest prime number.This function will be passed a number
and it should return the largest prime number that is smaller than or equal to than this input.In this function we also use Prime Function.

 

def get_largest_prime(p):
    if p>=2:
        p=int(p)
        if is_prime(p):
            return p
        else:
            new_p = improvement(p)
            return get_largest_prime(new_p)
    else:
        return None

def improvement(number):
    if number%2==0:
        new_number=number-1
        return new_number
    else:
        new_number=number-2
        return new_number

print get_largest_prime(10)  # should return 7

Prime factors of a Number

Program to find the Prime factor of a number that is given to that function.

def output_prime_factors(num):
    num = round (num)
    start=0
    while start= x * x:
            x = x + 2
            if p == x * x:
                return False
        else:
            return True
    else:
        return False


def prime(new):
    if new <= 1:
        return False
    else:
        p=int(new)
        if new==p:
            if p == 2 or p == 3 or p == 5 or p == 7 or p == 11:
                return True
            if p % 2 == 0 :
                return False
            if p % 3 == 0 :
                return False
            if p % 5 == 0:
                return False
            if p % 7 == 0 :
                return False
            if p % 11 == 0 :
                return False
            else:
                return True
        else:
            return False


output_prime_factors(23)

Prime Number

Program to find the nth prime number.This function will be given a number n as
input. The function should find the n th prime number. For example, if we pass the number 1 as input, the function should return 2.

def get_nth_prime(n):
    if n==1:
        return 2
    else:
        b = 1
        while n > 1:
            b = b + 2
            if is_prime(b):
                n = n - 1
                if n == 1:
                    return b


print get_nth_prime(4)

NUCES SGPA using list

Program to calculate the sgpa of the student by giving input a list of grades of the student.

def calculate_sgpa(lst):
    if lst == None : return None
    if lst == [] :return 0 
    if type(lst) == list :
        counter =len(lst)
        b = []                # List of score 
        for i in lst :
            a = score (i)
            if a == None:
                return None
            b.append (a)     
        sum_of_score = sum(b)  # Adding the Element of list 
        sgpa = sum_of_score / counter
        return sgpa
    else:
        new = [lst]
        return calculate_sgpa(new)


def score(n):

    if n == "A+" : return 4.0
    elif n == "A" : return 4.0
    elif n == "A-" : return 3.67    
    elif n == "B+" : return 3.33 
    elif n == "B" : return 3.0  
    elif n == "B-" : return 2.67
    elif n == "C+" : return 2.33
    elif n == "C" : return 2.0
    elif n == "C-" : return 1.67
    elif n == "D+" : return 1.33    
    elif n == "D" : return 1.0
    elif n == "F" : return 0.0
    elif n == None : return None 
    else :
        return None


print calculate_sgpa(['A+'])

NUCES SGPA Weighted

Program to Calculate the sgpa of the student based on the credit hour of the subject.

def calculate_sgpa_weighted(lst1 , lst2):
    if lst1 == [] or lst2 == [] : return 0 
    if type(lst1) != list:
        result= score(lst1)
        return result
    l1 = len (lst1)
    l2 = len (lst2)
    weighted = sum(lst2)
    points = []                #lsit of point scored
    if l1 == l2 :
        for i in lst1 :
            c = score(i)
            if c == None : return None
            points.append(c)
        multiplied_value = []    #list of ponits scored multipy with weighted
        for i in points :
            for j in lst2 :
                t = i * j
                multiplied_value.append(t)
                lst2.pop(0)
                break
        total_points = sum(multiplied_value)
        final_value = total_points / weighted
        return final_value 
    else:
        return None


print calculate_sgpa_weighted(['A+'], [4])

Cumulative Marks

Program to find the cumulative marks.This function will be given a list of tuples.Each tuple represents the scores of a student. The first element is the roll number of the student and the second is the full name. The rest of the elements are the student’s score in assignments.

def find_cumulative_marks(lst):
    if lst == None : return  None 
    if lst == [] : return []
    if type(lst) == list :
        final_list = []
        for i in lst :
            student_list = list (i) 
            sum_of_score = 0 
            lst1 = []
            for j in student_list : 
                if j == None : sum_of_score = sum_of_score + 0
                if type(j) == str : lst1.append(j) 
                if type(j) == int or type(j) == float  : sum_of_score=sum_of_score+j
            lst1.append(sum_of_score)
            final_tuple = tuple(lst1)
            final_list.append(final_tuple)
        return final_list



results = [
        ('p101111', 'Ali Khayam', 64, 78.5, 89, 25, 99),
        ('p101112', 'Mudasser Farooq', 14, 28.5, 83, 76),
        ('p101113', 'Tamleek Ali', 87, None, 1.6)
         ]

print find_cumulative_marks(results) 

Top Student

Program to find the top student.This function will be given a list of tuples.Each tuple represents the scores of a student. The first element is the roll number of the student and the second is the full name. The rest of the elements are the student’s score in assignments.We use the previous program of cumulative marks in this program.

def find_top_student(lst):
    lst1 = find_cumulative_marks(lst)
    list_of_score = []
    for i in lst1:
        lst2 = list(i)
        for j in lst2 :
            if type(j) == int or type(j) == float:
                list_of_score.append(j)
    top_student = max(list_of_score)
    counter = 0
    final_list = []
    for i in list_of_score :
        if i == top_student :
            list_of_top_student = list(lst1[counter])
            for i in list_of_top_student :
                if type(i) == int or type(i) == float:
                    list_of_top_student.remove(i)
                    tuple_of_top_student = tuple(list_of_top_student)
                    final_list.append(tuple_of_top_student)
        counter = counter + 1
    if len(final_list) == 1 : return tuple_of_top_student
    else:
        return final_list





 results = [
        ('p101111', 'Ali Khayam', 64, 78.5, 89, 25, 99),
        ('p101112', 'Mudasser Farooq', 14, 28.5, 83, 76),
        ('p101113', 'Tamleek Ali', 87, None, 1.6)
    ]
print find_top_student(results)

Count Lines

Program to find the lines in a file.That takes in a directory and a filename.It can take in an optional third parameter. If this parameter is set to True, the function should only count lines which have something other than a whitespace in them. It then read this file from the directory and return the number of lines which are in this file.


def line_count(directory , filename , condition = False):
    count = 0
    final_file = os.path.join(directory , filename)
    with open (final_file , 'r') as f:
        list_of_lines = f.read().split('\n')
        if condition == True:
            for line in list_of_lines:
                if line != '':
                    count = count + 1
        if condition == False:
            for line in list_of_lines:
                count = count + 1
    return count

print line_count('.', 'essay.txt')

Count Character

Progam to find the character in a file.That takes in a directory and a filename.It can take in an optional third parameter, which if set to True, causes the function to skip whitespaces from the character count. It should then read this file from the directory.It should count the number of characters in the given file instead of the number of lines.


def character_count(directory , filename , y = False):
    count = 0
    final_file = os.path.join(directory , filename)
    with open (final_file , 'r') as f:
        if y == True:
            for line in f:
                for i in line:
                    if i == ' ' or i == '\n' :
                        count = count + 0
                    else:
                        count = count + 1
        if y == False:
            for line in f:
                for i in line:
                    count = count + 1
            
    return count


print character_count('.', 'essay.txt')

Move lines

Program to moves line from one file to the other file.It takes in two relative paths.One for the input file and another for the output file. The function also take in a third parameter that gives the number of lines to be moved from the input file to the output file. This function returns nothing but moves the specified number of lines from the top of the input file to the output file.


def move_lines(file1 , file2 , lines):
    with open (file1 , 'r') as f:
        list_of_lines = f.read().split('\n')
        list_of_lines 
        value = list_of_lines[:lines]
        with open (file2 , 'w') as f:
            final = '\n'.join(value)
            f.write(final)


move_lines('essay.txt', 'out.txt', 3)