1. Write a Python program to check whether a given number is a narcissistic number or not.
For example, 371 is a narcissistic number; it has three digits, and if we cube each digits 33 + 73 + 13 the sum is 371.
Other 3-digit narcissistic numbers are
153 = 13 + 53 + 33
370 = 33 + 73 + 03
407 = 43 + 03 + 73.
def is_narcissistic_num(num):
return num == sum([int(x) ** len(str(num)) for x in str(num)])
for x in range(100, 1000):
if is_narcissistic_num(x):
print(x)
Result:
153
370
371
407
2. Print a customized calendar.
import calendar
import re
yy = int(input("Enter the year number: "))
mm = int(input("Enter the month number: "))
calendar.setfirstweekday(calendar.SUNDAY)
x = calendar.month(yy, mm, 3)
pattern = rf" {yy}\n"
x = re.sub(pattern, "{}----------------------------\n".format(pattern), x)
print(x)
Result:
Enter the year number: 2023
Enter the month number: 5
May 2023
----------------------------
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Process finished with exit code 0
Ref.
3. Use Python turtle to plot a function.
import turtle as t
def line(x1,y1,x2,y2):
t.up()
t.goto(x1,y1)
t.down()
t.goto(x2,y2)
return
line(0,300,0,0)
line(0,0,300,0)
t.goto(0,0)
t.shape("turtle")
t.color("red")
for x in range(0, 151):
y = pow(x, 2) + 1
t.goto(x, y * 0.01)
t.done()
Result:
4. Replace Python list of blank elements with a specific value (list comprehension)
z_list = ['oriel', 'indifference', '', 'hypomania', '', 'my']
z_list = ['xxx' if x == '' else x for x in z_list]
print(z_list)
5. The prime numbers from 1 to 100
num=0
while num <= 100:
cnt = 0
i = 1
while i<=num:
if num % i == 0:
cnt += 1
i += 1
if cnt == 2:
print(num, end=" ")
num += 1
Result:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97