Assignment 3
Assignment 3
Section 5
Compiled By:
pg. 1
Assignment 1
1. Checking if a word is palindrome. You need to write a program that uses loop to
check if a given string is a palindrome.
E.g. The word noon is a palindrome. A palindrome have the same spelling in
reverse.
CODE 1:
def is_palindrome(word):
word = word.lower()
reversed_word = ""
Explanation:
1. First, I converted the input word to lowercase using word.lower(). This ensures that the
palindrome check is not affected by case differences.
2. Second, I initialized an empty string reversed_word that will store the reverse of the input
word.
3. Then, I used a for loop to go through each character in the word. Each character is added
to the front of reversed_word, which constructs the reverse of the input word.
4. After that, I compared the original word with the reversed_word. If both are the same, it
means the word is a palindrome.
5. Finally, the function returns True if the word is a palindrome, or False otherwise.
2. This question includes a reading assignment. Read about dictionary from your
text book. The program you are going to write below counts the words in a given
string where the key is the word and the value is the frequency of the word in the
sentence.
Eg. I ate an apple.
{
“I”:1,
“ate”: 1
“an”: 1
“apple”: 1
CODE 2:
def word_count(sentence):
pg. 2
words = sentence.split()
word_freq = {}
return word_freq
Explanation:
1. First, I split the sentence into individual words using the split() function, which breaks the
sentence into a list of words based on spaces.
2. Second, I initialized an empty dictionary word_freq to store the frequency of each word as
the key-value pair.
3. Then, I used a for loop to iterate through each word in the list. For each word:
If the word already exists in the dictionary, I increment its count by 1.
If the word is not in the dictionary, I add it with a value of 1.
4. Finally, after processing all words, I return the word_freq dictionary, which contains each
word and its corresponding count.
3. Write a program that removes stop words such as the, is, an, a, and so on. From a
string. Use this link (https://countwordsfree.com/stopwords) to use at least 10
stop words that you are going to remove the string.
Note: The use of external packages such as NLTK is not allowed
CODE 3:
def remove_stop_words(sentence):
stop_words = ["the", "is", "in", "on", "a", "an", "of", "and", "or",
"to"]
words = sentence.split()
filtered_sentence = []
pg. 3
return " ".join(filtered_sentence)
Explanation:
1. First, I defined a list stop_words containing at least 10 common stop words that I want to
remove from the sentence. These words include articles and conjunctions like "the", "is", "a",
etc.
2. Second, I split the input sentence into individual words using the split() function, storing them in
a list called words.
3. Then, I initialized an empty list filtered_sentence to store the words that are not stop words.
4. After that, I used a for loop to iterate over each word in the words list. I checked if the word
(converted to lowercase) is not in the stop_words list. If it's not, I added the word to
filtered_sentence.
5. Finally, I joined the filtered words back together using " ".join(filtered_sentence) to form the
final sentence, and returned this string without the stop words.
Assignment 2
1. Write a python program that accepts a positive number and prints the sum of
the digits in the number. i.e. if the number is 576, it should print 18 = 5 + 7 + 6.
CODE 1:
def sum_of_digits(number):
total = 0
while number > 0:
digit = number % 10
total += digit
number = number // 10
print(total)
Explanation:
1. First, I initialized a variable total to 0, which will be used to store the sum of the digits.
2. Second, I used a while loop that continues as long as the number is greater than 0.
3. Then, inside the loop, I extracted the last digit of the number by using the modulus
operator (% 10) and added it to total.
4. After that, I removed the last digit from the number by dividing it by 10 and using
integer division (// 10).
5. Finally, when the loop finishes (i.e., when all digits are processed), I printed the sum of
the digits stored in total.
2. Write a python program that accepts a number and prints the sum of its
factors.
pg. 4
CODE 2:
def sum_of_factors(number):
total = 0
for i in range(1, number + 1):
if number % i == 0:
total += i
print(total)
Explanation:
1. First, I initialized a variable total to 0 to store the sum of the factors.
2. Second, I used a for loop to iterate through every integer from 1 to the given number.
3. Then, I checked if each integer i is a factor of the given number by checking if number % i
== 0. If it is, I added i to total.
4. After that, the loop continues until all factors are found.
5. Finally, I printed the sum of the factors stored in total.
3. Write a python program that generates a random number in the range 0 to 100
and prompts the user to guess and enter the number continuously until the
user’s input matches the randomly generated number. The program should
inform the user if his/her guess is less/more than the random number. if the
user can't guess the value by entering at most 7 guesses the program should
print GAME OVER
CODE 3:
import random
def guessing_game():
number = random.randint(0, 100)
attempts = 0
max_attempts = 7
pg. 5
print("GAME OVER. The correct number was", number)
Explanation:
1. First, I used the random.randint() function to generate a random number between 0 and
100 and stored it in the variable number.
2. Second, I initialized a variable attempts to 0, which keeps track of how many guesses the
user has made.
3. Then, I set max_attempts to 7, which is the maximum number of guesses allowed.
4. After that, I used a while loop that continues as long as the number of attempts is less
than 7.
Inside the loop, I prompted the user to input their guess and compared it with
the generated number.
If the guess is lower than the number, the program prints "Your guess is too
low!".
If the guess is higher than the number, the program prints "Your guess is too
high!".
If the guess matches the number, the program prints a success message and
exits.
5. Finally, if the user fails to guess the number in 7 attempts, the program prints "GAME
OVER" and reveals the correct number.
Assignment 3
1. Write function exclamation() that takes as input a string and returns it with this
modification: Every vowel is replaced by four consecutive copies of itself and an
exclamation mark (!) is added at the end.
>>> exclamation('argh')
'aaaargh!'
>>> exclamation('hello')
'Heeeelloooo!'
CODE 1:
def exclamation(input_str):
vowels = "aeiouAEIOU"
result = ""
for char in input_str:
if char in vowels:
result += char * 4
pg. 6
else:
result += char
return result + "!"
Explanation:
2. An inversion in a sequence is a pair of entries that are out of order. For example,
the characters F and D form an inversion in string 'ABBFHDL' because F appears
before D; so do characters H and D. The total number of inversions in a sequence
(i.e., the number of pairs that are out of order) is a measure of how unsorted the
sequence is. The total number of inversions in 'ABBFHDL' is 2. Implement
function inversions () that takes a sequence (i.e., a string) of uppercase characters
A through Z and returns the number of inversions in the sequence.
>>> inversions('ABBFHDL')
2
>>> inversions('ABCD')
0
>>> inversions('DCBA')
6
CODE 2:
def inversions(sequence):
count = 0
for i in range(len(sequence)):
for j in range(i + 1, len(sequence)):
if sequence[i] > sequence[j]:
count += 1
return count
pg. 7
Explanation:
1. First, I initialized a variable count to track the number of inversions.
2. Then, I used two loops to compare every character in the sequence with the characters
that follow it.
3. If a character was greater than the one following it, it meant they were out of order, so I
increased the count.
4. After checking all the pairs, I returned the total number of inversions.
3. Elevator
An elevator is given an input code which it then uses to go up or down floors:
"^" = go up one floor "v" (lower-case v) = go down one floor. The elevator starts
on floor 0.
Write a generic program that determines the where the lift will end up given a
string input.
Example input
"^v^^v^^vv^vv^vv^^vvv^^v^^^vv^^^vv^v^^vvv^^^^^v^v^v^v^vv^^vvv^^^^vvv
^^vvv^^^^^vvvv^^vvv^vv^^vv^vv^v^^^"
CODE 3:
def elevator(input_code):
floor = 0
for char in input_code:
if char == "^":
floor += 1
elif char == "v":
floor -= 1
return floor
Explanation:
1. First, I initialized a variable floor to represent the starting position (0).
2. Then, I looped through each character in the input code:
* if the character was “^”, I increased the floor by 1
* if the character was “v”, I decreased the floor by 1
3. After processing the entire string, I returned the final floor value, indicating where the
elevator ended up.
pg. 8
4. Write a program that finds an integer between 1 and 10000 that has the largest
number of divisors, and how many divisors does it have?
CODE 4:
def max_divisors():
max_div_count = 0
num_with_max_div = 0
for i in range(1, 10001):
div_count = 0
for j in range(1, i + 1):
if i % j == 0:
div_count += 1
if div_count > max_div_count:
max_div_count = div_count
num_with_max_div = i
return num_with_max_div, max_div_count
Explanation:
1. First, I initialized two variables: max_div_count to track the highest divisor count, and
num_with_max_div to store the number with the most divisors.
2. I looped through numbers from 1 to 10,000.
3. For each number, I counted how many divisors it had by checking every number from 1
to itself.
4. If the divisor count was higher than the current maximum, I updated both max_div_count
and num_with_max_div.
5. Finally, I returned the number with the most divisors and the total number of divisors it
had.
pg. 9