티스토리 뷰

파이썬/예제

[파이썬]Chapter 5 예제

cll179 2017. 8. 16. 16:49

*5.1 (Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
sum = 0
countPos = 0
countNeg = 0
number = 1
while number != 0:
    number = eval(input("Enter an integer, the input ends if it is 0: "))
    sum += number
 
    if number < 0:
        countNeg += 1
 
    elif number > 0:
        countPos += 1
 
average = sum/(countPos + countNeg)
 
print("The number of positives is ",countPos)
print("The number of negatives is ",countNeg)
print("The total is ", sum)
print("The average is "format(average,".2f"))
 
cs

5.4 (Conversion from miles to kilometers) Write a program that displays the following table (note that 1 mile is 1.609 kilometers):

1
2
3
4
print("kilograms\tPounds")
 
for i in range(1,200):
    print(i,"\t",format(i*2.2,"10.1f"))
cs

*5.5 (Conversion from kilograms to pounds and pounds to kilograms) Write a program that displays the following two tables side by side (note that 1 kilogram is 2.2 pounds and that 1 pound is .45 kilograms):

1
2
3
4
5
6
7
8
9
10
11
print("kilograms\tPounds   |   Pounds\tkilograms")
 
= #Kilogram index
= 20 #Pounds index
    
for i in range(1,101):
    
    print(j,"\t"format(j*2.2,"10.1f"),end = "   |   ")
    print(k,"\t"format(k*0.45,"10.2f"))
    j += 2
    k += 5
cs

5.7 (Use trigonometric functions) Print the following table to display the sin value and cos value of degrees from 0 to 360 with increments of 10 degrees. Round the value to keep four digits after the decimal point.

1
2
3
4
5
6
import math
 
print("Degree\tSin\tCos")
 
for D in range(0,370,10):
    print(D,"\t",format(math.sin(math.radians(D)),".4f"),"\t",format(math.cos(math.radians(D)),".4f"))
cs

**5.9 (Financial application: compute future tuition) Suppose that the tuition for a university is $10,000 this year and increases 5% every year. Write a program that computes the tuition in ten years and the total cost of four years’ worth of tuition starting ten years from now 

1
2
3
4
5
6
7
8
9
10
11
12
13
tuition = 10000
total = 0
 
for i in range(1,15):
    tuition += tuition * 0.05
 
    if i == 10 :
        print("The cost of tuition in 10 years is $",format(tuition,".2f"))
 
    if i > 10 :
        total = total + tuition
 
print("The total cost of 4 years tuition in 10 years is $",format(total,".2f"))
cs

 *5.11 (Find the two highest scores) Write a program that prompts the user to enter the number of students and each student’s score, and displays the highest and secondhighest scores

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
numOfStudents = eval(input("Enter the number of students : "))
 
firstScore = 0
secondScore = 0
firstStudent = 0
secondStudent = 0
 
for i in range(numOfStudents):
    
    score = eval(input("Enter the student"+ str(i+1+ "'s score : "))
 
    if score > secondScore:
        if score > firstScore:
            firstScore = score
            firstStudent = i
        else :
            secondScore = score
            secondStudent = i
 
print("The first student is Student",firstStudent+1" and the student's score is ",firstScore)
print("The second student is Student",secondStudent+1" and the student's score is ",secondScore)
cs

5.12 (Find numbers divisible by 5 and 6) Write a program that displays, ten numbers per line, all the numbers from 100 to 1,000 that are divisible by 5 and 6. The numbers are separated by exactly one space 

1
2
3
4
5
6
7
8
9
NUMBERS_PER_LINE = 10
count = 0
 
for n in range(100,1000):
    if n % == and n % == :
        print(n, end = " ")
        count += 1
        if count % NUMBERS_PER_LINE == :
            print()
cs

5.14 (Find the smallest n such that n2 12,000) Use a while loop to find the smallest integer n such that n2 is greater than 12,000. 

1
2
3
4
5
= 0
while n**< 12000:
    n += 1
 
print(n)
cs

*5.16 (Compute the greatest common divisor) For Listing 5.8, another solution to find the greatest common divisor of two integers n1 and n2 is as follows: First find d to be the minimum of n1 and n2, and then check whether d, d - 1, d - 2, ..., 2, or 1 is a divisor for both n1 and n2 in this order. The first such common divisor is the greatest common divisor for n1 and n2. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
n1 = eval(input("Enter first integer: "))
n2 = eval(input("Enter second integer: "))
 
= 2
gcd = 1
 
while d <= n1 and d <= n2 :
    if n1 % d == and n2 % d == :
        for i in range(0,d-1):
            if n1 % (d - i) == and n2 % (d - i) == :
                gcd = d
                break
                
    d += 1
 
print("The greatest common divisor for",n1 ,"and",n2, "is",gcd)
cs

 *5.17 (Display the ASCII character table) Write a program that displays the characters in the ASCII character table from ! to ~. Display ten characters per line. The characters are separated by exactly one space.

1
2
3
4
5
6
7
8
NUMBER_OF_CHR_PER_LINE = 10
count = 0
 
for i in range(33127):
    print(chr(i), end = " ")
    count += 1
    if count % NUMBER_OF_CHR_PER_LINE == :
        print()
cs

**5.18 (Find the factors of an integer) Write a program that reads an integer and displays all its smallest factors, also known as prime factors. For example, if the input integer is 120, the output should be as follows:

 

2, 2, 2, 3, 5

 

1
2
3
4
5
6
7
8
9
10
11
12
13
number = eval(input("Enter the number : "))
= 2
 
while number != 0:
    if number % f == :
        print(f, end="")
        number /= f
 
        if number != 1:
            print(",",end = " ")
 
    else:
        f += 1
cs

**5.19(중요) (Display a pyramid) Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NUMBER_OF_LINE = eval(input("Enter the nuber of lines: "))
 
for i in range(1, NUMBER_OF_LINE+1):
    
    for space in range(1, (NUMBER_OF_LINE+1- i):# 공백부터 넣기
        print("  ", end = " ")
 
    for left in range(i, 1-1): # 공백이 다 끝난뒤 왼쪽 수 출력
        print(format(left,"2d"), end = " ")
 
    for right in range(1, i+1):# 왼쪽 수 출력 끝난 뒤 오른쪽 수 출력
        print(format(right,"2d"), end = " ")
 
    print()
cs


*5.20 (Display four patterns using loops) Use nested loops that display the following patterns in four separate programs:

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
NUMBER_OF_LINE = 6
 
print("Pattern A")
for i in range(1, NUMBER_OF_LINE+1):
    for j in range(1,i+1):
        print(j, end = " ")
    print()
 
print("\nPattern B")
for i in range(NUMBER_OF_LINE+1,1,-1):
    for j in range(1,i):
        print(j,end = " ")
    print()
 
print("\nPattern C")
for i in range(1,NUMBER_OF_LINE+1):
    for space in range(0,NUMBER_OF_LINE-i):
        print(" ", end = " ")
 
    for j in range(i,0,-1):
        print(j, end = " ")
    print()
 
print("\nPattern D")
for i in range(NUMBER_OF_LINE+1,1,-1):
    for j in range(1,i):
        print(j, end = " ")
    print()
cs

**5.21 (Display numbers in a pyramid pattern) Write a nested for loop that displays the following output: 

1
2
3
4
5
6
7
8
9
10
11
12
NUMBER_PER_LINE = 8
 
for i in range(1,NUMBER_PER_LINE+1):
    for space in range(NUMBER_PER_LINE+1-i, 1,-1):
        print("   ", end = "  ")
 
    for left in range(0, i-1):
        print(format(2**left,"3d"), end = "  ")
 
    for right in range(i-1,-1,-1): #주의 -1까지 돌려야함.
        print(format(2**right,"3d"), end = "  ")
    print()
cs

*5.25 (Demonstrate cancellation errors) A cancellation error occurs when you are manipulating a very large number with a very small number. The large number may cancel out the smaller number. For example, the result of 100000000.0 + 0.000000001 is equal to 100000000.0. To avoid cancellation errors and obtain more accurate results, carefully select the order of computation. For example, in computing the following series, you will obtain more accurate results by computing from right to left rather than from left to right:

 

Write a program that compares the results of the summation of the preceding series, computing both from left to right and from right to left with n 50000.

 

1
2
3
4
5
6
7
8
9
10
11
12
= 5000
sum1 = 0
for i in range(1, n):
    sum1 += 1/i
 
print("left to right : ",sum1)
 
sum2 = 0
for i in range(n, 1):
    sum2 += 1/i
 
print("right to left: ",sum2)
cs

**5.27 (Compute ) You can approximate by using the following series: 

 

1
2
3
4
5
6
7
8
sum = 0
 
for i in range(10000,110000,+10000) :
    for k in range(1,i+1):
        sum += ((-1)**(k+1)) / (2*k-1)
    PI = 4*sum
    print("i = ",i,", ","PI is =", PI)
    sum = 0
cs


**5.28(중요) (Compute e) You can approximate e by using the following series:

 

 

 

 

Write a program that displays the e value for i = 10000, 20000, . . ., and 100000.

1
2
3
4
5
6
7
for i in range(10000,110000,+10000):
    e = 1
    item = 1
    for k in range(1,i+1):
        item /= k
        e += item
    print("i = ",i,", e =",e)
cs

 **5.30 (Display the first days of each month) Write a program that prompts the user to enter the year and first day of the year, and displays the first day of each month in the year on the console. For example, if the user entered year 2013, and 2 for Tuesday, January 1, 2013, your program should display the following output:

 

January 1, 2013 is Tuesday

...

December 1, 2013 is Sunday

 

**5.31 (Display calendars) Write a program that prompts the user to enter the year and first day of the year, and displays on the console the calendar table for the year.

 

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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# 주어진 연도와 월에 대한 달력을 출력한다.
def printMonth(year, month):
    # 달력 머리행을 출력한다.
    printMonthTitle(year, month)
 
    # 달력의 몸체를 출력한다.
    printMonthBody(year, month)
 
# 달력의 제목을 출력한다. 예, May 1999
def printMonthTitle(year, month):
    print("         ", getMonthName(month), " ", year)
    print("-----------------------------")
    print(" Sun Mon Tue Wed Thu Fri Sat")
 
# 달력의 몸체를 출력한다.
def printMonthBody(year, month):
    # 주어진 월의 첫 번째 일에 대한 시작 요일을 구한다.
    startDay = getStartDay(year, month)
 
    # 월의 일수를 구한다.
    numberOfDaysInMonth = getNumberOfDaysInMonth(year, month)
 
    # 월의 첫째 날 앞에 공백을 삽입한다.
    i = 0
    for i in range(startDay):
       print("    ", end = "")
 
    for i in range(1, numberOfDaysInMonth + 1):
        print(format(i, '4d'), end = "")
 
        if (i + startDay) % == 0:
            print() # 새로운 행으로 이동한다.
 
# 월에 대한 영문 이름을 가져온다.
def getMonthName(month):
    if month == 1:
        monthName = "January"
    elif month == 2:
        monthName = "February"
    elif month == 3:
        monthName = "March"
    elif month == 4:
        monthName = "April"
    elif month == 5:
        monthName = "May"
    elif month == 6:
        monthName = "June"
    elif month == 7:
        monthName = "July"
    elif month == 8:
        monthName = "August"
    elif month == 9:
        monthName = "September"
    elif month == 10:
        monthName = "October"
    elif month == 11:
        monthName = "November"
    else:
        monthName = "December"
 
    return monthName
 
#  주어진 년/월/일의 시작 요일을 구한다.
def getStartDay(year, month):
    START_DAY_FOR_JAN_1_1800 = 3
 
    # 1800년 1월 1일부터 주어진 년/월/1까지 총 일수를 구한다.
    totalNumberOfDays = getTotalNumberOfDays(year, month)
 
    # 주어진 년/월/1의 시작 요일을 반환한다.
    return (totalNumberOfDays + START_DAY_FOR_JAN_1_1800) % 7
 
# 1800년 1월 1일부터 총 일수를 계산한다.
def getTotalNumberOfDays(year, month):
    total = 0
 
    # 1800년부터 입력된 년도의 1월 1일까지 모든 일수를 계산한다.
    for i in range(1800, year):
        if isLeapYear(i):
            total = total + 366
        else:
            total = total + 365
 
    # 1월부터 입력된 월의 이전 월까지 모든 일수를 더한다.
    for i in range(1, month):
        total = total + getNumberOfDaysInMonth(year, i)
 
    return total
 
# 해당 월의 총 일수를 구한다.
def getNumberOfDaysInMonth(year, month):
    if (month == or month == or month == or month == or
        month == or month == 10 or month == 12):
        return 31
 
    if month == or month == or month == or month == 11:
        return 30
 
    if month == 2:
        return 29 if isLeapYear(year) else 28
 
    return # 잘못된 월 입력일 경우
 
# 입력된 연도가 윤년인지 결정한다.
def isLeapYear(year):
    return year % 400 == or (year % == and year % 100 != 0)
 
def main():
    # 사용자로부터 년도와 월을 입력받는다.
    year = eval(input("연도를 입력하세요(예, 2001): "))
    month = eval(input(("월에 해당하는 숫자를 입력하세요(1-12): ")))
 
    # 입력 연도와 월에 대한 달력을 출력한다.
    printMonth(year, month)
 
main() # main 함수를 호출한다.
 
cs

*5.33 (Financial application: compute CD value) Suppose you put $10,000 into a CD with an annual percentage yield of 5.75%. After one month, the CD is worth

 

10000 + 10000 * 5.75 / 1200 = 10047.91

 

After two months, the CD is worth

 

10047.91 + 10047.91 * 5.75 / 1200 = 10096.06

 

After three months, the CD is worth 10096.06 + 10096.06 * 5.75 / 1200 = 10145.43

and so on.

Write a program that prompts the user to enter an amount (e.g., 10,000), the annual percentage yield (e.g., 5.75), and the number of months (e.g., 18), and displays a table as shown in the sample run.

 

1
2
3
4
5
6
7
8
initAmount = eval(input("Enter the initial deposit amount : "))
annualPercent = eval(input("Enter the annual percentage yield: "))
period = eval(input("Enter maturity period (number of months): "))
 
print("Month\tCD Value")
for i in range(1,period+1):
    initAmount += initAmount * annualPercent / 1200
    print(i,"\t",format(initAmount,".2f"))
cs

**5.34 (Game: lottery) Revise Listing 4.10, Lottery.py, to generate a lottery of a two-digit number. The two digits in the number are distinct. (Hint: Generate the first digit. Use a loop to continuously generate the second digit until it is different from the first digit.)

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
import random
 
number= eval(input("Enter the number: "))
 
userDigit1 = number//10
userDigit2 = number%10
 
comDigit1 = 1#random.randint(0,9)
while 1:
    comDigit2 = 3#random.randint(0,9)
    if(comDigit1 != comDigit2):
        break;
 
if comDigit1 == userDigit1 and comDigit2 == userDigit2:
    print("You win! $10,000")
 
elif comDigit1 == userDigit2 and comDigit2 == userDigit1:
    print("$3,000")
 
elif (comDigit1 == userDigit2 or\
      comDigit1 == userDigit1 or\
      comDigit2 == userDigit2 or\
      comDigit2 == userDigit1):
    print("$1,000")
    
else:
    print("You lose")
cs

**5.35 (Perfect number) A positive integer is called a perfect number if it is equal to the sum of all of its positive divisors, excluding itself. For example, 6 is the first perfect number, because The next is There are four perfect numbers less than 10,000. Write a program to find these four numbers.

1
2
3
4
5
6
7
8
for i in range(5,10000):
    sum = 1
    for j in range(2,i):
        if i % j == 0:
           sum += j
 
    if i == sum:
        print(i, end = " ")
cs

***5.36 (Game: scissor, rock, paper) Programming Exercise 4.17 gives a program that plays the scissor, rock, paper game. Revise the program to let the user play continuously until either the user or the computer wins more than two times.  

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
import random
 
comcnt=0
usercnt=0
 
while :
    com = random.randint(0,2)
    user = eval(input("scissor(0), rock(1), paper(2)"))
    
    if(user == 0):
        if(com == 0):
            print("The computer is scissor. You are scissor. It is a draw.")
 
        elif(com == 1):
            print("The computer is rock. You are scissor. You lose.")
            comcnt += 1
 
        else:
            print("The computer is paper. You are scissor. You won.")
            usercnt += 1
 
    elif(user == 1):
        if(com == 0):
            print("The computer is scissor. You are rock. You won.")
            usercnt += 1
 
        elif(com == 1):
            print("The computer is rock. You are rock. It is a draw.")
 
        else:
            print("The computer is paper. You are rock. You lose.")
            comcnt += 1
            
    elif(user == 2):
        if(com == 0):
            print("The computer is scissor. You are paper. You lose.")
            comcnt += 1
            
        elif(com == 1):
            print("The computer is rock. You are paper. You won.")
            usercnt += 1
            
        else:
            print("The computer is paper. You are paper. It is a draw.")
 
    if comcnt == 2:
        print("Computer won two times")
        break;
    if usercnt == 2:
        print("User won two times")
        break;
cs

*5.37 (Summation) Write a program that computes the following summation:

1
2
3
4
5
sum = 0
for i in range(1,625):
    sum += 1/(i**0.+ (i+1)**0.5)
 
print(sum)
cs

*5.38 (Simulation: clock countdown) You can use the time.sleep(seconds) function in the time module to let the program pause for the specified seconds. Write a program that prompts the user to enter the number of seconds, displays a message at every second, and terminates when the time expires.

1
2
3
4
5
6
7
8
9
10
11
12
13
import time
 
seconds = eval(input("Enter the number of seconds: "))
 
for i in range(seconds-1,0,-1):
    if i == 1:
        print(i, "second reamining.")
 
    else:
        print(i, "seconds remaining")
    time.sleep(1)
 
print("stopped")
cs

5.39 (중요)  (Financial application: find the sales amount) You have just started a sales job in a department store. Your pay consists of a base salary plus a commission. The base salary is $5,000. The following scheme shows how to determine the commission rate:

 

 

Your goal is to earn $30,000 a year. Write a program that finds out the minimum amount of sales you have to generate in order to make $30,000.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
salesAmount = 0.01
commission = 0
while commission < 25000:
    if salesAmount >= 10001 :
        commission = 5000*0.08 + 5000*0.1 + (salesAmount-10000)*0.12;
        
    elif salesAmount >= 5001:
        commission = 5000*0.08 + (salesAmount-5000)*0.10;
        
    else :
        commission = salesAmount*0.08;
 
    salesAmount += 0.01
 
print(salesAmount)
 
cs


**5.41 (Occurrence of max numbers) Write a program that reads integers, finds the largest of them, and counts its occurrences. Assume that the input ends with number 0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest number is 5 and the occurrence count for 5 is 4. (Hint: Maintain two variables, max and count. The variable max stores the current maximum number, and count stores its occurrences. Initially, assign the first number to max and 1 to count. Compare each subsequent number with max. If the number is greater than max, assign it to max and reset count to 1. If the number is equal to max, increment count by 1.)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
number = 1
max = 0
count = 0
while 1:
    number = eval(input("Enter the number (0: for end of input): "))
 
    if number == 0 :
        break
    elif number > max :
        max = number
        count = 1
 
    elif number == max :
        count += 1
 
print("The largest number is ",max)
print("The occurrence count of the largest number is ",count)
 
cs


**5.42 (Monte Carlo simulation) A square is divided into four smaller regions as shown in (a). If you throw a dart into the square one million times, what is the probability for the dart to fall into an odd-numbered region? Write a program to simulate the process and display the result. (Hint: Place the center of the square in the center of a coordinate system, as shown in (b). Randomly generate a point in the square and count the number of times for a point to fall in an odd-numbered region.) 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import random
 
NUMBER_OF_TRIALS = 1000000
numberOfHits = 0
 
for i in range(NUMBER_OF_TRIALS):
    x = random.random() * 2.0 - 1;
    y = random.random() * 2.0 - 1;
    if x < 0:
        numberOfHits += 1
    elif not (x > 1 or x < 0 or y > 1 or y < 0):
        slope = (1.0 - 0/ (0 - 1.0)
        x1 = x + -* slope
        if x1 <= 1:
          numberOfHits += 1
 
 
result =  numberOfHits / NUMBER_OF_TRIALS
 
print(result)
 
cs

 *5.43 (Math: combinations) Write a program that displays all possible combinations for picking two numbers from integers 1 to 7. Also display the total number of combinations.

1
2
3
4
5
6
7
8
count = 0
 
for i in range(1,8):
    for j in range(i+1,8):
        print(i, j)
        count += 1
 
print("The total number of all combination is ",count)
cs


**5.44 (중요)(Decimal to binary) Write a program that prompts the user to enter a decimal integer and displays its corresponding binary value. 
1
2
3
4
5
6
7
8
9
10
decimal = eval(input("Enter an integer: "))
    
binaryString = ""
value = decimal
 
while value != 0:
    binaryString = str(value % 2+ binaryString #뒤에 문자열을 더함.
    value = value // 2
    
print(binaryString)
cs

**5.45 (Decimal to hex) Write a program that prompts the user to enter a decimal integer and displays its corresponding hexadecimal value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
hex = eval(input("Enter an integer: "))
    
hexString = ""
value = hex
 
while value != 0:
    if value % 16 >= 10 :
        hexString = chr(value % 16 + 55+ hexString
 
    else:
        hexString = str(value % 16+ hexString
 
    value //= 16
 
print(hexString)
cs

 


 

**5.46 (Statistics: compute mean and standard deviation) In business applications, you are often asked to compute the mean and standard deviation of data. The mean is simply the average of the numbers. The standard deviation is a statistic that tells you how tightly all the various data are clustered around the mean in a set of data. For example, what is the average age of the students in a class? How close are the ages? If all the students are the same age, the deviation is 0. Write a program that prompts the user to enter ten numbers, and displays the mean and standard deviations of these numbers using the following formula:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sum = 0
sumDevi = 0
 
print("Enter ten numbers: ",end = "")
 
for i in range (0,10):
    x = eval(input())
    sum += x
    sumDevi += x**2
    
mean = sum/10
deviation = ( (sumDevi - ((sum)**2/10))/9 )**0.5
 
print("The mean is ",format(mean, ".2f"))
print("The standard deviation is ",format(deviation, ".5f")
cs


**5.47 (Turtle: draw random balls) Write a program that displays 10 random balls in a rectangle with width 120 and height 100, centered at (0, 0), as shown in Figure 5.3a .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import turtle as t
import random
 
t.penup()
t.goto(-60,-50)
t.pendown()
t.goto(60,-50)
t.goto(60,50)
t.goto(-60,50)
t.goto(-60,-50)
 
for i in range(0,10):
    t.penup()
    x = random.randint(-60,60)
    y = random.randint(-50,50)
    t.goto(x,y)
    t.pendown()
    t.dot(10,"red")
cs

 


**5.48 (Turtle: draw circles) Write a program that draws 10 circles with centers (0, 0), as shown in Figure 5.3b.  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import turtle
 
radius = 50
 
for i in range(10):
    turtle.penup() # Pull the pen up
    turtle.goto(0-radius)
    turtle.pendown() # Pull the pen down
 
    turtle.circle(radius)
    radius += 5
 
turtle.hideturtle()
 
turtle.done()
cs
 

 

 


**5.49 (Turtle: display a multiplication table) Write a program that displays a multiplication table, as shown in Figure 5.4a.
1
2
3
4
5
6
7
8
9
10
11
12
print("       Multiplication Table")
print("      ",end ="")
 
for i in range(110):
    print(i,end ="   ")
print("\n-----------------------------------------")
 
for i in range(1,10):
    print(i,"|",end="  ")
    for j in range(1,10):
        print(format(i*j,"2d"),end = "  ")
    print()
cs

**5.50(중요) (Turtle: display numbers in a triangular pattern) Write a program that displays numbers in a triangular pattern, as shown in Figure 5.4b.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import turtle
 
= -100
= 100
line = ""
for i in range(112):
    for j in range(1, i):
        line += str(j) + " "
    
    # Draw a line
    turtle.penup() # Pull the pen up
    turtle.goto(x, y)
    turtle.pendown() # Pull the pen down
    turtle.write(line, font = ("Times"18"bold"))
 
    line = ""
    y -= 20
 
turtle.hideturtle()
 
turtle.done()
cs

 

**5.51 (Turtle: display a lattice) Write a program that displays an 18-by-18 lattice, as shown in Figure 5.4c

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
import turtle as t
 
= -90
= 90
 
t.penup()
t.goto(x,y)
t.pendown()
 
for i in range(0,19):
    t.goto(x+180, y)
    t.penup()
    y -= 10
    t.goto(x,y)
    t.pendown()
 
= -90
= 90
 
t.penup()
t.goto(x,y)
t.pendown()
 
for i in range(0,19):
    t.goto(x, y-180)
    t.penup()
    x += 10
    t.goto(x, y)
    t.pendown()
cs

**5.52(중요) (Turtle: plot the sine function) Write a program that plots the sine function, as shown in Figure 5.5a. 
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
import turtle
import math
 
# Draw X-axis
turtle.penup()
turtle.goto(-2200)
turtle.pendown()
 
turtle.goto(2200)
 
# Draw arrows
turtle.degrees()
turtle.setheading(150)
turtle.forward(20)
 
turtle.penup()
turtle.goto(2200)
turtle.pendown()
turtle.setheading(-150)
turtle.forward(20)
 
# Draw Y-axis
turtle.penup()
turtle.goto(0-80)
turtle.pendown()
turtle.goto(080)
 
turtle.penup()
turtle.goto(080)
turtle.pendown()
turtle.setheading(240)
turtle.forward(20)
 
turtle.penup()
turtle.goto(080)
turtle.pendown()
turtle.setheading(-60)
turtle.forward(20)
 
#Pi write
turtle.penup()
turtle.goto(-100-15)
turtle.pendown()
turtle.write("-2\u03c0")
 
turtle.penup()
turtle.goto(100-15)
turtle.pendown()
turtle.write("2\u03c0")
turtle.penup()
 
#draw graph
turtle.goto(-17550 * math.sin((-175 / 100* 2 * math.pi))
turtle.pendown()
for x in range(-175176):
    turtle.goto(x, 50 * math.sin((x / 100* 2 * math.pi))
 
cs


**5.53(중요)  (Turtle: plot the sine and cosine functions) Write a program that plots the sine function in red and cosine in blue, as shown in Figure 5.5b.

 

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
import turtle
import math
 
# Draw X-axis
turtle.penup()
turtle.goto(-2200)
turtle.pendown()
 
turtle.goto(2200)
 
# Draw arrows
turtle.degrees()
turtle.setheading(150)
turtle.forward(20)
 
turtle.penup()
turtle.goto(2200)
turtle.pendown()
turtle.setheading(-150)
turtle.forward(20)
 
# Draw Y-axis
turtle.penup()
turtle.goto(0-80)
turtle.pendown()
turtle.goto(080)
 
turtle.penup()
turtle.goto(080)
turtle.pendown()
turtle.setheading(240)
turtle.forward(20)
 
turtle.penup()
turtle.goto(080)
turtle.pendown()
turtle.setheading(-60)
turtle.forward(20)
 
#Pi write
turtle.penup()
turtle.goto(-100-15)
turtle.pendown()
turtle.write("-2\u03c0")
 
turtle.penup()
turtle.goto(100-15)
turtle.pendown()
turtle.write("2\u03c0")
turtle.penup()
 
#draw graph
turtle.goto(-17550 * math.sin((-175 / 100* 2 * math.pi))
turtle.pendown()
turtle.color("red")
 
for x in range(-175176):
    turtle.goto(x, 50 * math.sin((x / 100* 2 * math.pi))
 
turtle.penup()
turtle.goto(-17550 * math.cos((-175 / 100* 2 * math.pi))
turtle.pendown()
turtle.color("blue")
 
for x in range(-175176):
    turtle.goto(x, 50 * math.cos((x / 100* 2 * math.pi))
 
cs


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



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

 

 

 

 

 

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

[파이썬]Chapter 6 예제 part 1 (Q.1 ~ Q.25)  (0) 2017.08.30
[파이썬]Chater 4 예제  (0) 2017.07.26
[파이썬] Chapter 3 예제  (0) 2017.07.19
파이썬 Chapter 2 예제  (0) 2017.07.14
댓글