示例#1
0
def pages (page_spec : str, unique :  bool) -> [int]: #result in ascending order
    page_struct = (set() if unique else [])
    page_comp = re.compile(open('repattern2a.txt', 'r').read())
    for spec in page_spec.split(','):
        g1, g2, g3, g4 = page_comp.match(spec).groups()
        assert page_comp.match(spec), f'pages: in page specification {spec}, No Match Found!'
        if not g2:
            if unique: page_struct.add(int(g1))
            else: page_struct.append(int(g1))
        if g2 == '-': 
            assert (int(g1) <= int(g3)), f'pages: in page specification {spec}, {g1} > {g3}.'
            if unique: 
                if not g4: page_struct.update({pg for pg in irange(int(g1), int(g3))})
                else: page_struct.update({pg for pg in irange(int(g1), int(g3), int(g4))})
            else:
                if not g4: page_struct.extend([pg for pg in irange(int(g1), int(g3))])
                else: page_struct.extend([pg for pg in irange(int(g1), int(g3), int(g4))])
        elif g2 == ':':
            if unique: 
                if not g4: page_struct.update({pg for pg in range(int(g1), int(g1)+int(g3))})
                else: page_struct.update({pg for pg in range(int(g1), int(g1)+int(g3), int(g4))})
            else:
                if not g4: page_struct.extend([pg for pg in range(int(g1), int(g1)+int(g3))])
                else: page_struct.extend([pg for pg in range(int(g1), int(g1)+int(g3), int(g4))])
    return sorted(page_struct)
示例#2
0
def pages(page_spec: str, unique: bool) -> [int]:  #result in ascending order
    answer = []
    pattern = r"^([1-9][0-9]*)(?:(?:(:|-)([1-9][0-9]*)(?:(?:\/)([1-9][0-9]*))?))?$"
    seperate = page_spec.split(",")
    for i in seperate:
        m = re.match(pattern, i).groups()
        assert m != None, 'No match'
        if m[1] == None:
            answer.append(int(m[0]))
        else:
            if m[1] == "-":
                assert int(m[2]) >= int(
                    m[0]
                ), f"pages: in page specification {m[0]}-{m[2]}, {m[2]} > {m[0]}"
                if m[3] != None:
                    answer += [
                        k for k in irange(int(m[0]), int(m[2]), int(m[3]))
                    ]
                else:
                    answer += [k for k in irange(int(m[0]), int(m[2]))]
            elif m[1] == ":":
                if m[3] != None:
                    answer += [
                        k for k in irange(int(m[0]),
                                          int(m[0]) + int(m[2]) - 1, int(m[3]))
                    ]
                else:
                    answer += [
                        k for k in irange(int(m[0]),
                                          int(m[0]) + int(m[2]) - 1)
                    ]
    if unique == True:
        answer = list(set(answer))
    return sorted(answer)
示例#3
0
def pages(page_spec: str, unique) -> [int]:  #result in ascending order
    result = []
    pages = page_spec.split(',')
    for page in pages:
        m = re.match(
            '^([1-9][0-9]*)(?:(:|-)([1-9][0-9]*)(?:/([1-9][0-9]*))?)?$', page)
        assert m != None
        fpage, extra, lpage, skip = m.groups()
        if extra == None:
            result.append(int(fpage))
        else:
            if extra == '-':
                assert int(fpage) <= int(lpage)
                if skip == None:
                    result.extend(irange(int(fpage), int(lpage)))
                else:
                    result.extend(irange(int(fpage), int(lpage), int(skip)))
            else:
                if skip == None:
                    result.extend(range(int(fpage), (int(fpage) + int(lpage))))
                else:
                    result.extend(
                        range(int(fpage), (int(fpage) + int(lpage)),
                              int(skip)))
    if unique:
        return sorted(set(result))
    else:
        return sorted(result)
示例#4
0
 def best_approximation(self, n):
     best = Rational(0)
     for num in irange(0, 10**n - 1):
         for denom in irange(1, 10**n - 1):
             if abs(self - Rational(num, denom)) < abs(self - best):
                 best = Rational(num, denom)
     return best
示例#5
0
 def best_approximation(self,n):
     best = Rational(0)
     for num in irange(0,10**n-1):
         for denom in irange(1,10**n-1):
             if abs(self-Rational(num,denom)) < abs(self-best):
                 best = Rational(num,denom)
     return best
示例#6
0
def pages (page_spec : str, unique :  bool) -> [int]: #result in ascending order
    ret =[]
    pages = page_spec.split(",")
    for page_string in pages:
        mat =[]
        try:
            p2 = open('repattern2a.txt').read().rstrip() # Read pattern on first line
            m = re.match(p2,page_string)
            for mt in m.groups():
                if mt != None:
                    mat.append(mt)
                else:
                    mat.append(None)
        except:
            raise AssertionError('failed on regular expression matching')
                
        # if its a range...
        if mat[1] == '-':
            #make sure its a valid range
            if mat[0] and mat[2] != None:
                if int(mat[0]) > int(mat[2]):
                    raise AssertionError('failed range is smaller than starting page') 
            
            #check for a divisor
            if mat[3] != None:
             for p in irange(int(mat[0]), int(mat[2]), int(mat[3])):
                ret.append(p)
            # equal range
            elif int(mat[0]) == int(mat[2]):
                ret.append(mat[0])
            # if no divisor but range
            else:
                for p in irange(int(mat[0]), int(mat[2])):
                    ret.append(p)
                
        #if its a constructed range
        elif mat[1] == ':':
            #check for a divisor
            if mat[3] != None:
             for p in irange(int(mat[0]), int(mat[0])+int(mat[2]), int(mat[3])):
                ret.append(p)
            # otherwise
            # if no divisor but range
            else:
                for p in irange(int(mat[0]), int(mat[0])+int(mat[2])):
                    ret.append(p)
        # or no divisor and range   
        else:
            ret.append(int(mat[0]))
    
    if unique:
        s = {item for item in ret}
        return sorted(list(s))        
    else:
        return sorted(ret)        
示例#7
0
文件: graph.py 项目: shwilliams/ICS33
def random_graph(nodes,percent):
    from goody import irange
    from random import random,randint
    g = Graph()
    for i in irange(nodes):
        g.add_node(str(i))
    for i in irange(nodes):
        for j in irange(nodes):
            if 100*random() <= percent:
                g.add_edge((str(i),str(j)),randint(0,100))
    return g
示例#8
0
def random_graph(nodes, percent):
    from goody import irange
    from random import random, randint
    g = Graph()
    for i in irange(nodes):
        g.add_node(str(i))
    for i in irange(nodes):
        for j in irange(nodes):
            if 100 * random() <= percent:
                g.add_edge((str(i), str(j)), randint(0, 100))
    return g
 def __len__(self):
     days_total = 0
     if self.year != 0:
         for years in irange(0, self.year):
             if years != self.year:
                 for months in irange(12):
                     days_total += self.days_in(years, months)
             else:
                 for months in irange(self.month - 1):
                     days_total += self.days_in(years, months)
         days_total += self.day - 1
         return days_total
     for month_self in irange(self.month - 1):
         days_total += self.days_in(self.year, month_self)
     days_total += self.day - 1
     return days_total
示例#10
0
 def __call__(self, x):
     return_str = '' if self.num > 0 else '-'
     return_str += str(self.num // self.denom)
     return_str += '.'
     for dec_place in irange(1, x):
         return_str += str((self.num * (10**dec_place)) // self.denom)[-1:]
     return return_str
示例#11
0
def pages(page_spec: str) -> [int]:  #result in ascending order (no duplicates)
    return_list = []
    page_check = re.split(',', page_spec)
    pattern_str = "^(?:(\s*[1-9]+\d*\s*|\s*[1-9]+\s*)(?:(?:([:,-]))([1-9]+\d*\s*|\s+[1-9]\d*\s*)?)?)$"
    object_list = [
        re.match(pattern_str, ''.join(page_check[query].split()))
        for query in range(len(page_check))
    ]
    assert object_list != [None]
    for match_object in object_list:
        assert match_object != None
        if match_object.group(2) == '-':
            assert int(match_object.group(1)) < int(match_object.group(
                3)), 'pages: in page sequence {1}-{0}, {1} > {0}'.format(
                    match_object.group(3), match_object.group(1))
            return_list.extend([
                page for page in irange(int(match_object.group(1)),
                                        int(match_object.group(3)))
            ])
        elif match_object.group(2) == ':':
            return_list.extend([
                page for page in range(
                    int(match_object.group(1)),
                    int(match_object.group(1)) + int(match_object.group(3)))
            ])
        else:
            return_list.append(int(match_object.group(1)))
    return sorted(set(return_list))
示例#12
0
def pages(page_spec: str, unique: bool) -> [int]:  #result in ascending order
    spec_list = page_spec.split(',')
    page_list = []

    for spec in spec_list:
        match = re.match('^([1-9]\d*)(-|:)?([1-9]\d*)?/?([1-9]\d*)?$', spec)
        groups = list(match.groups())

        if groups[0] != None:
            if groups[1] == None:
                #Adds one page only
                page_list.append(int(groups[0]))

            elif groups[1] == '-':
                #Adds pages from first # to second #
                assert int(groups[0]) <= int(
                    groups[2]
                ), f'pages: in page specification {groups[0]}-{groups[2]}, {groups[0]} > {groups[2]}'
                for pg in irange(
                        int(groups[0]), int(groups[2]),
                        int(groups[3]) if groups[3] is not None else 1):
                    page_list.append(pg)

            elif groups[1] == ':':
                #Adds pages from first # and n number more pages
                for pg in range(
                        int(groups[0]),
                        int(groups[0]) + int(groups[2]),
                        int(groups[3]) if groups[3] is not None else 1):
                    page_list.append(pg)

            if unique == True:
                page_list = list(set(page_list))

    return sorted(page_list)
def fact2(n):
    if type(n) is not int:
        raise TypeError("factorial(" + str(n) + ") must be called with an int argument")
    if n < 0:
        raise ValueError("factorial(" + str(n) + ") not defined for negative values")
    answer = 1
    for i in irange(2, n):
        answer *= i
    return answer
示例#14
0
def produce_text(corpus, text, count):
    os = len(text)
    for i in irange(count):
        key = tuple(start[-os:])
        if key not in corpus:
            text.append(None)
            return text
        start.append(choice(corpus[key]))
    return start
示例#15
0
def read_corpus(os,file):
    corpus = dict() # defaultdict(list)
    key =[next(file) for i in irange(os)]
    for w in file:
        if tuple(key) not in corpus or w not in corpus[tuple(key)]:# w not in corpus[tuple(key)]:
            corpus.setdefault(tuple(key),list()).append(w)
        key.pop(0)
        key.append(w)
    return corpus
示例#16
0
def produce_text(corpus,text,count):
    os = len(text)
    for i in irange(count):
        key = tuple(start[-os:])
        if key not in corpus:
            text.append(None)
            return text
        start.append(choice(corpus[key]))
    return start    
示例#17
0
def read_corpus(os, file):
    corpus = dict()  # defaultdict(list)
    key = [next(file) for i in irange(os)]
    for w in file:
        if tuple(key) not in corpus or w not in corpus[tuple(
                key)]:  # w not in corpus[tuple(key)]:
            corpus.setdefault(tuple(key), list()).append(w)
        key.pop(0)
        key.append(w)
    return corpus
示例#18
0
def fact2(n):
    if type(n) is not int:
        raise TypeError('factorial(' + str(n) +
                        ') must be called with an int argument')
    if n < 0:
        raise ValueError('factorial(' + str(n) +
                         ') not defined for negative values')
    answer = 1
    for i in irange(2, n):
        answer *= i
    return answer
示例#19
0
def compute_pi(n):
    def prod(r):
        answer = 1
        for i in r:
            answer *= i
        return answer

    answer = Rational(1,2)
    x      = Rational(1,2)
    for i in irange(1,n):
        big = 2*i+1
        answer += Rational(prod(range(1,big,2)),prod(range(2,big,2)))*x**big/big
    return 6*answer
示例#20
0
def compute_pi(n):
    def prod(r):
        answer = 1
        for i in r:
            answer *= i
        return answer

    answer = Rational(1, 2)
    x = Rational(1, 2)
    for i in irange(1, n):
        big = 2 * i + 1
        answer += Rational(prod(range(1, big, 2)), prod(range(
            2, big, 2))) * x**big / big
    return 6 * answer
示例#21
0
def pages (page_spec : str) -> [int]: #result in ascending order (no duplicates)
    page_list = []
    page_str = re.compile(r'^(?: )*([1-9][0-9]*)(?: )*(?:([\-:])(?: *)([1-9][0-9]*)(?: *))?$')
    pages = page_spec.split(',')
    for page in pages:
        p = page_str.match(page)
        assert p != None, 'Page Sequence does not match regular expression.'
        if p.group(2) == '-':
            assert int(p.group(1)) <= int(p.group(3)), 'pages: in page sequence {}-{}, {} > {}'.format(p.group(1), p.group(3), p.group(1), p.group(3))
            page_list.extend(list(irange(int(p.group(1)), int(p.group(3)))))
        elif p.group(2) == ':':
            page_list.extend(list(range(int(p.group(1)), int(p.group(1)) + int(p.group(3)))))
        else:
            page_list.append(int(p.group(1)))
    return sorted(set(page_list))
示例#22
0
    def __call__(self,*args):
        if args in self.cache:
            return self.cache[args]
        else:
            answer = self.f(*args)
            self.cache[args] = answer
        return answer

    def reset_cache(self):
        self.cache = {}
        
    def __getattr__(self,attr):        # if attr not here, try self.f
        return getattr(self.f,attr)





if __name__ == '__main__':
    from goody import irange
    
    @Memoize
    def fib(n):
        if    n == 0: return 1
        elif  n == 1: return 1
        else:         return fib(n-1) + fib(n-2)
    
    print('\nacking calls for recursive fib(onacci)')    
    for i in irange(0,50): 
            fib.reset_cache()  # if Memoize decorator
            print('  Fib('+str(i)+') =', fib(i))
示例#23
0
        else:
            answer = self.f(*args)
            self.cache[args] = answer
        return answer

    def reset_cache(self):
        self.cache = {}
        
    def __getattr__(self,attr):        # if attr not here, try self.f
        return getattr(self.f,attr)





if __name__ == '__main__':
    from goody import irange
    
    @Memoize
    @Track_Calls
    def fib(n):
        if    n == 0: return 1
        elif  n == 1: return 1
        else:         return fib(n-1) + fib(n-2)
    
    print('\nTracking calls for recursive fib(onacci) with Memoizing')    
    for i in irange(0,5): 
            fib.reset_calls()  # if Track_Calls decorator
            fib.reset_cache()  # if Memoize decorator
            print('  Fib('+str(i)+') =', fib(i), 'and # calls for fib('+str(i)+') =', fib.called())
示例#24
0
    mins,maxs=-1,-1
    for k in sorted(corpus):
        print(' ',k,'can be followed by any of', corpus[k])
        mins = len(corpus[k]) if mins == -1 or len(corpus[k]) < mins else mins
        maxs = len(corpus[k]) if maxs == -1 or len(corpus[k]) > maxs else maxs
        if len(corpus[k]) == 46:
            print (k,corpus[k])
    print('min/max =',str(mins)+'/'+str(maxs)) 


def produce_text(corpus,text,count):
    os = len(text)
    for i in irange(count):
        key = tuple(start[-os:])
        if key not in corpus:
            text.append(None)
            return text
        start.append(choice(corpus[key]))
    return start    



os = prompt.for_int('Enter order statistic',is_legal=lambda x : x >= 1)
corpus = read_corpus(os, goody.read_file_values(goody.safe_open('Enter file to process', 'r', 'Cannot find that file')))
print_corpus(corpus)

print('\nEnter '+str(os)+' words to start with')
start = [prompt.for_string('Enter word '+str(i)) for i in irange(os)]
how_many = prompt.for_int('Enter # of words to generate',is_legal=lambda x : x > 0)
text = produce_text(corpus,start,how_many)
print('Random text =',text)
示例#25
0
def compute_prefixes(fq): 
    return {fq[0:i] for i in irange(1,len(fq))} 
    return d

if __name__ == '__main__':
    from goody import irange
    from predicate import is_prime
    import driver
   
    # Feel free to test other cases as well
    
    print('Testing one_of: is_vowel')
    is_vowel = one_of(['a','e','i','o','u'])
    print([(c,is_vowel(c)) for c in "tobeornottobe"])
        
    print('\nTesting opposite_of: is_composite')
    is_composite = opposite_of(is_prime)
    print(sorted({i:is_composite(i) for i in irange(2,10)}.items()))
        
    print('\nTesting opposite_of: is_consonant')
    is_consonant = opposite_of(is_vowel)
    print([(c,is_consonant(c)) for c in "tobeornottobe"])
        
    print('\nTesting sort_names: ')
    print(sort_names([('John','Smith'), ('Mary', 'Smith'),
                      ('Fred','Jones'), ('Frieda', 'Jones'),('Timothy', 'Jones')])) 
       
    print('\nTesting sort_ages:')
    print(sort_ages
          ([('Angie',(2,10,1954)),('Bob',(12,16,1949)),('Charlie',(9,4,1988)),
            ('Denise',(11,29,1990)),('Egon',(11, 22, 1924)),('Frances',(2,10,1954)),
            ('Gerald',(2,21,1920)),('Helen',(8,15,1924)),('Izzy',(12, 29, 1924)),
            ('Joyce',(2,21,1920))
示例#27
0
import random
from goody         import irange
from priorityqueue import PriorityQueue
from performance   import Performance


def setup(N):
    global pq
    pq = PriorityQueue([random.randrange(0, N) for i in range(0, N)])
        
def code(N):
    global pq
    for i in range(N):
        pq.remove()
 
for i in irange(0, 8):
    N = 10000*2**i
    P = Performance(lambda: code(10000), lambda: setup(N), 8, title = "\nPriority Queue of size " + str(N))
    P.evaluate()
    P.analyze()
 def _heapify(self):
     """
     Linear-time algorithm for converting a list into a heap
     """
     for i in irange(len(self._values) - 1, 0, -1):
         self._percolate_down(i)
示例#29
0
        if self.value_of() == self._modulus - 1:
            Counter.reset(self)
        else:
            Counter.inc(self)
        
    def modulus_of(self):
        return self._modulus



# Testing Script

if __name__ == '__main__':
    
    print('Testing count')
    values = [i for i in irange(1,100)] 
    print('Count of primes in list =', sum(1 for i in values if predicate.is_prime(i)))
    for i in range(5):
        shuffle(values)
        t = add_all(None,values)
        print('Count of primes in randomly built tree =',count(t,predicate.is_prime))
              
    print('\nTesting equal')           
    a = list_to_ll(['one','two','three','four'])
    b = list_to_ll(['one','two','three','four'])
    c = list_to_ll(['one','two','three'])
    d = list_to_ll(['one','two','three','four','five'])
    e = list_to_ll(['one','two','four','four'])
    
    print('These are equal:', equal(a,b))
    print('These are unequal:',equal(a,c), equal(a,d), equal(a,e))
示例#30
0
from performance import Performance
from goody import irange
from graph_goody import random, spanning_tree

# Put script here to generate data for Problem #1
g = None

def create_random(n):
    global g
    g = random(n, lambda n : 10*n) 
    
for i in irange(0,7) :
    n = 1000 * 2**i
    p = Performance(lambda : spanning_tree(g), lambda : create_random(n),5,'Spanning Tree of size {}'.format(n))
    p.evaluate()
    p.analyze()
    print()
示例#31
0
def compute_e(n):
    answer = Rational(1)
    for i in irange(1,n):
        answer += Rational(1,math.factorial(i))
    return answer
示例#32
0
def how_frequent(iterable, p):
    count = 0
    for total, i in enumerate(iterable):
        if p(i):
            count += 1
    return count / total


dice = [1, 2, 3, 4, 5, 6]

# Print all possible throws of 3 dice
print('All 3-dice throws:', list(product(dice, dice, dice)))
print()

# Print how frequently (.1 means 10%) each possible value of the sum of 3 dice appears
for d_sum in irange(3, 18):
    print(d_sum,
          how_frequent(product(dice, dice, dice), lambda x: sum(x) == d_sum))
print()

suits = ['Diamonds', 'Hearts', 'Clubs', 'Spades']
values = irange(1, 13)  # Jack = 11, Queen = 12, King = 13

# Print all possible cards (52) in a deck
print('All cards in a deck:', list(product(values, suits)))
print()

# In the calculations below, at no time do we have a data structure storing all
#   2,598,960 poker; we do generate each of these hands one after another to
#   do something with it (count it; count it if it is a straight flush).
示例#33
0
 def _heapify(self):
     """
     Linear-time algorithm for converting a list into a heap
     """
     for i in irange(len(self._values) - 1, 0, -1):
         self._percolate_down(i)
示例#34
0
    filtered  = filter((lambda x: x[0]<x[1] and x[1]>x[2]), reduced)    #filter out triples not representing peaks
    mapped   = map((lambda x: x[1]), filtered)    #map triple to its middle value
    return list(mapped)                     #map is a generator; store its values in list 
    




if __name__=="__main__":
    import predicate,random,driver
    from goody import irange
    
    print('Testing separate')
    print(separate(predicate.is_positive,[]))
    print(separate(predicate.is_positive,[1, -3, -2, 4, 0, -1, 8]))
    print(separate(predicate.is_prime,[i for i in irange(2,20)]))
    print(separate(lambda x : len(x) <= 3,'to be or not to be that is the question'.split(' ')))
     
    print('\nTesting is_sorted')
    print(is_sorted([]))
    print(is_sorted([1,2,3,4,5,6,7]))
    print(is_sorted([1,2,3,7,4,5,6]))
    print(is_sorted([1,2,3,4,5,6,5]))
    print(is_sorted([7,6,5,4,3,2,1]))
    
    print('\nTesting sort')
    print(sort([1,2,3,4,5,6,7]))
    print(sort([7,6,5,4,3,2,1]))
    print(sort([4,5,3,1,2,7,6]))
    print(sort([1,7,2,6,3,5,4]))
    l = [i+1 for i in range(30)]
示例#35
0
from stopwatch import Stopwatch
import prompt
import predicate

 
win_count     = 0                            #Win/Lose/Dice Statistics
lose_count    = 0

dice          = Dice([6,6])
game_timer    = Stopwatch()

games_to_play = prompt.for_int('Enter # of games to play', is_legal=predicate.is_positive, error_message='an int, but not > 0')

game_timer.start()
dice.standard_rolls_for_debugging()
for game in irange(1, games_to_play):        #Each iteration plays one game
    first_roll = dice.roll().pip_sum()       #Roll the dice and record their pip sum

    #Based on firstRoll, decide how to continue:
    #  immediate win/loss or trying to make point
    if first_roll == 7 or first_roll == 11:
        win_count += 1                       #Win on the first roll with 7 or 11

    elif first_roll == 2 or first_roll == 3 or first_roll == 12:
        lose_count += 1                      #Lose on the first roll with 2, 3, or 12

    else:                                    #Try to make the point as the game continues
        point = first_roll                   #point will never store 7, 11, 2, 3, or 12

        while(True):                         #Roll until roll point (win) or 7 (lose)
            roll = dice.roll().pip_sum()
示例#36
0
def compute_e(n):
    answer = Rational(1)
    for i in irange(1, n):
        answer += Rational(1, math.factorial(i))
    return answer
示例#37
0
            for (min_t,max_t) in hist:
                if min_t<= t < max_t:
                    hist[(min_t,max_t)] += 1

        print(title if title != None else self._title)
        print('Analysis of',len(times),'timings')
        print('avg = {avg:.3f}   min = {min:.3f}  max = {max:.3f}  span = {span:.1f}%'.
                format(min=mini,avg=avg,max=maxi,span=(maxi-mini)/avg*100))
        print('\n   Time Ranges    ')   
        print_histogram(hist)    

if __name__ == '__main__':
    from goody import irange
    import random
    from equivalence import EquivalenceClass
    
    def setup(size):
        global ec
        ec = EquivalenceClass([i for i in range(size)])
        
    def code(merges,size):
        global ec
        for i in range(merges):
            ec.merge_classes_containing(random.randint(0,size-1), random.randint(0,size-1))

    for i in irange(0,4):
        size = 10000 * 2**i
        p = Performance(lambda : code(200000,size), lambda:setup(size),5,'\n\nEquivalence Class of size ' + str(size))
        p.evaluate()
        p.analyze()
 
示例#38
0
 os, start = prompt.for_int(
     'Choose the order statistic ',
     default=2,
     is_legal=(lambda x: x >= 0),
     error_message='Not a Valid Order Statistic!'), []
 corpus = read_corpus(
     os,
     safe_open('Choose the file name to process ',
               'r',
               'Not a Valid Filename! Try Again!',
               default='wginput1.txt'))
 print('Corpus',
       corpus_as_str(corpus),
       f'Choose {os} words to start with',
       sep='\n')
 for i in irange(1, os):
     start.append(
         prompt.for_string(
             f'Choose word {i}',
             error_message=
             'Invalid Word: Please Enter a Valid word in the Text'))
 print(
     f"Random text = {produce_text(corpus, start, prompt.for_int('Choose # of words for generation ', default=10, is_legal= (lambda x: x >= 0), error_message= 'Not a Valid Number of Words!'))}"
 )
 # For running batch self-tests
 print()
 import driver
 driver.default_file_name = "bsc5.txt"
 driver.default_show_traceback = True
 driver.default_show_exception = True
 driver.default_show_exception_message = True
示例#39
0
from goody import irange
from generator import sequence, transform, count, chunk_sum, flatten

for i in sequence('abcd', 'ef', 'ghij'):
    print(i, end='')
print()


def upper(x):
    return x.upper()


for i in transform('abCdeFg', upper):
    print(i, end='')
print()


def is_upper(x):
    return x == x.upper()


for i in count('aBcDEfGhijK', is_upper):
    print(i, end=' ')
print()

for i in chunk_sum(irange(1, 20), 5):
    print(i, end=' ')

for i in flatten([1, 2, [3, 4, (5, 6, 7, {'abc': 1, 'xyz': 2}), 8, 9], 10]):
    print(i, end=' ')
示例#40
0
            
    
    
    
    pass
            
 
if __name__ == '__main__':
    from goody import irange
    from math import log
    # Feel free to test other cases as well
    
    
    print('Testing derivative')
    d = derivative (lambda x : 3*x**2 + 2*x - 2, .000001)
    print( [(a,d(a)) for a in irange(0,10)] )
    d = derivative (lambda x : log(x), .000001) # derivative of log(x) is 1/x
    print( [(a,d(a)) for a in irange(1,10)] )
     
    print('\nTesting keys_with')
    d = {'A':3,'B':2,'C':3,'D':2,'E':2,'F':4,'G':1,'H':4}
    kw = keys_with(d)
    print([(x,kw(x)) for x in sorted(set(d.values()))])
    d = {'A':1,'B':4,'C':2,'D':3,'E':1,'F':8,'G':3,'H':6,'I':4,'J':1}
    kw = keys_with(d)
    print([(x,kw(x)) for x in sorted(set(d.values()))])
         
    print('\nTesting flatten')
    db = {'ICS-31': {('Bob', 'A'), ('David', 'C'), ('Carol', 'B')},
          'Math-3A': {('Bob', 'B'), ('Alice', 'A')}} 
    print(flatten(db))
示例#41
0
            'avg = {avg:.5f}   min = {min:.5f}  max = {max:.5f}  span = {span:.1f}%'
            .format(min=mini,
                    avg=avg,
                    max=maxi,
                    span=(maxi - mini) / avg * 100))
        print('\n   Time Ranges    ')
        print_histogram(hist)


if __name__ == '__main__':
    from goody import irange
    import random
    from equivalence import EquivalenceClass

    def setup(size):
        global ec
        ec = EquivalenceClass([i for i in range(size)])

    def code(merges, size):
        global ec
        for i in range(merges):
            ec.merge_classes_containing(random.randint(0, size - 1),
                                        random.randint(0, size - 1))

    for i in irange(0, 4):
        size = 10000 * 2**i
        p = Performance(lambda: code(200000, size), lambda: setup(size), 5,
                        '\n\nEquivalence Class of size ' + str(size))
        p.evaluate()
        p.analyze()
示例#42
0
import predicate

win_count = 0  #Win/Lose/Dice Statistics
lose_count = 0

dice = Dice([6, 6])
game_timer = Stopwatch()

games_to_play = prompt.for_int('Enter # of games to play',
                               is_legal=predicate.is_positive,
                               error_message='an int, but not > 0')

game_timer.start()
dice.standard_rolls_for_debugging()
count = 0
for game in irange(1, games_to_play):
    #print('game',game)      #Each iteration plays one game
    first_roll = dice.roll().pip_sum()
    #print(first_roll)   #Roll the dice and record their pip sum
    #Based on firstRoll, decide how to continue:
    #  immediate win/loss or trying to make point
    if first_roll == 7 or first_roll == 11:
        win_count += 1
        count += 1
        #print(first_roll,game)                     #Win on the first roll with 7 or 11

    elif first_roll == 2 or first_roll == 3 or first_roll == 12:
        lose_count += 1  #Lose on the first roll with 2, 3, or 12
        #print(first_roll,'game',game)
    else:  #Try to make the point as the game continues
        point = first_roll  #point will never store 7, 11, 2, 3, or 12
示例#43
0
 import traceback
 
 driver.driver() # type quit in driver to return and execute code below
 
 # Test increases; add your own test cases
 print('Testing peaks')
 print(peaks([0,1,-1,3,8,4,3,5,4,3,8]))
 print(peaks([5,2,4,9,6,1,3,8,0,7]))
 print(peaks([1,2,3,4,5]))
 print(peaks([0,1]))
 
 #prints a 1 for every prime preceded/followed by a non prime
 #below 5, 7, 11, 13, 17, 19 have that property the result should be a list of 6 1s
 #[1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20]
 #[0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]
 print(list(int(is_prime(p)) for p in irange(1,20)))
 print(peaks(int(is_prime(p)) for p in irange(1,20)))
 
 
 # Test Permutation/Permuation2; add your own test cases
 print('\nTesting Permutation')
 for i in Permutation([4,0,3,1,2],0):
     print(i,end='')
 print()
 
 for i in Permutation([4,0,3,1,2],3):
     print(i,end='')
 print()
 
 for i in Permutation([0],0):
     print(i,end='')
示例#44
0
        filtered = filter(lambda x: (x[1] > x[0] and x[1] > x[2]), reduced)
        mapped = map(lambda x: x[1], filtered)

        return list(mapped)
    except:
        return []


if __name__ == "__main__":
    import predicate, random, driver
    from goody import irange

    print('Testing separate')
    print(separate(predicate.is_positive, []))
    print(separate(predicate.is_positive, [1, -3, -2, 4, 0, -1, 8]))
    print(separate(predicate.is_prime, [i for i in irange(2, 20)]))
    print(
        separate(lambda x: len(x) <= 3,
                 'to be or not to be that is the question'.split(' ')))

    print('\nTesting is_sorted')
    print(is_sorted([]))
    print(is_sorted([1, 2, 3, 4, 5, 6, 7]))
    print(is_sorted([1, 2, 3, 7, 4, 5, 6]))
    print(is_sorted([1, 2, 3, 4, 5, 6, 5]))
    print(is_sorted([7, 6, 5, 4, 3, 2, 1]))
    #
    #     print('\nTesting sort')
    #     print(sort([1,2,3,4,5,6,7]))
    #     print(sort([7,6,5,4,3,2,1]))
    #     print(sort([4,5,3,1,2,7,6]))
示例#45
0
from goody import irange
from generator import sequence, transform, count, chunk_sum, flatten


for i in sequence('abcd','ef','ghij'):
    print(i,end='')
print()


def upper(x):
    return x.upper()
    
for i in transform('abCdeFg',upper):
    print(i,end='')
print()
    
def is_upper(x):
    return x == x.upper()

for i in count('aBcDEfGhijK',is_upper):
    print(i,end=' ')
print()


for i in chunk_sum(irange(1,20),5):
    print(i,end=' ')

for i in flatten([1,2,[3,4,(5,6,7,{'abc':1,'xyz':2}),8,9],10]):
    print(i,end=' ')
示例#46
0

if __name__ == '__main__':
    from goody import irange
    from predicate import is_prime
    import driver

    # Feel free to test other cases as well

    print('Testing one_of: is_vowel')
    is_vowel = one_of(['a', 'e', 'i', 'o', 'u'])
    print([(c, is_vowel(c)) for c in "tobeornottobe"])

    print('\nTesting opposite_of: is_composite')
    is_composite = opposite_of(is_prime)
    print(sorted({i: is_composite(i) for i in irange(2, 10)}.items()))

    print('\nTesting opposite_of: is_consonant')
    is_consonant = opposite_of(is_vowel)
    print([(c, is_consonant(c)) for c in "tobeornottobe"])

    print('\nTesting sort_names: ')
    print(
        sort_names([('John', 'Smith'), ('Mary', 'Smith'), ('Fred', 'Jones'),
                    ('Frieda', 'Jones'), ('Timothy', 'Jones')]))

    print('\nTesting sort_ages:')
    print(
        sort_ages([('Angie', (2, 10, 1954)), ('Bob', (12, 16, 1949)),
                   ('Charlie', (9, 4, 1988)), ('Denise', (11, 29, 1990)),
                   ('Egon', (11, 22, 1924)), ('Frances', (2, 10, 1954)),
示例#47
0

if __name__ == '__main__':
    from goody import irange
    # Test peaks; add your own test cases
    print('Testing peaks')
    print(peaks([0, 1, -1, 3, 8, 4, 3, 5, 4, 3, 8]))
    print(peaks([5, 2, 4, 9, 6, 1, 3, 8, 0, 7]))
    print(peaks([1, 2, 3, 4, 5]))
    print(peaks([0, 1]))

    #prints a 1 for every prime preceded/followed by a non prime
    #below 5, 7, 11, 13, 17, 19 have that property the result should be a list of 6 1s
    #[1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20]
    #[0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0]
    print(list(int(is_prime(p)) for p in irange(1, 20)))
    print(peaks(int(is_prime(p)) for p in irange(1, 20)))

    # Test compress; add your own test cases
    print('\nTesting compress')
    for i in compress('abcdefghijklmnopqrstuvwxyz',
                      [is_prime(i) for i in irange(1, 26)]):
        print(i, end='')
    print()

    for i in compress('abcdefghijklmnopqrstuvwxyz',
                      (is_prime(i) for i in irange(1, 26))):
        print(i, end='')
    print('\n')

    # Test stop_when; add your own test cases
示例#48
0
    return reduce(lambda x,y: (x[0]+y[0],x[1]+y[1]), l)





if __name__=="__main__":
    import predicate,random,driver
    from goody import irange
    
    driver.driver() # type quit in driver to return and execute code below

    print('Testing separate')
    print(separate(predicate.is_positive,[]))
    print(separate(predicate.is_positive,[1, -3, -2, 4, 0, -1, 8]))
    print(separate(predicate.is_prime,[i for i in irange(2,20)]))
    print(separate(lambda x : len(x) <= 3,'to be or not to be that is the question'.split(' ')))
    
    print('\nTesting is_sorted')
    print(is_sorted([]))
    print(is_sorted([1,2,3,4,5,6,7]))
    print(is_sorted([1,2,3,7,4,5,6]))
    print(is_sorted([1,2,3,4,5,6,5]))
    print(is_sorted([7,6,5,4,3,2,1]))
    
    print('\nTesting sort')
    print(sort([1,2,3,4,5,6,7]))
    print(sort([7,6,5,4,3,2,1]))
    print(sort([4,5,3,1,2,7,6]))
    print(sort([1,7,2,6,3,5,4]))
    l = [i+1 for i in range(30)]
示例#49
0
        answer += Rational(1,math.factorial(i))
    return answer

# Newton: pi = 6*arcsin(1/2); see the arcsin series at http://mathforum.org/library/drmath/view/54137.html
# Check your results at http://www.numberworld.org/misc_runs/pi-5t/details.html
def compute_pi(n):
    def prod(r):
        answer = 1
        for i in r:
            answer *= i
        return answer
    
    answer = Rational(1,2)
    x      = Rational(1,2)
    for i in irange(1,n):
        big = 2*i+1
        answer += Rational(prod(range(1,big,2)),prod(range(2,big,2)))*x**big/big       
    return 6*answer


for i in irange(1,20):
    print(compute_e(i))
# Driver: prompts and executes commands (can call compute_e/computer_pi)
while True:
    try:
        exec(prompt.for_string('Command'))
    except Exception as report:
        import traceback
        traceback.print_exc()