Data Processing and Visulisation with Python
Python Exercise 8
Factorial
Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument.
def factorial(n):
#-----------------Your code----------------
#---------------End of you code------------
answer
def factorial(n):
if n == 0 or n == 1:
return 1
else :
return n * factorial(n-1)
m = int(input('Please input the last two digits of your student ID: '))
print(f'{m}!={factorial(m)}')
Max of four
Write a Python function to find the Max of four numbers.
def max2(a, b):
#-----------------Your code----------------
#---------------End of you code------------
def max4(a, b, c, d):
#-----------------Your code----------------
#---------------End of you code------------
answer
def max2(a, b):
if a>=b:
return a
else:
return b
def max4(a, b, c, d):
if a>=b and a>=c and a>=d :
return a
elif b>=a and b>=c and b>=d:
return b
elif c>=a and c>=b and c>=d:
return c
else:
return d
print('Please input four numbers:')
w = float(input('w='))
x = float(input('x='))
y = float(input('y='))
z = float(input('z='))
print("Max of four is:", max4(w, x, y, z))
In range
Write a Python function to check whether a number x is in a given range [start, end].
def testRange(x, start, end):
#-----------------Your code----------------
#---------------End of you code------------
answer
def testRange(x, start, end):
if x<=end and x>=start:
return True
else:
return False
a = float(input('Please input the number to check: '))
m = float(input('Please input the lower bound of the interval: '))
n = float(input('Please input the upper bound of the interval: '))
print(f"{a} {'is' if testRange(a, m, n) else 'is not'} in range [{m}, {n}].")
Prime or not
Write a Python function that takes an integer number (>=2) as a parameter and checks if the number is prime or not.
def isPrime(n):
#-----------------Your code----------------
#---------------End of you code------------
answer
def isPrime(n):
from math import sqrt
count = 0
sqrt_n = int(sqrt(n))
for i in range(2,sqrt_n+1):
if n % i == 0:
count = count + 1
if count == 0:
return True
m = int(input('Please input the first four digits of your student ID: '))
print(f"{m} {'is' if isPrime(m) else 'is not'} a prime.")
another method
#Q4
def isPrime(n):
for j in range(2,int(n**0.5)+1):
if n%j == 0:
return False
else:
return True
##注意此时的else缩进位置
m = int(input('Please input the first four digits of your student ID: '))
print(f"{m} {'is' if isPrime(m) else 'is not'} a prime.")
Palindrome number
Write a Python function to test if a 5-digit-integer (in [10000, 99999]) is a palindrome number. Then write a Python program to input a positive integer between 10000 and 99999, call the function of yours and print if that integer is a palindrome number.
have problem
def tenet(m):
from math import ceil
n=str(m)
k=len(n)
for i in range(ceil(k/2)):
if n[i] == n[-1-i]:
return True
m = int(input("Please input an integer between 10000 and 99999:"))
print(f"{m} {'is' if tenet(m) else 'is not'} a palindrome number.")
right anwser 1
def tenet(m):
from math import ceil
n=str(m)
k=len(n)
for i in range(ceil(k/2)):
if n[i] != n[-1-i]:
return False
else:
return True
right anwser 2
def func1(n):
if (n%10==n//10000) and (n%100//10==n//1000%10):
return True
else:
return False
m = int(input("Please input an integer between 10000 and 99999:"))
print(f"{m} {'is'if func1(m)==True else 'is not'} a palindrome number.")
Perfect number
Write a Python function to check whether a positive integer is perfect or not. Then write a Python program to test your function.
Note:
According to Wikipedia : In number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).
Example : The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.
answer 1
def pn(m):
divisors=[]
for i in range(1,m+1):
if m % i == 0:
divisors.append(i)
s=sum(divisors)
if m == s/2 :
return True
m = int(input("Please input a positive integer:"))
print(f"{m} {'is' if pn(m) else 'is not'} a perfect number.")
answer 2
def isPerfect(n):
x=int(n)
s=0
for i in range(1,x+1):
if x%i==0:
s+=i
else:
s+=0
if x==s/2:
print(n,"is a perfect number.")
else:
print(n,"is not a perfect number.")
n=input("Please input a positive integer: ")
isPerfect(n)
Digital triangle
Write a Python function (with parameter between 1 and 9) to construct the following pattern, using a nested loop number.
Expected Output – when parameter is 7:
1
22
333
4444
55555
666666
7777777
answer
def digitriangle(m):
for i in range(1,m+1):
print(f"{i}"*i )
digitriangle(9)
Reversed number
Write a Python function which gets a positive integer from caller and return a number in reverse.
For example: when 123456 is sent as a parameter to the function, 654321 will be returned.
answer 1
def reverseNumber(n):
n = str(n)
m = ""
for i in range(1,len(n)+1):
m = m + n[-i]
return int((m))
x = int(input('Please input the decimal part of the start datetime of this exercise: '))
reverseNumber(x)
answer 2
def reverseNumber(n):
r = 0
for i in range(1,len(str(n))+1):
k = n%(10**i)//(10**(i-1))
r += k*(10**(len(str(n))-i))
return r
x = int(input('Please input the decimal part of the start datetime of this exercise: '))
reverseNumber(x)
answer 3
def reverseNumber(x):
i = 0
while x != 0:
i = i*10 + x%10
x = int(x/10)
return i
x = int(input('Please input the decimal part of the start datetime of this exercise: '))
reverseNumber(x)
Greetings
Write a Python function named “greetings” to take two parameters, one greeting with default value of “Happy New Year”, one name with default of “everyone”, then print out the greeting followed by name.
answer
def greetings(word = "Happy New Year" , name = "everyone"):
print(word,name)
greetings()
greetings("Happy Christmas")
greetings("Happy birthday","John")
greetings(name='Tom')
Variance
Write a Python function to take arbitrary number of float arguments and return their variace. If no float passed, then return 0.0
Hint:
A tuple can be accessed as a list, and the number of elements in tuple t can be returned from len(t).
answer1
def variance(*values ):
l=len(values)
if l == 0 :
var = 0.0
else:
s1 = sum(values)
i_square=[]
for i in values:
i_square.append(i**2)
s2 = sum(i_square)
e1=(s1/l)**2
e2=s2/l
var=e2-e1
return var
print(variance(5,6,7,8,9))
print(variance(5,5))
print(variance())
answer2
def variance(*value):
if len(value) == 0 :
v = 0.0
return v
else:
mean = sum(value)/len(value)
v = 0
for i in range(len(value)):
vi = (value[i]-mean)**2
v += vi
return v/len(value)
print(variance(5,6,7,8,9))
print(variance(5,5))
print(variance())