Problem 8: make_averaged function 구현
- make_averaged function
- original_function을 인자로 받는 high-order function
- return값은 original_function과 동일한 수의 인수를 받는 함수이다.
- 이 함수를 호출하면 이것은 original_function을 반복적으로 호출한 평균값을 리턴할 것이다.
- 특히, 이 함수는 original_function을 total_samples횟수만큼 호출해야하고 이 호출들의 결과의 평균을 반환해야 한다.
- 주의할 점
- 기본 룰은 굴린 dice의 수의 합을 구하는 것. 여기에 규칙을 적용하는 것임 주의
def make_averaged(original_function, total_samples=1000):
"""Return a function that returns the average value of ORIGINAL_FUNCTION
called TOTAL_SAMPLES times.
To implement this function, you will have to use *args syntax, a new Python
feature introduced in this project. See the project description.
>>> dice = make_test_dice(4, 2, 5, 1)
>>> averaged_dice = make_averaged(roll_dice, 1000)
>>> averaged_dice(1, dice)
3.0
"""
# BEGIN PROBLEM 8
def f(*args):
sum = 0
for i in range(total_samples):
sum += original_function(*args)
return sum / total_samples
return f
# END PROBLEM 8
Problem 9: max_scoring_num_rolls 함수 구현하기
- max_scoring_num_rolls
- turn마다 최대 평균 점수를 제공하는 함수
- 주사위를 1회부터 10회까지 던지고(그게 각각의 turn)
- turn마다 나온 average값들을 비교해서 그중에 max값을 나오게 하는 number of rolls를 리턴함
- make_averaged와 roll_dice를 사용해야 한다.
- 만약 두 roll숫자가 최대평균점수에 대해 동점인 경우 더 낮은 숫자를 반환함
- if both 3 and 6 achieve a maximum average score, return 3.
def max_scoring_num_rolls(dice=six_sided, total_samples=1000):
"""Return the number of dice (1 to 10) that gives the highest average turn score
by calling roll_dice with the provided DICE a total of TOTAL_SAMPLES times.
Assume that the dice always return positive outcomes.
>>> dice = make_test_dice(1, 6)
>>> max_scoring_num_rolls(dice)
1
"""
# BEGIN PROBLEM 9
max = 0
max_index = 0
dice_average = make_averaged(roll_dice, total_samples)
for i in range(1, 11):
tmp = dice_average(i, dice)
if tmp > max:
max_index = i
max = tmp
return max_index
# END PROBLEM 9
Problem 10: oink_points_strategy 구현하기
- oink_points_strategy
- 0을 굴리는게 가장 유리할 때 이 전략을 사용한다.
- 이 전략은 threshold로 넘겨준 값보다 같거나 크면 0을 리턴하게 하고
안 넘으면 num_rolls로 받아온 값을 이용한다.
- 이 전략은 Pigs on Prime 규칙을 고려하지 않는다.
def oink_points_strategy(score, opponent_score, threshold=8, num_rolls=6):
"""This strategy returns 0 dice if that gives at least THRESHOLD points, and
returns NUM_ROLLS otherwise.
"""
# BEGIN PROBLEM 10
o_points = oink_points(score, opponent_score)
if o_points >= threshold:
return 0
return num_rolls
# END PROBLEM 10
Problem 11: pigs_on_prime_strategy 구현하기
- pigs_on_prime_strategy
- 이 전략은 이 규칙을 유발하고 0이 아닌 점수를 얻는 경우에 항상 0을 굴린다
- 다른 경우에는 만약 threshold값 이상이면 0을 굴리고 그렇지 않으면 num_rolls값을 굴린다.
def pigs_on_prime_strategy(score, opponent_score, threshold=8, num_rolls=6):
"""This strategy returns 0 dice when this would result in Pigs on Prime taking
effect. It also returns 0 dice if it gives at least THRESHOLD points.
Otherwise, it returns NUM_ROLLS.
"""
# BEGIN PROBLEM 11
if is_prime(oink_points(score, opponent_score) + score):
return 0
else:
return oink_points_strategy(score, opponent_score, threshold, num_rolls)
# END PROBLEM 11