UCB CS61A 2020Fall Project2 Cats

"""Typing test implementation"""

from cmath import inf
from distutils.util import convert_path
from this import d

from numpy import append
from utils import lower, split, remove_punctuation, lines_from_file
from ucb import main, interact, trace
from datetime import datetime


###########
# Phase 1 #
###########


def choose(paragraphs, select, k):
    """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
    paragraph returns true. If there are fewer than K such paragraphs, return
    the empty string.
    """
    # BEGIN PROBLEM 1
    "*** YOUR CODE HERE ***"
    
    res =  [para for para in paragraphs if select(para)]
    if len(res) >= k+1:
        return res[k]
    else:
        return ''
    # END PROBLEM 1


def about(topic):
    """Return a select function that returns whether a paragraph contains one
    of the words in TOPIC.

    >>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
    >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0)
    'Cute Dog!'
    >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1)
    'Nice pup.'
    """
    assert all([lower(x) == x for x in topic]), 'topics should be lowercase.'
    # BEGIN PROBLEM 2
    "*** YOUR CODE HERE ***"
    def judge(sentence):
        convert_stc = split(remove_punctuation(lower(sentence)))
        for tp in topic:
            for stc in convert_stc:
                if tp == stc:
                    return True
        return False
    return judge
    # END PROBLEM 2


def accuracy(typed, reference):
    """Return the accuracy (percentage of words typed correctly) of TYPED
    when compared to the prefix of REFERENCE that was typed.

    >>> accuracy('Cute Dog!', 'Cute Dog.')
    50.0
    >>> accuracy('A Cute Dog!', 'Cute Dog.')
    0.0
    >>> accuracy('cute Dog.', 'Cute Dog.')
    50.0
    >>> accuracy('Cute Dog. I say!', 'Cute Dog.')
    50.0
    >>> accuracy('Cute', 'Cute Dog.')
    100.0
    >>> accuracy('', 'Cute Dog.')
    0.0
    """
    typed_words = split(typed)
    reference_words = split(reference)
    # BEGIN PROBLEM 3
    "*** YOUR CODE HERE ***"
    lengtha = len(typed_words)
    lengthb = len(reference_words)
    length = min(lengtha,lengthb)
    res = 0
    for i in range(length):
        if typed_words[i] == reference_words[i]:
            res += 1
    if lengtha == 0:
        return 0.0
    return res / lengtha * 100
    # END PROBLEM 3


def wpm(typed, elapsed):
    """Return the words-per-minute (WPM) of the TYPED string."""
    assert elapsed > 0, 'Elapsed time must be positive'
    # BEGIN PROBLEM 4
    "*** YOUR CODE HERE ***"
    
    return float(12 * len(typed)/elapsed)
    # END PROBLEM 4


def autocorrect(user_word, valid_words, diff_function, limit):
    """Returns the element of VALID_WORDS that has the smallest difference
    from USER_WORD. Instead returns USER_WORD if that difference is greater
    than LIMIT.
    """
    # BEGIN PROBLEM 5
    "*** YOUR CODE HERE ***"
    flag = 0
    res = inf
    for i in range(len(valid_words)):
        word = valid_words[i]
        if valid_words[i] == user_word:
            return user_word
        if diff_function(user_word,word,limit) < res:
            res = diff_function(user_word,word,limit)
            flag = i
    if res <= limit:
        return valid_words[flag]
    else:
        return user_word
        
    # END PROBLEM 5


def shifty_shifts(start, goal, limit):
    """A diff function for autocorrect that determines how many letters
    in START need to be substituted to create GOAL, then adds the difference in
    their lengths.
    """
    # BEGIN PROBLEM 6
    # assert False, 'Remove this line'
    lengtha = len(start)
    lengthb = len(goal)
    lengthmin = min(lengtha,lengthb)
    lengthmax = max(lengtha,lengthb)
    res = 0
    def helper(start,goal,res):
        if start[0] != goal[0]:
            res+=1
        if res > limit:
            return res
        if start[1:] and goal[1:]:
            return helper(start[1:],goal[1:],res)
        else:
            return res + (lengthmax-lengthmin)
    return helper(start,goal,res)

    # END PROBLEM 6


def pawssible_patches(start, goal, limit):
    """A diff function that computes the edit distance from START to GOAL."""
    # assert False, 'Remove this line'
    if(start == goal):
        return 0

    elif limit<0:
        return 0

    if len(start)==0 or len(goal) == 0: # Fill in the condition
        # BEGIN
        "*** YOUR CODE HERE ***"
        return max(len(start),len(goal))
        # END

    elif start[0]==goal[0]: # Feel free to remove or add additional cases
        # BEGIN
        "*** YOUR CODE HERE ***"
        return pawssible_patches(start[1:],goal[1:],limit)
        # END

    else:
        add_diff = pawssible_patches(start,goal[1:],limit-1) + 1
        remove_diff = pawssible_patches(start[1:],goal,limit-1) + 1
        substitute_diff = pawssible_patches(start[1:],goal[1:],limit-1) + 1
        
        # BEGIN
        "*** YOUR CODE HERE ***"
        return min(add_diff,remove_diff,substitute_diff)
        # END


def final_diff(start, goal, limit):
    """A diff function. If you implement this function, it will be used."""
    assert False, 'Remove this line to use your final_diff function'


###########
# Phase 3 #
###########


def report_progress(typed, prompt, user_id, send):
    """Send a report of your id and progress so far to the multiplayer server."""
    # BEGIN PROBLEM 8
    "*** YOUR CODE HERE ***"
    res = 0
    for i in range(len(typed)):
        if typed[i]==prompt[i]:
            res += 1
        else:
            break
    res = res/len(prompt)
    send({'id': user_id, 'progress': res})
    return res
    # END PROBLEM 8


def fastest_words_report(times_per_player, words):
    """Return a text description of the fastest words typed by each player."""
    game = time_per_word(times_per_player, words)
    fastest = fastest_words(game)
    report = ''
    for i in range(len(fastest)):
        words = ','.join(fastest[i])
        report += 'Player {} typed these fastest: {}\n'.format(i + 1, words)
    return report


def time_per_word(times_per_player, words):
    """Given timing data, return a game data abstraction, which contains a list
    of words and the amount of time each player took to type each word.

    Arguments:
        times_per_player: A list of lists of timestamps including the time
                          the player started typing, followed by the time
                          the player finished typing each word.
        words: a list of words, in the order they are typed.
    """
    # BEGIN PROBLEM 9
    "*** YOUR CODE HERE ***"
    res = []
    for times in times_per_player:
        res.append([times[i]-times[i-1] for i in range(1,len(times))])
    return game(words,res)
    # END PROBLEM 9


def fastest_words(game):
    """Return a list of lists of which words each player typed fastest.

    Arguments:
        game: a game data abstraction as returned by time_per_word.
    Returns:
        a list of lists containing which words each player typed fastest
    """
    player_indices = range(len(all_times(game)))  # contains an *index* for each player
    word_indices = range(len(all_words(game)))    # contains an *index* for each word
    # BEGIN PROBLEM 10
    "*** YOUR CODE HERE ***"
    res = [[] for i in player_indices]
    for i in word_indices:
        for j in player_indices:
            if j==0:
                min_time = time(game,j,i)
                flag = 0
            elif time(game,j,i) < min_time:
                min_time = time(game,j,i)
                flag = j
        res[flag].append(word_at(game,i))
    return res


    # END PROBLEM 10


def game(words, times):
    """A data abstraction containing all words typed and their times."""
    assert all([type(w) == str for w in words]), 'words should be a list of strings'
    assert all([type(t) == list for t in times]), 'times should be a list of lists'
    assert all([isinstance(i, (int, float)) for t in times for i in t]), 'times lists should contain numbers'
    assert all([len(t) == len(words) for t in times]), 'There should be one word per time.'
    return [words, times]


def word_at(game, word_index):
    """A selector function that gets the word with index word_index"""
    assert 0 <= word_index < len(game[0]), "word_index out of range of words"
    return game[0][word_index]


def all_words(game):
    """A selector function for all the words in the game"""
    return game[0]


def all_times(game):
    """A selector function for all typing times for all players"""
    return game[1]


def time(game, player_num, word_index):
    """A selector function for the time it took player_num to type the word at word_index"""
    assert word_index < len(game[0]), "word_index out of range of words"
    assert player_num < len(game[1]), "player_num out of range of players"
    return game[1][player_num][word_index]


def game_string(game):
    """A helper function that takes in a game object and returns a string representation of it"""
    return "game(%s, %s)" % (game[0], game[1])

enable_multiplayer = False  # Change to True when you're ready to race.

##########################
# Command Line Interface #
##########################


def run_typing_test(topics):
    """Measure typing speed and accuracy on the command line."""
    paragraphs = lines_from_file('data/sample_paragraphs.txt')
    select = lambda p: True
    if topics:
        select = about(topics)
    i = 0
    while True:
        reference = choose(paragraphs, select, i)
        if not reference:
            print('No more paragraphs about', topics, 'are available.')
            return
        print('Type the following paragraph and then press enter/return.')
        print('If you only type part of it, you will be scored only on that part.\n')
        print(reference)
        print()

        start = datetime.now()
        typed = input()
        if not typed:
            print('Goodbye.')
            return
        print()

        elapsed = (datetime.now() - start).total_seconds()
        print("Nice work!")
        print('Words per minute:', wpm(typed, elapsed))
        print('Accuracy:        ', accuracy(typed, reference))

        print('\nPress enter/return for the next paragraph or type q to quit.')
        if input().strip() == 'q':
            return
        i += 1


@main
def run(*args):
    """Read in the command-line argument and calls corresponding functions."""
    import argparse
    parser = argparse.ArgumentParser(description="Typing Test")
    parser.add_argument('topic', help="Topic word", nargs='*')
    parser.add_argument('-t', help="Run typing test", action='store_true')

    args = parser.parse_args()
    if args.t:
        run_typing_test(args.topic)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的UCB2算法的Python实现,假设有10个臂,每个臂的回报率都是服从0到1之间的均匀分布: ```python import math import random num_arms = 10 # 臂数量 counts = [0] * num_arms # 每个臂的选中次数 values = [0.0] * num_arms # 每个臂的平均回报率 variances = [0.0] * num_arms # 每个臂选中次数的方差 t = 0 # 时间步数 # UCB2算法 def ucb2(t): global num_arms, counts, values, variances # 选中每个臂至少一次 if t < num_arms: return t # 计算每个臂的UCBucb_values = [0.0] * num_arms for i in range(num_arms): if counts[i] == 0: ucb_values[i] = float('inf') else: bonus = math.sqrt((2 * math.log(t)) / counts[i]) ucb_values[i] = values[i] + bonus + math.sqrt(variances[i]) # 选择UCB值最大的臂 return ucb_values.index(max(ucb_values)) # 进行一次UCB2算法的操作 def ucb2_step(): global counts, values, variances, t # 选择臂 arm = ucb2(t) t += 1 # 生成回报 reward = random.uniform(0.0, 1.0) # 更新计数、平均回报率和方差 counts[arm] += 1 n = counts[arm] value = values[arm] values[arm] = ((n - 1) / n) * value + (1 / n) * reward variance = variances[arm] variances[arm] = ((n - 1) / n) * variance + (1 / (n - 1)) * (reward - value) * (reward - values[arm]) # 进行多次UCB2算法的操作 def ucb2_simulate(num_steps): global counts, values, variances, t counts = [0] * num_arms values = [0.0] * num_arms variances = [0.0] * num_arms t = 0 for i in range(num_steps): ucb2_step() # 返回每个臂的平均回报率 return values ``` 上述代码中,`ucb2()`函数用于计算每个臂的UCB值,`ucb2_step()`函数用于执行一次UCB2算法的操作,`ucb2_simulate()`函数用于进行多次UCB2算法的操作,并返回每个臂的平均回报率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值