Unit 4 - Lesson 14

47.1.1. Understanding List Comprehensions

#take a string from the user
str1 = input("str: ")
l1 = [i for i in str1]

#fill in the missing code

print(l1)

47.1.2. Nested List Comprehension

n1 = int(input())
n2 = int(input())

L1 = [a for a in range(n1,n2) if a%2==0 and a%3==0]

#fill in the missing code..

print(L1)

47.1.3. Illustration of Nested List comprehension

m = int(input("Enter N: "))
matrix = [list(map(int,input().split(" "))) for i in range(m)]
print("Original matrix: ")
for i in matrix:
	print(i)
t1 = [[matrix[j][i] for j in range(m)] for i in range(m)]
print("transpose using single list comprehension: ")
transposed = []

#fill in the missing code

for i in transposed:	
	print(i)
for i in t1:
	print(i)

print("transpose using double list comprehension: ")

#fill in the missing code

transposed = [[matrix[j][i] for j in range(m)] for i in range(m)]

for i in transposed:	
	print(i)

47.1.4. Write a program to accept numbers as user input and print the same using list comprehension

list1 = [int(x) for x in input("data: ").split(" ")]

#fill in the missing code..

print("contents:", list1)

Post a Comment