티스토리 뷰

6.1 (Math: pentagonal numbers) A pentagonal number is defined as for and so on. So, the first few numbers are 1, 5, 12, 22, .... Write a function with the following header that returns a pentagonal number:

 

def getPentagonalNumber(n):

 

Write a test program that uses this function to display the first 100 pentagonal numbers with 10 numbers on each line.

 

1
2
3
4
5
6
7
8
9
10
11
12
def getPentagonalNumber(n):
    result = n*(3*n-1)//2
    return result
 
def main():
    
    for i in range(1,101):
        print(format(getPentagonalNumber(i),"5d"), end = "  ")
        if i % 10 == 0:
            print()
 
main()
cs

*6.2 (Sum the digits in an integer) Write a function that computes the sum of the digits in an integer. Use the following function header:

 

def sumDigits(n):

 

For example, sumDigits(234) returns 9 (Hint: Use the % operator to extract digits, and the // operator to remove the extracted digit. For instance, to extract 4 from 234, use 234 % 10 To remove 4 from 234, use 234 // 10 Use a loop to repeatedly extract and remove the digits until all the digits are extracted.) Write a test program

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def sumDigits(n):
    sum = 0
    while n != 0 :
        sum += n%10
        n //= 10
 
    return sum
 
def main() :
 
    number = eval(input("Enter the number : "))
    print(sumDigits(number))
 
main()
cs

**6.3 (Palindrome integer) Write the functions with the following headers:

 

# Return the reversal of an integer, e.g. reverse(456) returns

# 654

def reverse(number):

 

# Return true if number is a palindrome

def isPalindrome(number):

 

Use the reverse function to implement isPalindrome. A number is a palindrome if its reversal is the same as itself. Write a test program that prompts the user to enter an integer and reports whether the integer is a palindrome

 

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
def reverse(number):
    result = 0
    while number != 0:
        digit = number % 10
        result = result*10 + digit
        number //= 10
 
    return result
 
def isPalindrome(number):
    if reverse(number) == number :
        return True
 
    else :
        return False
 
def main():
    number = eval(input("Enter the number :"))
    print("reverse number is ",reverse(number))
 
    if isPalindrome(number):
        print(number, " is Palindrome")
    else:
        print(number, " is not palindrome")
 
main()
cs

*6.4 (Display an integer reversed) Write the following function to display an integer in reverse order:

 

def reverse(number):

 

For example, reverse(3456) displays 6543. Write a test program that prompts the user to enter an integer and displays its reversal.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def reverse(number):
    result = 0
    while number != 0:
        digit = number % 10
        result = result*10 + digit
        number //= 10
 
    return result
 
def main():
    number = eval(input("Enter the number :"))
    print("reverse number is ",reverse(number))
 
main()
cs

*6.5 (Sort three numbers) Write the following function to display three numbers in increasing order:

 

def displaySortedNumbers(num1, num2, num3):

 

Write a test program that prompts the user to enter three numbers and invokes the function to display them in increasing order.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def displaySortedNumbers(num1, num2, num3):
    if num1 > num2 :
        num1, num2 = num2, num1
 
    if num1 > num3 :
        num1, num3 = num3, num1
 
    if num2 > num3 :
        num2, num3 = num3, num2
 
    return num1,num2,num3
 
def main():
    n1,n2,n3 = eval(input("Enter three numbers: "))
    print(displaySortedNumbers(n1, n2, n3))
 
main()
cs

*6.6 (Display patterns) Write a function to display a pattern as follows:

    1

             2 1

     3 2 1

...

n n-1 ... 3 2 1

 

The function header is

 

def displayPattern(n):

 

Write a test program that prompts the user to enter a number n and invokes displayPattern(n) to display the pattern.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def displayPattern(n):
    for i in range(0,n+1):
        for space in range(n - i , 0-1):
            print("   ",end="")
 
        for number in range(i, 0-1):
            print(format(number,"3d"), end = "")
 
        print()
            
        
def main():
    number = eval(input("Enter the number : "))
    displayPattern(number)
 
main()
cs

*6.7 (Financial application: compute the future investment value) Write a function that computes a future investment value at a given interest rate for a specified number of years. The future investment is determined using the formula in Exercise 2.19. Use the following function header:

 

def futureInvestmentValue( investmentAmount, monthlyInterestRate, years):

 

For example, futureInvestmentValue(10000, 0.05/12, 5) returns 12833.59.

 

Write a test program that prompts the user to enter the investment amount and the annual interest rate in percent and prints a table that displays the future value for the years from 1 to 30.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
def futureInvestmentValue(investmentAmount, monthlyInterestRate, years):
    print("Years\tFuture Value")
    for i in range(1,years):
        futureValue = investmentAmount * ((1+monthlyInterestRate)**(12*i))
        print(i,"\t",format(futureValue,".2f"))
        
def main():
    investmentAmount = eval(input("The amount invested : "))
    interestRate = eval(input("Annual interest rate : "))
 
    futureInvestmentValue(investmentAmount, interestRate/120030)
 
main()
cs

 6.8 (Conversions between Celsius and Fahrenheit) Write a module that contains the following two functions:

# Converts from Celsius to Fahrenheit

def celsiusToFahrenheit(celsius):

 

# Converts from Fahrenheit to Celsius

def fahrenheitToCelsius(fahrenheit):

 

The formulas for the conversion are:

celsius = (5 / 9) * (fahrenheit – 32)

fahrenheit = (9 / 5) * celsius + 32

 

Write a test program that invokes these functions to display the following tables:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Converts from Celsius to Fahrenheit
def celsiusToFahrenheit(celsius):
    fahrenheit = (9 / 5* celsius + 32
    return fahrenheit
 
# Converts from Fahrenheit to Celsius
def fahrenheitToCelsius(fahrenheit):
    celsius = (5 / 9* (fahrenheit - 32)
    return celsius
 
def main():
    count = 0
    cel = 40.0
    fah = 120.0
 
    print("Celsius\tFahrenheit      |       Fahrenheit\tCelsius")
    while count != 10:
        print(cel,"\t",format(fahrenheitToCelsius(cel),".2"),"     |     ",fah,"\t",fahrenheitToCelsius(fah))
        cel -= 1
        fah -= 10
        count += 1
    
main()
 
cs

6.9 (Conversions between feet and meters) Write a module that contains the following two functions: 

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
# Converts from feet to meters
def footToMeter(foot):
    return 0.305 * foot
    
# Converts from meters to feet
def meterToFoot(meter):
    return meter / 0.305
 
def main():
    count = 0
    feet = 1
    meters = 20
    
    print("Feet\tMeter      |     Meter\t\tFeet"  )
    print("--------------------------------------------------")
        
    while count != 10:
        print(format(feet,".2f"),"\t",format(footToMeter(feet),".2f"),"     |     "\
              ,format(meters,".2f"), "\t"format(meterToFoot(meters),".2f"))
        count += 1
        feet += 1
        meters += 1
 
main()
 
cs

6.10 (Use the isPrime Function) Listing 6.7, PrimeNumberFunction.py, provides the isPrime(number) function for testing whether a number is prime. Use this function to find the number of prime numbers less than 10,000.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Check whether number is prime
def isPrime(number):
    divisor = 2
    while divisor <= number / 2:
        if number % divisor == 0:
            # If true, number is not prime
            return False # number is not a prime
        divisor += 1
 
    return True # number is prime
 
def main():
    number = 2
    count = 0
    while number <= 10000:
        if isPrime(number):
            print(number, end = " ")
        if count == 10:
            print()
            count = 0
        number += 1
 
main()
cs

*6.13 (Sum series) Write a function to compute the following series:

 

 

Write a test program that displays the following table: 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def m(i):
    sum = 0
    n = 1
    
    while n != i:
       sum += n/(n+1)
       n += 1
 
    return sum
 
def main():
    i = 1
    
    print("i\t\t  m(i)")
    print()
    while i != 21:
        print(i,"\t\t",format(m(i+1),".4f"))
        i += 1
 
main()
cs

*6.14 (Estimate ) can be computed using the following series: 

 

 

 

Write a function that returns m(i) for a given i and write a test program that displays the following table:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def m(i):
    sum = 0
    n = 1
    
    while n != i:
        sum += (-1)**(n+1)/(2*n-1)
        n += 1
 
    return 4*sum
 
def main():
 
    print("i\t\t  m(i)")
    print()
    for i in range(1902100):
        print(i,"\t\t",format(m(i+1),".4f"))
        i += 1
 
main()
cs

*6.16 (Number of days in a year) Write a function that returns the number of days in a year using the following header:

 

def numberOfDaysInAYear(year):

 

Write a test program that displays the number of days in the years from 2010 to 2020.

 

1
2
3
4
5
6
7
8
9
10
11
def numberOfDaysInAYear(year):
    if (year % 4 == 0 and year % 100 != 0or year % 400 == 0 :
        return 366
    else:
        return 365
def main():
 
    for i in range(20102021):
        print(i ,"= ",numberOfDaysInAYear(i),"days")
 
main()
cs

 *6.17 (The MyTriangle module) Create a module named MyTriangle that contains the following two functions:

 

# Returns true if the sum of any two sides is

# greater than the third side.

def isValid(side1, side2, side3):

 

# Returns the area of the triangle.

def area(side1, side2, side3):

 

Write a test program that reads three sides for a triangle and computes the area if the input is valid. Otherwise, it displays that the input is invalid. The formula for computing the area of a triangle is given in Exercise 2.14.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Returns true if the sum of any two sides is
# greater than the third side.
def isValid(side1, side2, side3):
    return (side1 + side2 > side3) and (side1 + side3 > side2) and (side2 + side3 > side1)
    
# Returns the area of the triangle.
def area(side1, side2, side3):
    s = (side1 + side2 + side3) / 2
    return (s*(s - side1)*(s - side2)*(s - side3))**0.5
    
def main():
    s1,s2,s3 = eval(input("Enter three sides in double: "))
    if isValid(s1,s2,s3):
        print("The area of the triangle is ",area(s1,s2,s3))
 
    else :
        print("Input is invalid")
 
main()
cs

 *6.18 (Display matrix of 0s and 1s) Write a function that displays an n-by-n matrix using the following header:

 

def printMatrix(n):

 

Each element is 0 or 1, which is generated randomly. Write a test program that prompts the user to enter n and displays an n-by-n matrix.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random
 
def printMatrix(n):
    for i in range(0,n):
        for j in range(0,n):
            element = random.randint(0,1)
            print(element,end = " ")
        print()
    
def main():
    n = eval(input("Enter n :"))
    printMatrix(n)
    
main()
cs

*6.19 (Geometry: point position) Exercise 4.31 shows how to test whether a point is on the left side of a directed line, on the right, or on the same line. Write the following functions:

 

# Return true if point (x2, y2) is on the left side of the

# directed line from (x0, y0) to (x1, y1)

def leftOfTheLine(x0, y0, x1, y1, x2, y2):

 

# Return true if point (x2, y2) is on the same

# line from (x0, y0) to (x1, y1)

def onTheSameLine(x0, y0, x1, y1, x2, y2):

 

# Return true if point (x2, y2) is on the

# line segment from (x0, y0) to (x1, y1)

def onTheLineSegment(x0, y0, x1, y1, x2, y2): 

 

Write a program that prompts the user to enter the three points for p0, p1, and p2 and displays whether p2 is on the left of the line from p0 to p1, on the right, on the same line, or on the line segment. The sample runs of this program are the same as in Exercise 4.31.

 

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
32
33
34
# Return true if point (x2, y2) is on the left side of the
# directed line from (x0, y0) to (x1, y1)
def leftOfTheLine(x0, y0, x1, y1, x2, y2):
    if (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0) > 0 :
        return "on the left side of"
 
    elif (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0) < 0 :
        return "on the right side of"
    
# Return true if point (x2, y2) is on the same
# line from (x0, y0) to (x1, y1)
def onTheSameLine(x0, y0, x1, y1, x2, y2):
    return (x1 - x0)*(y2 - y0) - (x2 - x0)*(y1 - y0) == 0
    
# Return true if point (x2, y2) is on the
# line segment from (x0, y0) to (x1, y1)
def onTheLineSegment(x0, y0, x1, y1, x2, y2):
    status = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)
    return status <= 0.0000000001 and ((x0 <= x2 and x2 <= x1) or (x0 >= x2 and x2 >= x1))
 
    
def main():
    x0,y0,x1,y1,x2,y2 = eval(input("Enter coordinates for the three points p0, p1, and p2: "))
 
    if onTheLineSegment(x0, y0, x1, y1, x2, y2):
        print("p2 is on the line segment from p0 to p1")
 
    else :
        if onTheSameLine(x0, y0, x1, y1, x2, y2):
            print("p2 is on the same line from p0 to p1")
        else :
            print("p2 " + leftOfTheLine(x0, y0, x1, y1, x2, y2) + "from p0 to p1")
    
main()
cs

*6.20 (Geometry: display angles) Rewrite Listing 2.9, ComputeDistance.py, using the following function for computing the distance between two points.

 

def distance(x1, y1, x2, y2):

 

1
2
3
4
5
6
7
def distance(x1, y1, x2, y2):
    return ((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1))**0.5
    
def main():
    x1,y1,x2,y2 = eval(input("Enter coordinates for the two points p0, p1 :"))
    print("The distance between the two points is", distance(x1, y1, x2, y2))
main()
cs

 **6.21(중요) (Math: approximate the square root) There are several techniques for implementing the sqrt function in the math module. One such technique is known as the Babylonian function. It approximates the square root of a number, n, by repeatedly performing a calculation using the following formula:

 

nextGuess = (lastGuess + (n / lastGuess)) / 2

 

When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root. The initial guess can be any positive value (e.g., 1). This value will be the starting value for lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of n. If not, nextGuess becomes lastGuess and the approximation process continues. Implement the following function that returns the square root of n. def sqrt(n):

 

1
2
3
4
5
6
7
8
9
10
11
12
13
def sqrt(n):
    lastGuess = 1
    for i in range(0,n):
        nextGuess = (lastGuess + (n / lastGuess)) / 2
        lastGuess = nextGuess
 
    return nextGuess
    
def main():
    n = eval(input("Enter the number : "))
    print(sqrt(n))
 
main()
cs

 **6.22(중요) (Display current date and time) Listing 2.7, ShowCurrentTime.py, displays the current time. Enhance this program to display the current date and time. (Hint: The calendar example in Listing 6.13, PrintCalendar.py, should give you some ideas on how to find the year, month, and day.)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import time
 
def main():
    currentTime = time.time() # Get current time
 
    # Obtain the total seconds since midnight, Jan 1, 1970
    totalSeconds = int(currentTime)
 
    # Get the current second 
    currentSecond = totalSeconds % 60 
 
    # Obtain the total minutes
    totalMinutes = totalSeconds // 60 
 
    # Compute the current minute in the hour
    currentMinute = totalMinutes % 60
 
    # Obtain the total hours
    totalHours = totalMinutes // 60
 
    # Compute the current hour
    currentHour = totalHours % 24
 
    # Compute the total days
    totalDays = totalHours // 24
    if currentHour > 0:
        totalDays += 1
 
    # Obtain Year
    currentYear = 2000
    while getTotalDaysInYears(currentYear) < totalDays:
        currentYear += 1
 
    # Obtain Month
    totalNumOfDaysInTheYear = totalDays - getTotalDaysInYears(currentYear - 1);
    currentMonth = 0;
    while getTotalDaysInMonths(currentYear, currentMonth) < totalNumOfDaysInTheYear:
         currentMonth += 1
 
    # Obtain Day
    currentDay = totalNumOfDaysInTheYear - getTotalDaysInMonths(currentYear, currentMonth - 1)
 
    # Display results
    output = "Current date and time is " + \
        str(currentMonth) + "/" + str(currentDay) + "/" + str(currentYear) + " " + \
        str(currentHour) + ":" + str(currentMinute) + ":" + str(currentSecond) + " GMT"
 
    print(output)
 
#Get the total number of days from Jan 1, 1970 to the specified year
def getTotalDaysInYears(year):
    total = 0
 
    # Get the total days from 1970 to the specified year
    for i in range(1970, year + 1):
        if isLeapYear(i):
            total = total + 366
        else:
            total = total + 365
 
    return total
 
# Get the total number of days from Jan 1 to the month in the year*
def getTotalDaysInMonths(year, month):
    total = 0
 
    # Add days from Jan to the month
    for i in range(1, month + 1):
        total = total + getNumberOfDaysInMonth(year, i)
 
    return total
 
# Get the number of days in a month
def getNumberOfDaysInMonth(year, month): 
    if month == 1 or month == 3 or month == 5 or month == 7 or \
        month == 8 or month == 10 or month == 12:
        return 31
 
    if month == 4 or month == 6 or month == 9 or month == 11:
        return 30
 
    if month == 2:
        return 29 if isLeapYear(year) else 28
 
    return 0 # If month is incorrect
 
# Determine if it is a leap year
def isLeapYear(year): 
    return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
 
main()
 
cs

 **6.23 (Convert milliseconds to hours, minutes, and seconds) Write a function that converts milliseconds to hours, minutes, and seconds using the following header:

 

def convertMillis(millis):

 

The function returns a string as hours:minutes:seconds. For example, convertMillis(5500) returns the string 0:0:5, convertMillis(100000) returns the string 0:1:40, and convertMillis(555550000) returns the string 154:19:10.

Write a test program that prompts the user to enter a value for milliseconds and displays a string in the format of hours:minutes:seconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def convertMillis(millis):
    millis *= 0.001
 
    hour = str(int(millis // 3600))
    millis -= 3600*(millis // 3600)
    minute = str(int(millis // 60))
    millis -= 60*(millis // 60)
    sec = str(int(millis % 60))
 
    return hour +":"+ minute +":"+ sec
 
def main():
    millis = eval(input("Enter the millis"))
    print(convertMillis(millis))
    
main()
cs

**6.24 (Palindromic prime) A palindromic prime is a prime number that is also palindromic. For example, 131 is a prime and also a palindromic prime, as are 313 and 757. Write a program that displays the first 100 palindromic prime numbers. Display 10 numbers per line and align the numbers properly, as follows: 

 

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
32
33
34
35
36
37
38
def isPrime(number):
    divisor = 2
 
    while divisor < number :
        if number % divisor == 0 and divisor != number:
            return False
 
        divisor += 1
 
    return True
        
    
def isPalin(number):
    return number == reverse(number)
 
def reverse(number):
    result = 0
    while number != 0:
        result = (result*10+ (number%10)
        number //= 10
 
    return result
    
def main():
    count = 0
    number = 2
    
    while count <= 100 :
        if isPalin(number) and isPrime(number) :
            print(format(number,"5d"),end = "   ")
            count += 1
 
            if count % 10 == 0 :
                print()
 
        number += 1
         
main()
cs

**6.25 (Emirp) An emirp ( prime spelled backward) is a nonpalindromic prime number whose reversal is also a prime. For example, both 17 and 71 are prime numbers, so 17 and 71 are emirps. Write a program that displays the first 100 emirps. Display 10 numbers per line and align the numbers properly, as follows: 

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
32
33
34
35
36
37
38
def isPrime(number):
    divisor = 2
 
    while divisor < number :
        if number % divisor == 0 and divisor != number:
            return False
 
        divisor += 1
 
    return True
        
    
def isPalin(number):
    return number == reverse(number)
 
def reverse(number):
    result = 0
    while number != 0:
        result = (result*10+ (number%10)
        number //= 10
 
    return result
    
def main():
    count = 0
    number = 2
    
    while count <= 100 :
        if isPalin(number) == False and isPrime(number) and isPrime(reverse(number)):
            print(format(number,"5d"),end = "   ")
            count += 1
 
            if count % 10 == 0 :
                print()
 
        number += 1
         
main()
cs

 

 참고 문헌 : Introduction to Programming Using Python / Y.DANIEL LIANG



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.

 

'파이썬 > 예제' 카테고리의 다른 글

[파이썬]Chapter 5 예제  (0) 2017.08.16
[파이썬]Chater 4 예제  (0) 2017.07.26
[파이썬] Chapter 3 예제  (0) 2017.07.19
파이썬 Chapter 2 예제  (0) 2017.07.14
댓글