티스토리 뷰

파이썬/예제

[파이썬]Chater 4 예제

cll179 2017. 7. 26. 15:49

*4.1 (Algebra: solve quadratic equations) The two roots of a quadratic equation, for example, can be obtained using the following formula:

 

is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots. Write a program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0, display one root. Otherwise, display The equation has no real roots.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
a,b,c = eval(input("Enter a, b, c: "))
 
dis  = (b**2)  - (4*a*c)
 
r1 = (-+ dis**0.5/ (2*a)
r2 = (-- dis**0.5/ (2*a)
 
if dis > :
    print("The roots are ",format(r1,".6f"), format(r2,".5f"))
    
elif dis == 0:
    print("The roots is ", r1)
 
else:
    print("The equation has no real roots")
cs

 


*4.2 (Game: add three numbers) The program in Listing 4.1 generates two integers and prompts the user to enter the sum of these two integers. Revise the program to generate three single-digit integers and prompt the user to enter the sum of these three integers. 

1
2
3
4
5
6
7
8
9
import random
 
n1 = random.randint(1,9)
n2 = random.randint(1,9)
n3 = random.randint(1,9)
 
answer = eval(input("what is " +str(n1)+" + "+str(n2)+" + "+str(n3)+" ? :"))
 
print(n1,"+",n2,"+",n3," = ",answer," is ",answer == n1+n2+n3)
cs

*4.3 (Algebra: solve linear equations) You can use Cramer’s rule to solve the following system of linear equation:

 

 

 

Write a program that prompts the user to enter a, b, c, d, e, and f and display the result. If ad – bc is 0, report that The equation has no solution. 

1
2
3
4
5
6
7
8
9
a,b,c,d,e,f = eval(input("Enter a,b,c,d,e,f: "))
 
if a*- b*== 0:
    print("The equation has no solution.")
 
else :
    x = (e*- b*f)/(a*- b*c)
    y = (a*- e*c)/(a*- b*c)
    print("x is "format(x,".1f"),"and y is ",format(y,".1f") )
cs

*4.5 (Find future dates) Write a program that prompts the user to enter an integer for today’s day of the week (Sunday is 0, Monday is 1, ..., and Saturday is 6). Also prompt the user to enter the number of days after today for a future day and display the future day of the week.

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
todayNumber = eval(input("Enter today's day: "))
numOfDays = eval(input("Enter the number of days elapsed since today : "))
 
resultNumber = (todayNumber + numOfDays) % 7
    
if todayNumber == 1:
    today = "Monday"
elif todayNumber == 2:
    today = "Thuseday"
elif todayNumber == 3:
    today = "Wednesday"
elif todayNumber == 4:
    today = "Thursday"
elif todayNumber == 5:
    today = "Friday"
elif todayNumber == 6:
    today = "Saturday"
elif todayNumber == 7:
    today = "Sunday"
 
if resultNumber == 1:
    result = "Monday"
elif resultNumber == 2:
    result = "Thuseday"
elif resultNumber == 3:
    result = "Wednesday"
elif resultNumber == 4:
    result = "Thursday"
elif resultNumber == 5:
    result = "Friday"
elif resultNumber == 6:
    result = "Saturday"
elif resultNumber == 0:
    result = "Sunday"
 
print("Today is ", today, "and future day is ", result)
cs

*4.8 (Sort three integers) Write a program that prompts the user to enter three integers and displays them in increasing order. 

1
2
3
4
5
6
7
8
9
10
11
12
a,b,c = eval(input("Enter three number: "))
 
if a>b:
    a,b = b,a
 
if a>c:
    a,c = c,a
 
if b>c:
    b,c = c,b
 
print(a," ",b," ",c)
cs

*4.9 (Financial: compare costs) Suppose you shop for rice and find it in two differentsized packages. You would like to write a program to compare the costs of the packages. The program prompts the user to enter the weight and price of each package and then displays the one with the better price. 

1
2
3
4
5
6
7
8
weight1, price1 = eval(input("Enter weight and price for package 1: "))
weight2, price2 = eval(input("Enter weight and price for package 2: "))
 
if weight1 / price1 < weight2 / price2 :
    print("Packahe 1 has the better price.")
 
else :
    print("Packahe 2 has the better price.")
cs

*4.11 (Find the number of days in a month) Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month 2 and year 2000, the program should display that February 2000 has 29 days. If the user entered month 3 and year 2005, the program should display that March 2005 has 31 days.

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
monthNumber, years = eval(input("Enter month and years : "))
 
if monthNumber == 1:
    month = "January"
elif monthNumber == 2:
    month = "February"
elif monthNumber == 3:
    month = "March"
elif monthNumber == 4:
    month = "April"
elif monthNumber == 5:
    month = "May"
elif monthNumber == 6:
    month = "June"
elif monthNumber == 7:
    month = "Junly"
elif monthNumber == 8:
    month = "August"
elif monthNumber == 9:
    month = "September"
elif monthNumber == 10:
    month = "October"
elif monthNumber == 11:
    month = "November"
elif monthNumber == 12:
    month = "December"
 
if (years % == and years % 100 !=0or years % 400 == 0:
    if monthNumber == :
        print(month, " ",years,"has 29 days")
    elif monthNumber % == 0:
        print(month, " ",years,"has 30 days")
    else:
        print(month, " ",years,"has 31 days")
 
else :
    if monthNumber == :
        print(month, " ",years,"has 28 days")
    elif monthNumber % == 0:
        print(month, " ",years,"has 30 days")
    else:
        print(month, " ",years,"has 31 days")
cs

**4.15 (Game: lottery) Revise Listing 4.10, Lottery.py, to generate a three-digit lottery number. The program prompts the user to enter a three-digit number and determines whether the user wins according to the following rules:

1. If the user input matches the lottery number in the exact order, the award is $10,000.

2. If all the digits in the user input match all the digits in the lottery number, the award is $3,000.

3. If one digit in the user input matches a digit in the lottery number, the award is $1,000. 

 

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 random as ran
 
lotto = ran.randint(100,999)
 
user = eval(input("Enter a three number : "))
 
Ldigit1 = lotto//100
Ldigit2 = (lotto%100)//10
Ldigit3 = lotto%10
 
Udigit1 = user//100
Udigit2 = (user%100)//10
Udigit3 = user%10
 
if Udigit1 == Ldigit1 and Udigit2 == Ldigit2 and Udigit3 == Ldigit3:
    print("Win $ 10,000")
 
elif Udigit1 != Ldigit1 and Udigit1 != Ldigit2 and Udigit1 != Ldigit3 and \
     Udigit2 != Ldigit1 and Udigit2 != Ldigit2 and Udigit2 != Ldigit3 and \
     Udigit3 != Ldigit1 and Udigit3 != Ldigit2 and Udigit3 != Ldigit3 :
    print("lose")
 
elif (Udigit1 == Ldigit1 or Udigit1 == Ldigit2 or Udigit1 == Ldigit3) and \
     (Udigit2 == Ldigit1 or Udigit2 == Ldigit2 or Udigit2 == Ldigit3) and \
     (Udigit3 == Ldigit1 or Udigit3 == Ldigit2 or Udigit3 == Ldigit3):
    print("Win $ 3,000")
 
else :
    print("Win % 1,000")
cs

 *4.17 (Game: scissor, rock, paper) Write a program that plays the popular scissor-rockpaper game. (A scissor can cut a paper, a rock can knock a scissor, and a paper can wrap a rock.) The program randomly generates a number 0, 1, or 2 representing scissor, rock, and paper. The program prompts the user to enter a number 0, 1, or 2 and displays a message indicating whether the user or the computer wins, loses, or draws.

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
import random
 
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.")
 
    else:
        print("The computer is paper. You are scissor. You won.")
 
elif(user == 1):
    if(com == 0):
        print("The computer is scissor. You are rock. You won.")
 
    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.")
 
elif(user == 2):
    if(com == 0):
        print("The computer is scissor. You are paper. You lose.")
 
    elif(com == 1):
        print("The computer is rock. You are paper. You won.")
 
    else:
        print("The computer is paper. You are paper. It is a draw.")
cs

*4.18 (Financials: currency exchange) Write a program that prompts the user to enter the currency exchange rate between U.S. dollars and Chinese Renminbi (RMB). Prompt the user to enter 0 to convert from U.S. dollars to Chinese RMB and 1 for vice versa. Prompt the user to enter the amount in U.S. dollars or Chinese RMB to convert it to Chinese RMB or U.S. dollars, respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
rate = eval(input("Enter the exchange rate from dollor to RMB: "))
exchangeType = eval(input("Enter 0 to conver dollors to RMB and 1 vice versa: "))
 
if exchangeType == 0:
    amount = eval(input("Enter the dollor amount: "))
    result = amount * rate
    print("$",format(amount, ".1f")," is ",format(result, ".1f")," yuan")
 
elif exchangeType == 1:
    amount = eval(input("Enter the RMB amount: "))
    result = amount/rate
    print(format(amount,".1f"),"yuan is $",format(result,".2f"))
  
cs



 **4.19 (Compute the perimeter of a triangle) Write a program that reads three edges for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. The input is valid if the sum of every pair of two edges is greater than the remaining edge.

1
2
3
4
5
6
7
x,y,z = eval(input("Enter three edges: "))
 
if x+> z and x+> y and y+> x:
    print("The perimeter is ",x+y+z)
 
else:
    print("The input is invalid")
cs

 


**4.21 (Science: day of the week) Zeller’s congruence is an algorithm developed by Christian Zeller to calculate the day of the week. The formula is

 

 

 

 

where

■ h is the day of the week (0: Saturday, 1: Sunday, 2: Monday, 3: Tuesday, 4: Wednesday, 5: Thursday, 6: Friday).

■ q is the day of the month.

■ m is the month (3: March, 4: April, ..., 12: December). January and February are counted as months 13 and 14 of the previous year.

■ j is the century (i.e., ).

■ k is the year of the century (i.e., year % 100).

 Write a program that prompts the user to enter a year, month, and day of the month, and then it displays the name of the day of the week.

 

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
year = eval(input("Enter year: (e.g., 2008): "))
 
= eval(input("Enter month: 1-12: "))
if m == :
    m = 13
    year -= 1
    
elif m == :
    m = 14
    year -= 1
 
= year//100
= year%100
 
= eval(input("Enter the day of the month 1 - 31: "))
 
= (q + (26*(m+1)//10+ k + (k//4+ (j//4+ 5*j) % 7
 
if h == :
    print("Day of the week is Saturday")
 
elif h == 1:
    print("Day of the week is Sunday")
 
elif h == 2:
    print("Day of the week is Monday")
 
elif h == 3:
    print("Day of the week is Tuesday")
 
elif h == 4:
    print("Day of the week is Wednesday")
    
elif h == 5:
    print("Day of the week is Thursday")
 
elif h == 6:
    print("Day of the week is Friday")
cs

 **4.22 (Geometry: point in a circle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the circle centered at (0, 0) with radius 10. For example, (4, 5) is inside the circle and (9, 9) is outside the circle, as shown in Figure 4.8a

 

1
2
3
4
5
6
7
8
9
x,y = eval(input("Enter a point with two coordinates : "))
 
= 10
= (x**+ y**2)**0.5
 
if d < r:
    print("Point(",format(x,".1f"),", ",format(y,".1f"), ") is in the circle")
else:
    print("Point(",format(x,".1f"),", ",format(y,".1f"), ") is not in the circle")
cs

**4.23 (Geometry: point in a rectangle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the rectangle centered at (0, 0) with width 10 and height 5. For example, (2, 2) is inside the rectangle and (6, 4) is outside the rectangle, as shown in Figure 4.8b. (Hint: A point is in the rectangle if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and its vertical distance to (0, 0) is less than or equal to 5.0 / 2. Test your program to cover all cases.)  

1
2
3
4
5
6
7
x,y = eval(input("Etner a point with two coordinates: "))
 
if x <= 5.and y <= 2.0:
    print("Point(",format(x,".1f"),", ",format(y,".1f"), ") is in the rectangle")
 
else :
    print("Point(",format(x,".1f"),", ",format(y,".1f"), ") is not in the rectangle")
cs

**4.24 (Game: pick a card ) Write a program that simulates picking a card from a deck of 52 cards. Your program should display the rank (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) and suit (Clubs, Diamonds, Hearts, Spades) of the card. 

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
import random
 
rank = random.randint(1,13)
 
if rank == 1:
    rank = "ACE"
 
elif rank == 11:
    rank = "Jack"
 
elif rank == 12:
    rank = "Queen"
 
elif rank == 13:
    rank = "King"
 
suit = random.randint(0,3)
 
if suit == :
    suit = "Clubs"
 
elif suit == 1:
    suit = "Diamonds"
 
elif suit == 2:
    suit = "Hearts"
 
elif suit == 3:
    suit = "Spades"
 
print("The card you picked is the ", rank," of ", suit)
cs

*4.25 (Geometry: intersecting point) Two points on line 1 are given as (x1, y1) and (x2, y2) and on line 2 as (x3, y3) and (x4, y4), as shown in Figure 4.9a–b.

 

(y1 - y2)x - (x 1 - x 2)y = (y1 - y2)x 1 - (x 1 - x 2)y1

 

(y3 - y4)x - (x 3 - x 4)y = (y3 - y4)x 3 - (x 3 - x 4)y3

 

The intersecting point of the two lines can be found by solving the following linear equation: This linear equation can be solved using Cramer’s rule (see Exercise 4.3). If the equation has no solutions, the two lines are parallel (Figure 4.9c). Write a program that prompts the user to enter four points and displays the intersecting point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
x1,y1,x2,y2,x3,y3,x4,y4 = eval(input("Enter x1,y1,x2,y2,x3,y3,x4,y4: "))
 
cramer = (y1 - y2)*((x4-x3)) - ((x2 - x1))*(y3 - y4)
 
if cramer == 0:
    print("The two lines are parallel")
 
else :
    a = y1 - y2
    b = x2 - x1
    c = y3 - y4
    d = x4 - x3
    e = (y1 - y2)*x1 + (x2 - x1)*y1
    f = (y3 - y4)*x3 + (x4 - x3)*y3
 
    rx = (e*- b*f)/cramer
    ry = (a*- e*c)/cramer
 
    print("The intersecting point is at ("format(rx,".5f"),",",format(ry,".5f"),")")
cs

4.26 (Palindrome number) Write a program that prompts the user to enter a three-digit integer and determines whether it is a palindrome number. A number is a palindrome if it reads the same from right to left and from left to right.

1
2
3
4
5
6
7
8
9
10
number = eval(input("Enter a three-digit integer: "))
 
digit1 = number//100
digit2 = number%10
 
if digit1 == digit2 :
    print(number, "is a palidrome")
 
else :
    print(number, "is not a palindrome")
cs

**4.27 (Geometry: points in triangle?) Suppose a right triangle is placed in a plane as shown below. The right-angle point is at (0, 0), and the other two points are at (200, 0), and (0, 100). Write a program that prompts the user to enter a point with x- and y-coordinates and determines whether the point is inside the triangle.      

1
2
3
4
5
6
7
8
9
10
x,y = eval(input("Enter a point's x- and y-coordinates: "))
 
 
find = -1/2*- y + 100
 
if find >= 0:
    print("The point is in the triangle")
 
else:
    print("The point is not in the triangle")
cs

**4.28 (다시보기)(Geometry: two rectangles) Write a program that prompts the user to enter the center x-, y-coordinates, width, and height of two rectangles and determines whether the second rectangle is inside the first or overlaps with the first, as shown in Figure 4.10. Test your program to cover all cases.

 


**4.29 (Geometry: two circles) Write a program that prompts the user to enter the center coordinates and radii of two circles and determines whether the second circle is inside the first or overlaps with the first, as shown in Figure 4.11. (Hint: circle2 is inside circle1 if the distance between the two centers <= | r1 - r2| and circle2 overlaps circle1 if the distance between the two centers <= r1 + r2. Test your program to cover all cases.)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
x1,y1,r1 = eval(input("Enter circle1's center x-, y-cordinates, and radius: "))
x2,y2,r2 = eval(input("Enter circle2's center x-, y-cordinates, and radius: "))
 
centerDistance = ((x1 - x2)**+ (y1 - y2)**2)**0.5
 
if r1 - r2 < 0:
    r1,r2 = r2,r1
 
if centerDistance <= r1 - r2 :
    print("circle2 is inside circle1")
 
elif centerDistance <= r1 + r2:
    print("circle2 overlaps circle1")
 
else:
    print("circle2 does not overlap circle1")
cs

*4.30 (Current time) Revise Programming Exercise 2.18 to display the hour using a 12- hour clock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import time
 
offset = eval(input("Enter the time zone offset to GMT: "))
timeType = "AM"
 
currenttime = time.time()
 
totalseconds = int(currenttime)
currentsecond = totalseconds % 60 
 
totalMinutes = totalseconds // 60
currentMinute = totalMinutes % 60
 
totalHours = totalMinutes // 60 
currentHour = totalHours % 24 
 
resultHour = currentHour + offset
if resultHour > 11:
    timeType = "PM"
    if resultHour != 12:
        resultHour -= 12
  
print("The current time is ",resultHour,":",currentMinute,":",currentsecond,timeType)
cs

*4.31 (Geometry: point position) Given a directed line from point p0(x0, y0) to p1(x1, y1), you can use the following condition to decide whether a point p2(x2, y2) is on the left side of the line, on the right side of the line, or on the same line (see Figure 4.12): 

Write a program that prompts the user to enter the x- and y-coordinates for the three points p0, p1, and p2 and displays whether p2 is on the left side of the line from p0 to p1, on the right side, or on the same line.

 

1
2
3
4
5
6
7
8
9
10
11
12
x0,y0, x1,y1, x2,y2 = eval(input("Enter coordinates for the three points p0, p1 and p2: "))
 
condition = (x1-x0)*(y2-y0) - (x2-x0)*(y1-y0)
 
if condition > 0:
    print("p2 is on the left side of the line from p0 to p1")
 
elif condition == 0:
    print("p2 is on the same line of the line from p0 to p1")
 
else :
    print("p2 is on the right side of the line from p0 to p1")
cs

 *4.33 (Decimal to hex) Write a program that prompts the user to enter an integer between 0 and 15 and displays its corresponding hex number.

1
2
3
4
5
6
7
8
9
10
number = eval(input("Enter a demical value(0 to 15): "))
 
if number < or number > 15:
    print("Invalid input")
 
else :
    if number >= 10:
        print(chr(number+55))
    else:
        print(number)
cs

**4.37 (Turtle: point in a rectangle?) Write a program that prompts the user to enter a point (x, y) and checks whether the point is within the rectangle centered at (0, 0) with width 100 and height 50. Display the point, the rectangle, and a message indicating whether the point is inside the rectangle in the window, as shown in Figure 4.14.

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 turtle as t
 
x, y = eval(input("Enter the point(x, y): "))
 
t.hideturtle()
 
t.penup()
t.goto(-50-25)
t.pendown()
t.goto(50-25)
t.goto(5025)
t.goto(-5025)
t.goto(-50-25)
 
t.penup()
t.goto(x,y)
t.color("red")
t.dot(5)
t.color("black")
 
if -50 < x < 50 and -25 < y < 25:
    t.goto(-50,-60)
    t.write("The point is insdie the rectangle")
 
else :
    t.goto(-50,-60)
    t.write("The point is not insdie the rectangle")
cs

*4.39 (Turtle: two circles) Write a program that prompts the user to enter the center coordinates and radii of two circles and determines whether the second circle is inside the first or overlaps with the first, as shown in Figure 4.16. 

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
import turtle as t
 
x1,y1,r1 = eval(input("Enter circle1's center x-, y,coordinates, and radius: "))
x2,y2,r2 = eval(input("Enter circle2's center x-, y,coordinates, and radius: "))
 
centerDistance = ((x1 - x2)**+ (y1 - y2)**2)**0.5
 
t.hideturtle()
 
t.penup()
t.goto(x1,y1)
t.pendown()
t.circle(r1)
 
t.penup()
t.goto(x2,y2)
t.pendown()
t.circle(r2)
 
t.penup()
t.goto(x1+r1+10, y1)
 
if r1 - r2 < 0:
    r1,r2 = r2,r1
 
if centerDistance <= r1 - r2 :
    t.write("circle2 is inside circle1")
 
elif centerDistance <= r1 + r2 :
    t.write("circle2 overlaps circle1")
 
else :
    t.write("circle2 does not overlap circle1")
cs

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



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

 

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

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