Python Devlopment






Practice Programs-1



1. A positive integer m can be expresseed as the sum of three squares if it is of the form p + q + r where p, q, r ≥ 0, and p, q, r are all perfect squares. For instance, 2 can be written as 0+1+1 but 7 cannot be expressed as the sum of three squares. The first numbers that cannot be expressed as the sum of three squares are 7, 15, 23, 28, 31, 39, 47, 55, 60, 63, 71. Write a Python function threesquares(m) that takes an integer m as input and returns True if m can be expressed as the sum of three squares and False otherwise. (If m is not positive, your function should return False.)

 

def threesquares(n):
    if n<0:
        return False
    for i in range(1, int(n**0.5)  + 1 ):
        for j in range(1, int(n**0.5) + 1 ):
            for k in range(1, int(n**0.5) + 1 ):
                m = i**2 + j**2+k**2
                if m == n:
                    return True
                elif m > n:
                    break
    return False

 

2. Write a function repfree(s) that takes as input a string s and checks whether any character appears more than once. The function should return True if there are no repetitions and False otherwise.

 

def repfree(arr):
    count=0
    for i in range (len(arr)):
        value=arr[i]
        for j in range (len(arr)):
            if arr[j]==value:
                count=count+1
        if(count>1):
            return("False")
        else:
            return("True")

 

3. A list of numbers is said to be a hill if it consists of an ascending sequence followed by a descending sequence, where each of the sequences is of length at least two. Similarly, a list of numbers is said to be a valley hill if it consists of an descending sequence followed by an ascending sequence. You can assume that consecutive numbers in the input sequence are always different from each other. Write a Python function hillvalley(l) that takes a list l of integers and returns True if it is a hill or a valley, and False otherwise.

 

def hillvalley(l):
    if (len(l) < 3):
        return False
 
 
    up_count = 1
    low_count = 1
 
    for i in range(0, len(l) - 1):
        if l[i] > l[i + 1]:
            if low_count > 1:
                return False
            up_count = up_count + 1
        if l[i] < l[i + 1]:
            low_count = low_count + 1
        if l[i] == l[i + 1]:
            return False
            
    if up_count > 1 and low_count > 1:
        return True
    else:
        return False