Tutorial 8 Worksheet
COMP1117B Computer Programming I 2024 - 2025
Tutorial objectives:
• To practice the use of bracket/index operator.
• To practice the use of string methods.
Deadline: 11:59 pm, April 28, 2025
•
Exercise 8.1 Last word of input
Write a program that reads in a string s and then prints the last word in s.
Note:
1. The input string can contain letters, numbers, spaces, and period symbols. The last word
should only contain letters. You may need to remove the unnecessary symbol (e.g. period
symbol) in the word.
2. You do not need to consider the last part is number.
Input Expected Output
Hello world. world
This item sells for 55610 HKD. HKD
This is an example example
Exercise 8.2 Max number in input
Write a program to read a line of digit-strings separated by comma and print the max number in
them.
Input Expected Output
123,456,879,100 879
1,2,3,45,678,50,-4 678
8,9,10,4,8 10
Exercise 8.3 Count characters
Write a program to read a line of string input, count the occurrences of each character in this
string, and print the corresponding count dictionary.
Note: The order of the keys in the count dictionary should match the order that first occurred in the
input string.
Input Expected Output
hello {'h': 1, 'e': 1, 'l': 2, 'o': 1}
banada {'b': 1, 'a': 3, 'n': 1, 'd': 1}
Exercise 8.4 Check credit card number
Write a program to read a line of credit card number separated by space and use the ‘Luhn
Algorithm’ to check if the card number is valid.
Note: This is not exactly the same in the real world. For this exercise, we need to check if the
check digit is right. The check digit is computed as follows:
1. Cut off the check digit (last digit) of the number to validate.
2. Calculate the check digit
a) Take the original number and start from the rightmost digit moving left, double the value of
every second digit (including the rightmost digit).
b) Replace the resulting value at each position with the sum of the digits of this position's value.
c) Sum up the resulting values from all positions as s.
d) The calculated check digit is equal to ‘10 – s mod 10’.
3. Compare your result with the check digit you cut off. The card number is valid when these two
numbers are the same.
Luhn algorithm: https://en.wikipedia.org/wiki/Luhn_algorithm
Input Expected Output
5190 9902 8192 5290 Invalid
6823 1198 3424 8189 Valid
3716 8200 1927 1998 Valid