Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Standard ML code Write a function firstN that takes a list and an int n and retu

ID: 3744542 • Letter: S

Question

Standard ML code

Write a function firstN that takes a list and an int n and returns the first n elements in the list. The type of firstN should be string 'a list -> int -> 'a list. If the input list is empty or if the length of the list is less than n, then the function should return the complete list. (You may assume that n is greater than 0.)

Examples:

> firstN ["a", "b", "c", "x", "y"] 3

["a", "b", "c"]

> firstN [1,2,3,4,5,6,7] 4

[1,2,3,4]

> firstN [1,2,3,4,5,6,7] 10

[1,2,3,4,5,6,7]

> firstN [[1,2,3],[4,5],[6],[],[7,8],[]] 4

[[1,2,3],[4,5],[6],[]]

> firstN [] 5 /*may give a warning*/ []

Explanation / Answer

def firstN(arr,val):
   arr2=list() #creating new list to store output
   if(len(arr)==0):
       print('no elements in the list')
   else:
       for i in range(0,val): #coping the array elements to output list
           arr2.append(arr[i])
   print(arr2)  
if __name__ == '__main__':
   print('enter list')
   arr = list(map(str, input().split())) #we are taking input from user     input should be space separated
   print('enter how much lenght you print')
   var=int(input())   #this value should be in new line
   firstN(arr,var) #passing to function

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote