# The Joy of Computing using Python | Week 5

**Session: JAN-APR 2024**

**Course Name: The Joy of Computing using Python**

**Course Link: Click Here**

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

#### Q1. Imagine the Monty Hall problem had four doors instead of three, and Monty opened one door to reveal a goat after your initial choice, what would be the probability of winning the car by switching?

1/2

1/3

1/4

3/4

**Answer: 3/4**

**Q2. What happens if you try to add a new key-value pair to a dictionary using a key that already exists in the dictionary?**

The new value overwrites the existing value

An error is raised

The dictionary becomes immutable

The new value is appended to the existing value

**Answer: The new value overwrites the existing value**

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q3. The extended version of “Rock, Paper, Scissors” with “Lizard” and “Spock” was popularized by the TV show “The Big Bang Theory.” Here are the rules for “Rock, Paper, Scissors, Lizard, Spock”:Rock wins against Scissors.Scissors wins against Paper.Paper wins against Rock.Rock wins against Lizard.Lizard wins against Spock.Spock wins against Scissors.Scissors wins against LizardLizard wins against PaperPaper wins against Spock.Spock wins against Rock.**

**Each option can defeat two other options, lose to two other options, and draw with one other option.What would be the possible change in steps for running “Rock, Paper, Scissors, Lizard, Spock”?**

Step 1 would involve assigning 5 values to choices instead of 3

The bitwise operations involved in Step 3 would involve modulo operation with 5 instead of 3

None of the above

All the above

**Answer: All the above**

**Q4. How does Bubble Sort compare elements in an array?**

Compares adjacent elements and swaps if they are in the wrong order

Compares random elements in the array

Compares all elements with the first element

Compares elements in reverse order

**Answer: Compares adjacent elements and swaps if they are in the wrong order**

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q5. To sort a list in ascending order when does Bubble Sort exhibit poor performance?**

When the list is sorted in ascending order

When the list is sorted in descending order

When the list contains unique elements

Bubble Sort always exhibits poor performance

**Answer: When the list is sorted in descending order**

**Q6. How many passes does Bubble Sort make through the array in the worst-case scenario for sorting n elements?**

n

n-1

2n

n^{2}

**Answer: n-1**

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q7. How many pairs of adjacent elements are compared in a single pass of the bubble sort algorithm?**

n

n-1

n/2

2n

**Answer: n-1**

**Q8. The following steps are required to implement the binary search for an array sorted in ascending order.Which steps would require modification if the array were sorted in descending order?**

Step 2

Step 4

Steps 2 and 4

No modification in steps

**Answer: Step 4**

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q9. Select the correct statements among the following**

A. In the presence of duplicate elements in a list, binary search always finds the first occurrence of the element in the list

B. In the presence of duplicate elements in a list, binary search may or may not find the first occurrence of the element in the list

C. In the presence of duplicate elements in a list, the existing binary search algorithm with minor modifications can be used to find the first occurrence of the target element in the list

D. In the presence of duplicate elements in a list , the existing binary search can be used to find any kth(k can be any number from 1 to number of times the element has been repeated) of target element in the list

**Answer: B, C**

**Q10. Swapping of two numbers is an intermediate step in any sorting algorithm, In the lecture we use a temporary variable to swap two elements in the list.Can swapping of two numbers be done without using a temporary variable?**

Yes

No

Depends on size of list

Depends on nature of elements in the list

**Answer: Yes**

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**The Joy of Computing using Python Programming Assignment**

**Question 1**

**Write a function insert that accepts a sorted list L of integers and an integer x as input. The function should return a sorted list with the element x inserted at the right place in the input list. The original list should not be disturbed in the process.**

**The only built-in methods you are allowed to use are append and remove. You should not use any other method provided for lists.****You do not have to accept input from the user or print output to the console. You just have to write the function definition.**

**Solution:**

```
def insert(L, x):
"""
insert an element x into a sorted list L
Arguments:
L: list
x: integers
Return:
sorted_L: list
"""
M=L[::]
M.append(x)
return(sorted(M))
```

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 2**

**Accept a sequence of words as input. Create a dictionary named real_dict whose keys are the letters of the English alphabet. For each key (letter), the corresponding value should be a list of words that begin with this key (letter). For any given key, the words should be appended to the corresponding list in the order in which they appear in the sequence. You can assume that all words of the sequence will be in lower case.You do not have to print the output to the console.**

**Solution:**

```
words=input().split(",")
#print("words is ",words)
real_dict={}
k=list("abcdefghijklmnopqrstuvwxyz")
for w in words:
if w[0] not in real_dict:
real_dict[w[0]]=[w]
else:
real_dict[w[0]].append(w)
```

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 3**

**Consider a grid-world of size n×n. You are at the bottom-left corner, at the cell (1,1), to start with. A sample grid-world for the case of n=5 is given below for your reference:**

**You can move one step at a time in any one of the four directions: “North”, “East”, “West”, “South”. At every cell of the grid, all four moves are possible. The only catch is that if you make a move that will take you out of the grid at a border cell, you will stay put at the same cell. Concretely, if you are at the cell (1,4) and try to move west, you will remain at the same cell. Or if you are at (3,1) and try to move south, you will remain there.**

**Write a function named final that accepts a positive integer n and a sequence of moves (string) as arguments and returns the final position where you would end up in an n×n grid-world if you start at (1,1). You must return a tuple of size 2, where the first element is the x-coordinate and the second is the y-coordinate.**

You do not have to accept input from the user or print output to the console. You just have to write the function definition.

**Solution:**

```
def final(n, moves):
x, y = 1, 1 # Starting position at (1,1)
for move in moves:
if move == "N" and y < n:
y += 1
elif move == "E" and x < n:
x += 1
elif move == "S" and y > 1:
y -= 1
elif move == "W" and x > 1:
x -= 1
return (x, y)
```

**For answers or latest updates join our telegram channel: Click here to join **

**These are the Joy of Computing using Python Assignment 5 Answers**

More Weeks of The Joy of Computing Using Python: Click here

More Nptel Courses: Click here

**Session: JULY-DEC 2023**

**Course Name: The Joy of Computing using Python**

**Course Link: Click Here**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q1. Which is the fastest sorting algorithm?**

Bubble Sort

Bucket Sort

Quick Sort

Insertion Sort

**Answer: Quick Sort**

**Q2. How can you remove all items from a dictionary?**

dict.clear()

del dict

dict.remove_all()

dict.pop()

**Answer: dict.clear()**

**Q3. What happens if you try to add a new key to a dictionary that already exists?**

The key and its associated value will be updated.

The key and its associated value will be added.

The key will be added, but the associated value will remain unchanged.

An error will occur.

**Answer: The key and its associated value will be updated.**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q4. Which of the following is true about dictionaries?**

There can be multiple same keys.

Every value must be unique.

Every key must be unique.

We can’t get every key from the dictionary.

**Answer: Every key must be unique.**

**Q5. What is the syntax to create a dictionary?**

D = []

D = {}

D = ()

D = dictionary()

**Answer: D = {}**

**Q6. What will be the output of the following code?**

‘a’ ‘b’ ‘c’

20 30 50

(‘a’, 20), (‘b’, 30), (‘c’, 50)

(‘a’, ‘b’, ‘c’) (20, 30, 50)

**Answer: (‘a’, 20), (‘b’, 30), (‘c’, 50)**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q7. In the Monte Hall Problem, what is the probability of winning if you switch doors after the host reveals a goat behind one of the other doors?**

1/3

1/2

2/3

3/4

**Answer: 2/3**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q8. In the Monte Hall Problem, what is the probability of winning if you do not switch doors after the host reveals a goat behind one of the other doors?**

1/3

1/2

2/3

3/4

**Answer: 1/3**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q9. What is the name of the game show that the Monte Hall Problem was based on?**

Jeopardy

Wheel of Fortune

The Price is Right

Let’s Make a Deal

**Answer: Let’s Make a Deal**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q10. Which module in Python can be used for Speech to Text conversion?**

SpeechRecognition

PyAudio

Wave

all of the above

**Answer: SpeechRecognition**

**These are the Joy of Computing using Python Assignment 5 Answers**

**The Joy of Computing using Python Programming Assignmnet**

**Question 1You are given a string S. Write a function count_letters which will return a dictionary containing letters (including special character) in string S as keys and their count in string S as values.(input and output will be handled by us you just need to write the function and return the dictionary)InputThe Joy of computing**

**Output{‘T’: 1, ‘h’: 1, ‘e’: 1, ‘ ‘: 3, ‘j’: 1, ‘o’: 3, ‘y’: 1, ‘f’: 1, ‘c’: 1, ‘m’: 1, ‘p’: 1, ‘u’: 1, ‘t’: 1, ‘i’: 1, ‘n’: 1, ‘g’: 1}Explanation: T is appeared once in the string, similarly o is appeared 3 times in the string and so on. (You do not have to worry about the order of arrangement in your dictionary)**

**Solution:**

```
def count_letters(S):
ans = {}
for j in S:
if j in ans:
ans[j] += 1
else:
ans[j] = 1
return(ans)
```

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 2You are given a list L. Write a function uniqueE which will return a list of unique elements is the list L in sorted order. (Unique element means it should appear in list L only once.)Input will be handled by usInput[1,2,3,3,4,4,2,5,6,7]Output[1,5,6,7]ExplanationElements 1,5,6,7 appears in the input list only once.**

**Solution:**

```
def uniqueE(L):
ans=list()
for a in L:
if L.count(a)==1:
ans.append(a)
return(sorted(ans))
```

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 3You are given a list L. Write a program to print first prime number encountered in the list L.(Treat numbers below and equal to 1 as non prime)Input will be handled by us.Input[1,2,3,4,5,6,7,8,9]output2ExplanationSince 2 is the first prime number is list L, therefor it is printed.**

**Solution:**

```
prime=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, 211, 223, 227, 229, 233, 239, 241, 251,
257, 263, 269, 271, 277, 281, 283, 293, 307, 311]
for j in L:
if j in prime:
print(j,end="")
break
```

**These are the Joy of Computing using Python Assignment 5 Answers**

More Weeks of The Joy of Computing Using Python: Click here

More Nptel Courses: Click here

**Session Jan-Apr 2023**

**Course Name: The Joy of Computing using Python**

**Course Link: Click Here**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q1. Binary search can be applied on ***_*.

a. Sorted list

b. Unsorted list

c. Both A and B

d. Any list with any elements

*_*.

**Answer: a. Sorted list**

**Q2. Which of the following is a Waveform Audio File Format.**

a. Wav

b. Wave

c. Wv

d. Waves

**Answer: a, b**

**Q3. Which of the following libraries can help us to convert audio into lyrics?**

a. speech_recognition

b. text_to_speech

c. speech_to_text

d. text_translate

**Answer: a. speech_recognition**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q4. State True or False: In the monte hall problem, swapping the choice does not increase the chance of winning. (For the large number of experiments)**

a. Swapping will decrease the chance of winning.

b. Swapping will increase the chance of winning.

c. Swapping will not affect the chance of winning.

d. Swapping may or may not increase the chance of winning.

**Answer: b. Swapping will increase the chance of winning.**

**Q5. What is the correct way to initialize a dictionary?**

a. D = {a-10, b-20, c-30}

b. D = {‘a’-10, ‘b’-20, ‘c’-30}

c. D = {a:10, b:20, c:30}

d. D = {‘a’:10, ‘b’:20, ‘c’:30}

**Answer: d. D = {‘a’:10, ‘b’:20, ‘c’:30}**

**Q6. What is the correct syntax to get all the keys only from a dictionary d?**

a. d.key()

b. d.item()

c. d.value()

d. d.keys()

**Answer: d. d.keys()**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q7. Which of the following is valid?**

a. D = {‘a’: {‘a’: 10}, ‘b’: 10}

b. D = {‘a’: ‘a’: 10, ‘b’: 10}

c. D = {‘a’: {‘a’: 10}, ‘b’: {‘b’: 10}}

d. D = {‘a’: ‘a’: 10, ‘b’: ‘b’: 10}

**Answer: a, c**

**Q8. For bubble sort, which of the following statements is true?**

a. If the list is sorted, the algorithm won’t work.

b. In each iteration consecutive pairs of elements are compared with each other.

c. Every element is compared with every other element in the list in each iteration.

d. Swapping never happens in bubble sort.

**Answer: b. In each iteration consecutive pairs of elements are compared with each other.**

**Q9. Which error is faced while accessing an element that is not there in a dictionary?**

a. KeyError

b. IndexError

c. RunTimeError

d. ValueError

**Answer: a. KeyError**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q10. In dictionaries, d.items() will return _**

a. Pairs of all (key, value) together.

b. All (keys) and (values) separately.

c. All (values) and (keys) separately.

d. Pairs of all (value, key) together.

**Answer: a. Pairs of all (key, value) together.**

**The Joy of Computing using Python Programming Assignmnet**

**Question 1**

**write a Python program that finds the Greatest Common Divisor (GCD) of two numbers. Your program should take two input numbers from the user, and use a function named ‘gcd’ to find the GCD of those two numbers. Your program should then print out the GCD of the two numbers as the output.**

**Solution:**

```
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
num1 = int(input())
num2 = int(input())
result = gcd(num1, num2)
print(result)
```

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 2**

**Write a Python program that calculates the dot product of two lists containing the same number of elements. The program should take two lists of integers as input from the user, and then call a function named dot_product to find the dot product of the two lists. The dot_product function should take two lists a and b as input, and should return the dot product of those two lists.**

**Your program should first prompt the user to enter the two lists of integers, which should be entered as strings separated by spaces. Your program should then convert the input strings into lists of integers. Your program should then call the dot_product function with the two lists as arguments, and store the resulting dot product in a variable named result. Finally, your program should print out the dot product of the two lists as the output.**

**You can assume that the two input lists will always contain the same number of elements. Your program should output an error message and exit gracefully if the two lists have different lengths.In your implementation, you should define the dot_product function using a loop to calculate the dot product of the two input lists.**

**Solution:**

```
def dot_product(a, b):
if len(a) != len(b):
print("Error: the two input lists have different lengths.")
return None
else:
result = 0
for i in range(len(a)):
result += a[i] * b[i]
return result
# Get input from user
a_str = input()
b_str = input()
# Convert input strings to lists of integers
a = [int(x) for x in a_str.split()]
b = [int(x) for x in b_str.split()]
# Calculate dot product
result = dot_product(a, b)
# Output result
if result is not None:
print(result)
```

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 3**

**Write a Python function that takes a string s as input and returns the length of the largest streak of 0s in the string. For example, if the input string is “10001000110000000001”, the function should return 6.**

**Input The input string s is guaranteed to contain only 0s and 1s.OutputThe function should return an integer, representing the length of the largest streak of 0s in the input string.Your program should also print the result.**

**Solution:**

```
def max_zero_streak(s):
max_streak = 0
current_streak = 0
for digit in s:
if digit == '0':
current_streak += 1
if current_streak > max_streak:
max_streak = current_streak
else:
current_streak = 0
return max_streak
s = input()
result = max_zero_streak(s)
print(result)
```

**These are the Joy of Computing using Python Assignment 5 Answers**

More Weeks of The Joy of Computing using Python: Click Here

More Nptel courses: https://progiez.com/nptel-assignment-answers/

**Session JUL-DEC 2022**

**Course name: The Joy of Computing Using Python**

Link to Enroll: Click here

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q1. What is the correct way to initialize a dictionary?**

a. D = {a-10, b-20, c-30}

b. D = {‘a’-10, ‘b’-20, ‘c’-30}

c. D = {a:10, b:20, c:30}

d. D = {‘a’:10, ‘b’:20, ‘c’:30}

**Answer: d**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q2. What is the correct syntax to get all the keys only from a dictionary d?**

a. d.key()

b. d.item()

c. d.value()

d. d.keys()

**Answer: d**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q3. Which of the following statements are true about dictionaries in python?**

a. The keys of a dictionary must be unique values.

b. The keys of a dictionary can or cannot be unique.

c. The values of a dictionary must be unique values.

d. The values of a dictionary can or cannot be unique.

**Answer: a, d**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q4. State True or False: In the monte hall problem, swapping the choice does not increase the chance of winning.**

a. True

b. False

**Answer: b**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q5. In dictionaries, d.items() will return**

a. Pairs of all (key, value) together.

b. All (keys) and (values) separately.

c. All (values) and (keys) separately.

d. Pairs of all (value, key) together.

**Answer: a**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q6. What will be the output of the following program?**

a. A dictionary with all letters as keys and 0 as values.

b. A dictionary with some letters as keys and 0 as values.

c. A dictionary with all letters as keys and some random numbers as values.

d. A dictionary with some letters as keys and some random numbers as values.

**Answer: d**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q7. Binary search can be applied on ___.**

a. Sorted list in ascending order.

b. Unsorted list

c. Both A and B

d. Sorted list in descending order

**Answer: a, d**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q8. Which error is encountered while accessing a position that is not present in a list**

a. KeyError

b. IndexError

c. RunTimeError

d. ValueError

**Answer: b**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q9. Which of the following command is correct to delete a key from a dictionary ‘d’**

a. d.pop(‘key’)

b. d.del(‘key’)

c. d.remove(‘key’)

d. d.delete(‘key’)

**Answer: a**

**These are the Joy of Computing using Python Assignment 5 Answers**

**Q10. Which of the following is/are correct regarding dictionaries?1) One can make a dictionary inside a dictionary in python.2) Keys in the dictionary are mutable.**

a. Option 1 is correct, option 2 is correct. Option 2 is the correct explanation for option 1.

b. Option 1 is correct, option 2 is incorrect. Option 2 is not the correct explanation for option 1.

c. Option 1 is correct, option 2 is correct. Option 2 is not the correct explanation for option 1.

d. None of these

**Answer: b**

**These are the Joy of Computing using Python Assignment 5 Answers**

## Python Assignment 5 Programming Solutions

**Question 1You are given a string S. Write a function count_letters which accepts the string S and returns a dictionary containing letters (including special character) in string S as keys and their count in string S as values.(input and output is handled by us, you just need to write the function and return the dictionary)InputThe Joy of computingOutput{‘T’: 1, ‘h’: 1, ‘e’: 1, ‘ ‘: 3, ‘j’: 1, ‘o’: 3, ‘y’: 1, ‘f’: 1, ‘c’: 1, ‘m’: 1, ‘p’: 1, ‘u’: 1, ‘t’: 1, ‘i’: 1, ‘n’: 1, ‘g’: 1}**

**Solution:**

```
def count_letters(S):
d={}
for i in S:
d[i]=0
for i in S:
d[i]+=1
return d
if __name__ == "__main__":
S = input()
d = count_letters(S)
#~~~THERE IS SOME INVISIBLE CODE HERE~~~
```

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 2You are given a list L. Write a function uniqueE which will return a list of unique elements is the list L in sorted order. (Unique element means it should appear in list L only once.)Input is handled by us.Input[1,2,3,3,4,4,2,5,6,7]Output[1,5,6,7]ExplanationElements 1,5,6,7 appears in the input list only once.**

**Solution:**

```
def uniqueE(L):
d = {}
for i in L:
d[i]=0
for i in L:
d[i]+=1
res = []
for key, value in d.items():
if value==1:
res.append(key)
res.sort()
return res
L = [int(i) for i in input().split()]
print(uniqueE(L))
```

**These are the Joy of Computing using Python Assignment 5 Answers**

**Question 3You are given a list L. Write a program to print first prime number encountered in the list L.(Treat numbers below and equal to 1 as non prime)Input is handled by us.Input[1,2,3,4,5,6,7,8,9]output2ExplanationSince 2 is the first prime number is list L, therefor it is printed.**

**Solution:**

```
#~~~THERE IS SOME INVISIBLE CODE HERE~~~
def isprime(num):
if num<=1:
return False
if num==2:
return True
for i in range(3,num-1):
if num%i == 0:
return False
return True
for k in L:
if isprime(k):
print(k,end="")
break
else:
continue
```

**These are the Joy of Computing using Python Assignment 5 Answers**

More NPTEL Solution: https://progiez.com/nptel

The content uploaded on this website is for reference purposes only. Please do it yourself first. |