VITyarthi Fundamentals of AI and ML Module 6 Challenging Task Solution (Question on Variables and Lists)

Note : If you directly copy – paste this solution , you may get any error. 

Question 1

Write a Prolog program that takes in a sequence of integers as input and calculates the Average of all even numbers provided.

% Base case: When the list is empty, the average is 0. Average_even([], 0).

 

 

% Recursive case: When the list is not empty, check the first element.

 

% If it’s even, calculate the average of the rest of the list and add the first element to it.

 

% If it’s odd, ignore it and calculate the average of the rest of the list. Average_even([H|T], Avg) :-

     0 is mod(H, 2), % Check if the number is even

 

       Average_even(T, RestAvg),

 

        Avg is (RestAvg * length(T) + H) / (length(T) + 1).

 

 

 

Average_even([H|T], Avg) :-

 

    1 is mod(H, 2), % Check if the number is odd

 

      Average_even(T, Avg).

 

Question 2

Write a Prolog program that takes a sequence of strings as input and returns the number of Strings starting with a vowel

% Base case: When the list is empty, the count is 0. Count_strings_starting_with_vowel([], 0).

 

 

% Recursive case: When the list is not empty, check the first element.

 

% If it starts with a vowel, increment the count and calculate the count in the rest of the list.

 

% If it doesn’t start with a vowel, calculate the count in the rest of the list. Count_strings_starting_with_vowel([H|T], Count) :-

        String_chars(H, [FirstChar|_]), % Extract the first character of the string          Member(FirstChar, [‘a’, ‘e’, ‘I’, ‘o’, ‘u’]), % Check if the first character is a vowel         

        Count_strings_starting_with_vowel(T, RestCount),

         Count is RestCount + 1.

 

 

 

Count_strings_starting_with_vowel([_|T], Count) :-          Count_strings_starting_with_vowel(T, Count).

 

Question 3

Write a Prolog program that takes in a sequence of words as input and returns the length of The longest word in the sequence.

 % Base case: When the list is empty, the length of the longest word is 0. Longest_word_length([], 0).

 

 

% Recursive case: When the list is not empty, check the length of the first word.

 

% Calculate the length of the longest word in the rest of the list,

 

% and compare it with the length of the first word to determine the overall longest word length. Longest_word_length([H|T], Length) :-

        Atom_length(H, WordLength), % Calculate the length of the first word

 

Longest_word_length(T, RestLength),

Length is max(WordLength, RestLength).



If you find anything wrong in this Solution, feel free to reach us in the comment section.

Sharing Is Caring:

Leave a Comment