Lab 10 Solutions Extra PDF

Title Lab 10 Solutions Extra
Course Introduction to Programming
Institution Dublin City University
Pages 3
File Size 89.1 KB
File Type PDF
Total Downloads 36
Total Views 146

Summary

This is the solution for the tenth lab exercise session by Professor Qun Liu....


Description

Lab 10 Solutions 1. String sequence to list Write a Python program which accepts a sequence of comma-separated numbers from user and generate a list and a tuple with those numbers. Example: Input: 3, 5, 7, 23 Output : List : ['3', ' 5', ' 7', ' 23'] Tuple : ('3', ' 5', ' 7', ' 23') Solution: inputStr = input("Please, enter the numbers: ") myList = inputStr.split(",") myTuple = tuple(myList) print(myList) print(myTuple)

2. Histogramm Write a Python program to create a histogram from a given list of integers.

Example: Input: 2, 3, 6, 5 Output : ** *** ****** ***** Solution: inputStr = input("Please, enter the numbers: ") myList = inputStr.split(",") for i in myList: intI = int(i) print("*"*intI)

3. Tuple to a dictionary. Write a Python program to convert a tuple to a dictionary. Solution 1: tuplex = ((2, "w"),(3, "r")) print(dict((y, x) for x, y in tuplex))

Solution 2: inputStr = input("Please, enter the numbers: ") myList = inputStr.split(",") t = tuple(myList) d= dict() for i in range(len(t)): d[i] = t[i] print(t) print(d)

4. Replace last value Write a Python program to replace last value of tuples in a list. Go to the editor Example: Sample list: Expected

[(10, 20, 40), (40, 50, 60), (70, 80, 90)] Output: [(10, 20, 100), (40, 50, 100), (70, 80, 100)]

Solution: lastElement = int(input("Please, enter the numbers: ")) # Simplify for short input (can be any list of any tuples) tupleOfLists = [(10, 20, 40), (40, 50, 60), (70, 80, 90)] new_tupleOfLists = [] for t in tupleOfLists: new_t =t[:-1] one_element_tuple = tuple([lastElement]) new_tupleOfLists.append(new_t+one_element_tuple) print (new_tupleOfLists)

5. Lo Shu Magic Square The Lo Shu Magic Square is a grid with 3 rows and 3 columns, shown in Figure 7-8. The Lo Shu Magic Square has the following properties: ● The grid contains the numbers 1 through 9 exactly. ● The sum of each row, each column, and each diagonal all add up to the same number. This is shown in figure: 4

9

2

3

5

7

8

1

6

In a program you can simulate a magic square using a two-dimensional list. Write a function that accepts a two-dimensional list as an argument and determines whether the list is a Lo Shu Magic Square. Test the function in a program.

Solution: See Lab 10 task 5 Solution.pdf...


Similar Free PDFs