Coursera Solutions coming soon!

Unit 2 - Lesson 5

19.1.1. Understand the For-loop construct

numbers = [int(x) for x in input().split()]
s = 0
#Find sum of all the numbers using for loop 
for  x in numbers   :
	s += x

print("sum:", s) # print the sum here

colors = [x for x in input().split()]
print("colors:")
#iterate over the given colors and print them individually
for x in colors    :
	print(x)

19.1.2. Using range function with For loop

#take the input num from the user
n = int(input("num: "))
#genarate and print the alternate elements from 1 to n alternatively using for loop
for i in range(1,n+1,2):
	print(i)

19.1.3. For loop with else

# Multiplication table
x = int(input("x: "))
y = int(input("y: "))

# Fill in the missing code below to print a multiplication table for x upto y rows.
# If y is more than 20, print the relevant message as per instructions and limit the number of rows to 20
for i in range(1, y+1 ):
	print(f"{x} * {i} = {x*i}")
	if(i>=20):
		print("rows is limited to 20")
		break

19.1.4. Write a program for Matrix Transposition using Nested For loops

r = int(input("rows: "))
c = int(input("columns: "))
matrix = []
print("row wise elements:")
for i in range(r):
	li = list(map(int, input().split()))
	matrix.append(li)
print("original matrix:",matrix)
#write you code to find the transpose

transposed = []
for i in range(len(matrix[0])):
	transposed_row = []
	for row in matrix:
		transposed_row.append(row[i])
	transposed.append(transposed_row)

#print the transposed matrix
print("Transposed matrix:", transposed)

19.1.5. Write a program to check a given number is perfect number

n = int(input("n: "))
i = 1
list1=[]
while i<n:
	if(n%i==0):
		list1.append(i)
	i += 1
print("factors:", list1)
s = 0
for i in list1:
	s += i
if(s == n):
	print("perfect number")
else:
	print("not perfect number")

19.1.6. Write a program to print the value of Pi to 25 decimal places

import math
pi = math.pi

# write your code here
n = int(input("n: "))
for i in range(1,n+1):
	print(f'%.{i}f'%pi)

19.1.7. Write a program to check the given String is valid expression or not.

s = input("str: ")
if s.count("(")==s.count(")"):
	print("valid and depth:",s.count("("))
else:
	a=s.count("(")-s.count(")")
	if a>0:
		print("not valid and errors:",a)
	else:
		print("not valid and errors:",-a)

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.