1. Question1_J24.py

DataStored=[]#array of 20 integer
NumberItems=len(DataStored)#stores the quantity of item in array
 
def Initialise():
  global DataStored, NumberItems
  
  Quan=int(input('Please enter a quantity'))
  
  while Quan<1 or Quan>20:
    print('Please only enter quantity between 1 and 20 inclusive')
    Quan=int(input('Please enter a quantity'))
    
  for i in range(Quan):
    num=int(input('Please enter number to store to array'))
    DataStored.append(num)

def BinarySearch(DataToFind):
  global DataStored, NumberItems
  #need to convert input to integer
  DataToFind=int(DataToFind)
  lowerBound=0
  upperBound=len(DataStored)-1#to correctly accessed array index as Py is zero-indexed

  while lowerBound<=upperBound:
    mid=(lowerBound+upperBound)//2
    if DataToFind==DataStored[mid]:
      print(f'the index to find {DataToFind} is {mid}')
      return mid#function exits after return any value
    elif DataToFind>DataStored[mid]:#upper area
      lowerBound=mid+1
    elif DataToFind<DataStored[mid]:
      upperBound=mid-1
      #if return does not happen, then directly goes to this
  print(f'{DataToFind} is not in the list.')
  return -1

  
def main():
    global DataStored
    global NumberItems
    
    Initialise()
    NumberItems = len(DataStored) 
    print(f"original array: {DataStored}")
    print(f"Number of items stored: {NumberItems}")

##    BubbleSort(DataStored)
##    print(f"After bubble sort: {DataStored}")

    BinarySearch(int(input('Please enter the data to find')))
    
    
main()

Outputs:


2. Question2_J24.py

class Tree:
    #PRIVATE TreeName: STRING
    #PRIVATE HeightGrowth: INTEGER
    #PRIVATE MaxHeight: INTEGER
    #PRIVATE MaxWidth:INTEGER
    #PRIVATE Evergreen:STRING
    def __init__(self,TN,HG,MH,MW,EG):
        self.__TreeName=TN
        self.__HeightGrowth=HG
        self.__MaxHeight=MH
        self.__MaxWidth=MW
        self.__Evergreen=EG
        
    def GetTreeName(self):
        return self.__TreeName
    def GetGrowth(self):
        return self.__HeightGrowth
    def GetMaxHeight(self):
        return self.__MaxHeight
    def GetMaxWidth(self):
        return self.__MaxWidth
    def GetEvergreen(self):
        return self.__Evergreen

array=[]
def ReadData():
    global array
    array=[]#array of type tree
    try:
        with open('Trees.txt','r') as f:#read file
            #for each line in file
            for line in f:
                #get line and insert it as parameter of Tree class
                #instanciate the object
                j=line.strip().split(',')
                #print(j)
                #j outputs Hazel,40,300,200,No, but it is sent as one parameter to Tree(), how to make it so that it will be sent as seperate parameter so all arguments is fulfilled
                # missing 4 required positional arguments: 'HG', 'MH', 'MW', and 'EG'
                #print(type(j))
                if len(j)==5:
                    obj=Tree(j[0],j[1],j[2],j[3],j[4])
                    #add obj to array
                    array.append(obj)
                else:
                    print('not enough parameter',j)
        
        #print(array)
        return array
    except FileNotFoundError:
        print('File not found')
        return None

def PrintTrees(obje):
    global array
    #takes tree object as parameter
    #check object's attribute( Evergreen)
    treeName=obje.GetTreeName()
    maxHeight=obje.GetMaxHeight()
    maxWidth=obje.GetMaxWidth()
    heightGrowth=obje.GetGrowth()
    if obje.GetEvergreen()=='Yes':
        print(f'{treeName} has a maximum height {maxHeight} a maximim width {maxWidth} and grows {heightGrowth} cm a year. It does not loose its leaves.')
    else:
        print(f'{treeName} has a maximum height {maxHeight} a maximim width {maxWidth} and grows {heightGrowth} cm a year. It loses its leaves each year.')

        
def ChooseTree(arr):

    new=[]# new array
    mH=int(input("Please enter maximum height in cm"))
    mW=int(input('Please enter maximum width in cm'))
    evergreen=input('Please choose whether evergreen (enter yes) or not evergreen(enter no)')#how to make the input to be either No or Yes?
    evergreen=evergreen.lower()
    #check if which index in arr matches the requirements
    #loop through all elements in arr
    for i in range(len(arr)):
        if (int(arr[i].GetMaxHeight())<=mH) and (int(arr[i].GetMaxWidth())<=mW) and (arr[i].GetEvergreen().lower()==evergreen):
            #if matches requirements, add to new array
            new.append(arr[i])
            PrintTrees(arr[i])#call PrintTrees for each Tree objects that meets requirements
    
    #take as input eh name of one of trees in new array
    name=input('Please enter the name one of the trees listed.')
    height=float(input('Please state the starting height of tree when bought.'))
    for f in range(len(new)):
        maxH=float(new[f].GetMaxHeight())
        #check the name within array new
        treeName=new[f].GetTreeName()
        divide=float(new[f].GetGrowth())
        if treeName.lower()==name.lower():
            
            h=maxH-height
            years=float(h/divide)
            print(f'It will takes {years} years for {name} to grow to its maximum height of {maxH}')

def main():
    global array
    ReadData()
    #PrintTrees(array[0])# calls PrintTree with the first object in the returned array
    ChooseTree(array)

main()

Outputs:


Question3_J24.py

QueueData=[]#DECLARE QueueData:ARRAY[0:19] OF STRING
QueueHead=0
QueueTail=0
def main():
    global QueueData, QueueHead, QueueTail
    #initialize all elements in QueueData to null value
    QueueData=['' for _ in range(20)]
    QueueHead=-1
    QueueTail=-1
    StoreItems()
    Dequeue()

def Enqueue(insert):
    global QueueData, QueueHead, QueueTail
    #check if queue is full
    if QueueTail==19:
        print('Queue is full, cannot enqueue')
        return False
    else:
        QueueTail+=1
        QueueData.append(insert)
        print(f'Successfully enqueue {insert}')
        return True

def Dequeue():
    item=''#to store the element to be dequeued
    global QueueData, QueueHead, QueueTail
    if QueueTail==-1:#or QueueTail==QueueHead
        print('Queue is empty, cannot dequeue')
        return False
    else:
        item=QueueData[QueueHead]
        print(item)
        
        QueueData[QueueHead]=None
        QueueHead+=1
        print(f'Successfully dequeue {item}')
        print(QueueData)
        return item
invalid=0
def StoreItems():
    global QueueData, QueueHead, QueueTail,invalid
    thisString=str(input('Please enter a 7 digit character string'))
    
    
    while len(thisString)!=7:#validate string length
        thisString=str(input('Please only enter a 7 digit character string'))

    So1=(int(thisString[0])+int(thisString[2])+int(thisString[4]))
    So2=(int(thisString[1])*3)+(int(thisString[3])*3)+(int(thisString[5])*3)
    Sum=int((So1+So2)/10)
    
    if Sum==10:
        Sum='X'
    
    if str(Sum)==thisString[6]:#valid input
        #removed check digit
        thisString=thisString[0:6]
        Enqueue(thisString)
        
    else: #invalid input don't store
        invalid+=1
        print(f'number of invalid inputs are {invalid}')
    print(QueueData)
     
main()

take notes:

while len(thisString) != 7: 
	print('Please only enter a 7-digit character string') 
	thisString = input('Please enter a 7-digit character string: ')
if str(Sum) == thisString[6]: # Convert Sum to string for comparison
item=QueueData[QueueHead]

Outputs:

Please enter a 7 digit character string999999X
Successfully enqueue 999999
Please enter a 7 digit character string1251484
Successfully enqueue 125148
Please enter a 7 digit character string5500212
Successfully enqueue 550021
Please enter a 7 digit character string0033585
number of invalid inputs are 1
Please enter a 7 digit character string9845788
Successfully enqueue 984578
Please enter a 7 digit character string6666666
number of invalid inputs are 2
Please enter a 7 digit character string3258746
number of invalid inputs are 3
Please enter a 7 digit character string8111022
Successfully enqueue 811102
Please enter a 7 digit character string7568557
Successfully enqueue 756855
Please enter a 7 digit character string0012353
number of invalid inputs are 4
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '999999', '125148', '550021', '984578', '811102', '756855']