Exemple #1
0
def e(n):
    """
    Approximates the mathematical value e using a Taylor expansion to the first n terms
    
    input n: a positive int
    """
    return 1 + sum(map(inverse, (map(math.factorial, range(1, n + 1)))))
Exemple #2
0
def e(n):
    """Creates a range from 1 - the nth term, and using the factorial function creates a list.
     Then the  return statement is +1 to get the correct value, and the sum of the inverse and the list 
     create the Taylor function of e"""
    elst = range(1, n + 1)
    elstwo = map(factorial, elst)
    return 1 + sum(map(inverse, elstwo))
Exemple #3
0
def e(x):
    "taylor expansion with x values"
    y = list(range(1, x + 1))
    q = map(fact, y)
    z = map(inverse, q)
    result = 1 + reduce(add, z)
    return result
Exemple #4
0
def e(n):
    '''Approximates the mathematical value e using a Taylor expansion.'''
    numberList = range(1, n + 1)
    factorialList = map(math.factorial, numberList)
    inverseList = map(inverse, factorialList)
    addedList = reduce(add, inverseList)

    return 1 + addedList
Exemple #5
0
def e(n):
    """approximates the mathematical value e using a Taylor polynomial
    expressed as the sum 1 + 1/1! + 1/2! + 1/3! + ... 1/n! where n is an integer given by the user
    """
    lst=range(0,n+1) #creating a list of all number 0 to n
    x= map(factorial,lst) #taking the list and making all the numbers factorials
    y = map(inverse, x) #inversing the list of the factorials
    return reduce(add,y) #adding the list of all the inverse factorials together and returning that value
Exemple #6
0
def e(n):
    '''approximates the mathematical value e using a Taylor expansion.'''
    list_of_numbers = range(1, n + 1)

    def add(x, y):
        return x + y

    return float(
        1 + reduce(add, map(inverse, map(math.factorial, list_of_numbers))))
Exemple #7
0
def e(n):
    """creates 1st list made up of values 1 through n *inclusive* because of n+1"""
    mylist=range(1,n+1)
    """creates another list that calculates the factorial val of each item in mylist"""
    faclist=map(factorial,mylist)
    """creates last list that takes the inverse of the factorial val"""
    nextlist=map(inverse, faclist)
    """adds up all the values in nextlist and adds one"""
    return (sum(nextlist)+1)
Exemple #8
0
def prime(n):
    '''takes argument n and checks whether the number is prime'''
    #first map applies the divides function which checks if n is divisible by any number excluding itself and 1
    #second map typecasts all the booleans to be string so I can apply len
    #third map applies the len() function to each string(boolean)
    #using reduce I add up all of the lengths
    #then I check whether they add up to 5*the length of the whole range itself, this means that n is not divisible by any number
    #since the above method doesn't work for 2 i just added an or statement
    if n < 2:
        return False
    return n == 2 or reduce(add,map(len,map(str,map(divides(n),range(2,n))))) == 5*len(range(2,n))
def e(n):
    list1 = range(1, n + 1)
    list2 = map(factorial, list1)
    list3 = map(inverse, list2)
    answer = sum(list3) + 1
    return answer
    """ this function approximates the math e using the Taylor series"""
    """list1 = create the range of values starting from 1 to n+1 depending on the user input"""
    """list2=this takes the input of list1 and applies the math factorial function to it as well as mapping (including) all the terms in that list"""
    """list3=this takes the inverse of the previous list2 and applies the inverse function and then maps (includes) the previous terms """
    """answer=takes the sum of list3. need add +1 because the series starts with 1+...1/(n+1)!"""
    """return= returns approx of the Taylor series function"""
Exemple #10
0
def items(capacity, itemList):
    '''helper function gets lists of weights and values'''
    if (capacity <= 0 or itemList == []): return []
    else:
        if capacity < itemList[0][0]: return items(capacity, itemList[1:])
        else:
            use_it = [itemList[0]] + items(capacity - itemList[0][0],
                                           itemList[1:])
            lose_it = items(capacity, itemList[1:])
            if sum(map(second, use_it)) > sum(map(second, lose_it)):
                return use_it
            else:
                return lose_it
Exemple #11
0
def compress(S):
    """Takes a binary string and returns a new binary string that is the input's run-to-length encoding"""
    if S == '':
        return ''
    elif S[0] == '1':
        return '0' * COMPRESSED_BLOCK_SIZE + reduce(
            add,
            map(binaryPadder, map(numToBinary, compressHelp3(
                compressHelp2(S)))))
    else:
        return reduce(
            add,
            map(binaryPadder, map(numToBinary,
                                  compressHelp3(compressHelp2(S)))))
Exemple #12
0
def compress(S):
    '''Takes as input a binary string, s, of length 64 and returns another binary string output. The output 
    string should be a run-length encoding of the input string'''
    if S == '':
        return ''
    elif S[0] == '1':
        return '0' * COMPRESSED_BLOCK_SIZE + reduce(
            add,
            map(binaryLength, map(numToBinary, compressBreak(
                compressList(S)))))
    else:
        return reduce(
            add,
            map(binaryLength, map(numToBinary,
                                  compressBreak(compressList(S)))))
Exemple #13
0
def scoreList(Rack):
    """Takes an input of a "Rack" of letters and finds which words can be produced from Dictionary, 
    and also returns the points for each word."""
    def wordLetters(S, Rack, n):
        """Takes inputs of a string "S" and the letters in "Rack", as well as a variable n, and returns Boolean True, 
        if the letters from Rack match S up to S[n]. It makes sure there are enough letters in Rack to form string S."""
        if n == len(S): return True
        if S[n] in Rack:
            if len(filter(lambda x: S[n] == x, S)) <= len(
                    filter(lambda x: S[n] == x, Rack)):
                return True and wordLetters(S, Rack, n + 1)
            else:
                return False

    def wordChecker(Rack):
        """Takes an input of a "Rack" of letters and returns a list of words that can be formed"""
        def wordCheckerHelper(S):
            if (lambda x: x in Rack, S):
                if wordLetters(S, Rack, 0):
                    return [S] + [wordScore(S, scrabbleScores)]
                else:
                    return []
            else:
                return []

        return wordCheckerHelper

    return filter(lambda a: a != [], map(wordChecker(Rack), Dictionary))
Exemple #14
0
def powerset(L):
    if L == []:
        return [[]]
    else:
        loseIt = powerset(L[1:])
        useIt = map(lambda item: [L[0]] + item, loseIt)
        return useIt + loseIt
Exemple #15
0
def powerset(lst):
    """returns the power set of the list which is the set of all subsets of the list"""
    if lst == []:
        return [[]]
    lose_it = powerset(lst[1:])
    use_it = map(lambda subset: [lst[0]] + subset, lose_it)
    return lose_it + use_it
def scoreList(Rack):
    '''score list takes the list of strings and prints out the possible words from that list'''
    def count(letter, lst):
        '''helper function that counts the amount of letters in the word(lst). '''
        if lst == '' or lst == []:
            return 0
        if letter == lst[0]:
            return count(letter, lst[1:]) + 1
            '''using the recursive the function returns the count plus 1 if the first letter is equal to the first element in the lst.'''
        return count(letter, lst[1:])
        '''if not it returns the recursive of the rest of the elements in the lst.'''

    def canSpell(rack, word):
        '''helper function to see if we can spell the word, so we need a rack of  letters but just need to find a word within that rack.'''
        if word == '':
            return True
        if count(word[0], word) > count(word[0], rack):
            return False
            '''if the count of the characters in the word is greater than that of the count letters in the rack then the return is false.'''
        return canSpell(rack, word[1:])
        '''if not then use the recursive to find the spelling of the word in the rack'''

    lst = filter(lambda word: canSpell(Rack, word), Dictionary)
    '''lst = use the filter function to to check if the rack of letters can form a word so that it correlates to the dictionary'''
    return map(lambda word: [word, wordScore(word, scrabbleScores)], lst)
    '''map goes through the words in the dictionary and makes a new list and fills it in with the word and the score of the word for all of the Rack input.  the lst will help correlate the words and letters to the dictionary '''
Exemple #17
0
def compress(s):
    '''Takes a binary string s and returns a run length encoded binary string'''
    def compresshelper(s,c):
        '''Returns seperated segments of 0's and 1's in string s'''
        if len(s)==1:
            return [c]
        else:
            if s[0]==s[1]:
                return compresshelper(s[1:],c+1)
            else:
                return [c]+compresshelper(s[1:],1)   
    def compresshelper2(y):
        '''Returns the length of each divded segment in list y'''
        return map(lambda x: numToBinary(x),y)
    z=compresshelper2(compresshelper(s,1))
    def filler(z):
        '''Pads z with 0's or 1's so it has length of 5'''
        if len(z)>COMPRESSED_BLOCK_SIZE:
            w=binaryToNum(z)-31
            return '11111'+'00000'+filler(numToBinary(w))
        else:
            q=5-len(z)
            return q*'0'+z
    z=map(filler,z)
    t=reduce(lambda x,y: x+y, z)
    if s[0]=='1':
        return '00000'+t
    else:
        return t
Exemple #18
0
def getSuggestions(user_input):
    '''For each word in the global words list, determine the edit distance of
    the user_input and the word. Return a list of tuples containing the
    (edit distance, word).
    Hint: Use map and lambda, and it's only one line of code!'''

    return map(lambda word: (fastED(user_input, word), word), words)
Exemple #19
0
def powerset(lst):
    '''Returns the power set of the list, that is, the set of all subsets of the list.'''
    if lst == []:
        return [[]]
    lose_it = powerset(lst[1:])
    use_it = map(lambda subset: [lst[0]] + subset, lose_it)
    return lose_it + use_it
Exemple #20
0
def wordsWithScore(dct, scores):
    '''List of words in dct, with their Scrabble score.

    Assume dct is a list of words and scores is a list of [letter,number]
    pairs. Return the dictionary annotated so each word is paired with its
    value. For example, wordsWithScore(Dictionary, scrabbleScores) should
    return [['a', 1], ['am', 4], ['at', 2] ...etc... ]
    '''

    # Implement your functions here.
    def letterScore(letter, scorelist):
        """gets the score for a certain letter in the list"""
        if scorelist == []:
            return 0
        first = scorelist[0]
        if first[0] == letter:
            return first[1]
        return letterScore(letter, scorelist[1:])

    #print(letterScore('c', scrabbleScores))

    def wordScore(S):
        """gets score of word given a string"""
        if S == "":
            return ['', 0]
        return [S, letterScore(S[0], scores) + wordScore(S[1:])[1]]

    #print(wordScore("wow", [['o', 10], ['w', 42]]))

    return map(wordScore, dct)
Exemple #21
0
def scoreList(Rack):
    "returns the list of words that can be made from letters in Rack along with their values"
    if checkWord(Dictionary, Rack) == []:
        return (['', 0], ['', 0])
    else:
        return map(lambda y: [y, wordScore(y, scrabbleScores)],
                   checkWord(Dictionary, Rack))
Exemple #22
0
def getScores(Rack):
    """
    Returns a list of all the scores that can be made from the given Rack.
     
    Inputs: Rack list of lowercase letters
    """
    return map(lambda x: wordScore(x, scrabbleScores), getWords(Rack))
Exemple #23
0
def bestWord(Rack):
    """Returns the highest word which can be made from a Rack based on dictionary"""
    L = scoreList(Rack)
    if L == []:
        return ['', 0]
    IL = map(lambda X: X[1], L)
    bestScore = max(IL)
    return L[ind(bestScore, IL)]
Exemple #24
0
def questify(str_list):
    '''Assume str_list is a list of strings. Returns a list of
    the same strings but with ? suffixed to each.'''
    def addQuestmark(s):
        '''Adds a question mark to a string.'''
        return s + '?'

    return map(addQuestmark, str_list)
Exemple #25
0
def scoreList(Rack):
    def check(S, temp_rack):
        if not S:
            return True
        elif S[0] in temp_rack:
            temp_rack.remove(S[0])
            return check(S[1:], temp_rack)
        return False

    runCheck = lambda S: check(S, Rack[:])
    foundIndexes = (list(
        compress(range(len(map(runCheck, Dictionary))),
                 map(runCheck, Dictionary))))

    output = lambda i: [
        Dictionary[i], wordScore(Dictionary[i], scrabbleScores)
    ]
    return map(output, foundIndexes) if foundIndexes else ["", 0]
Exemple #26
0
def wordsWithScore(dct, scores):
    '''Assume dct is a list of words and scores is a list of [letter, number]
    pairs. Return a copy of the dictionary, annotated so each word is paired
    with its value. For example, wordsWithScore(scrabbleScores, aDictionary)
    should return [["a", 1], ["am", 4], ["at", 2] ...etc... ]'''
    def scoreWord(wrd):
        return [wrd, wordScore(wrd, scores)]

    return map(scoreWord, dct)
Exemple #27
0
def powerset(lst):
    """returns the power set of the list - the set of all subsets of the list"""
    if lst == []:
        return [[]]
    #power set is a list of lists
    #this way is more efficent for getting the combinations of the characters in a list
    lose_it = powerset(lst[1:])
    use_it = map(lambda subset: [lst[0]] + subset, lose_it)
    return lose_it + use_it
Exemple #28
0
def prblm2(n):
    myList= range(1,n)
    print(myList)
    #squareList = map(makeSquare, myList)
    #print(squareList)
    #listSum = sum(squareList)
    #return listSum

    return reduce(sum, map(makeSquare, range(1,n)))
Exemple #29
0
def wordsWithScore(dct, scores):
    '''List of words in dct, with their Scrabble score.

    Assume dct is a list of words and scores is a list of [letter,number]
    pairs. Return the dictionary annotated so each word is paired with its
    value. For example, wordsWithScore(Dictionary, scrabbleScores) should
    return [['a', 1], ['am', 4], ['at', 2] ...etc... ]
    '''
    return map(lambda S: [S, wordScore(S, scores)], dct)
Exemple #30
0
def powerset(lst):
    """typically L=['one', 'two'] - return list of lists
    
    """
    if lst == []:
        return [[]]  #return empty list of list
    lose_it = powerset(lst[1:])  #lost the first element in the list
    use_it = map(lambda x: [lst[0]] + x,
                 lose_it)  #add the first element to the lose_it
    return lose_it + use_it