Ejemplo n.º 1
0
 def get_random_bytes(lrange=None, skip=None):
     if lrange is None:
         v = bytearray(rr(2**rr(10)))
     else:
         v = bytearray(rr(*lrange))
     for i in range(len(v)):
         v[i] = rr(256)
         while v[i] == skip:
             v[i] = rr(256)
     return bytes(v)
Ejemplo n.º 2
0
def run(n):

    ans = [rr(0, 2) for _ in range(n)]
    x_0 = [rr(0, 2) for _ in range(n)]
    if x_0 == ans:
        return 1
    iterations = 1
    x_1 = [1 - x_i for x_i in x_0]
    while x_1 != ans:
        r = random()
        distance = min([i for i in range(1, n) if prob[i] >= r])
        x_1 = mutate(x_0, distance)
        iterations += 1
    return iterations
Ejemplo n.º 3
0
def bogo_sort(items):
    num_items = len(items)
    # Cheating :)
    correct = sorted(items)
    while correct != items:
        rand_swap_a = rr(0, num_items)
        rand_swap_b = rr(0, num_items)
        if items[rand_swap_a] > items[rand_swap_b]:
            copy_a = items[rand_swap_a]
            copy_b = items[rand_swap_b]
            items[rand_swap_a] = copy_b
            items[rand_swap_b] = copy_a
    print(items)
    return items
Ejemplo n.º 4
0
def madlib():
    d={
    'pn':['the girl','she','it'],
    'v':['walking','gliding','flying'],
    'pl':['dark alley','basement','subway tracks'],
    'adj':['fat','sweaty','ugly'],
    'noun':['boy','monster','thing']
    }
    return render_template(
        "madlib.html",
        pn  =d['pn']  [rr(0, len(d['pn'])   ) ],
        v   =d['v']   [rr(0, len(d['v'])    ) ],
        pl  =d['pl']  [rr(0, len(d['pl'])   ) ],
        adj =d['adj'] [rr(0, len(d['adj'])  ) ],
        noun=d['noun'][rr(0, len(d['noun']) ) ]
        )
Ejemplo n.º 5
0
def people(param_num):
	people = []
	# Create people
	for ii in range(PEOPLE):
		new_person = Person(PSHARE[param_num], PCREATE[param_num], DOI, param_num)
		new_person.reset() # Init
		people.append(new_person)

	# Create quotas
	quotas = []
	for ii, topic in enumerate(TOPICS):
		quotas.append(int(math.ceil(PEOPLE * I_CONF[ii])))

	# Distribute interests
	for ii, quota in enumerate(quotas):
		for nn in range(quota):
			# Interested or very interested
			d = DOI[0] if rr() < DOI_PREF else DOI[1]

			# Pick a suitable person. Pick any person after 3 tries.
			person = 0 # Init
			for jj in range(3): # HARDCODE 3
				person = ri(0, PEOPLE - 1)
				# Count previus topics of interest
				num = 0
				for interest in people[person].interests.values():
					if interest != 0:
						num += 1
				# Give new interest if few previous interests
				if num < 2: # HARDCODE 2
					people[person].interests[TOPICS[ii]] = d
					break
				# Smaller chance to get many interests
				elif rr() < 0.3: # HARDCODE 0.3
					people[person].interests[TOPICS[ii]] = d
					break
			# Anyone goes
			else:
				person = ri(0, PEOPLE -1)
				people[person].interests[TOPICS[ii]] = d

			# Split topic
			if (ii == 0):
				# Preferences go half and half
				people[person].preference = 1 if nn % 2 == 0 else 2

	return people
Ejemplo n.º 6
0
    def MakeGraph(self, RandomGraph = True,UserTable = True):
        if RandomGraph:
            self.Random_Matrix = [
                [0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0],
                [0,0,0,0,0,0,0]
                ]
            for _ in range(2):
		dir = [0,1]
		dir.shuffle()
                while True:
                    x = rr(1,5)
                    y = rr(1,5)
                    if self.Random_Matrix[x][y] == self.Random_Matrix[x+dir[0]][y+dir[1]] == 0:
                        break
                self.Random_Matrix[x][y] = rr(1,3)
                if self.Random_Matrix[x][y] == 1:
                    self.Random_Matrix[x+dir[0]][y+dir[1]] = 2
                else:
                    self.Random_Matrix[x+dir[0]][y+dir[1]] = 1

            for _ in range(2):
                while True:
                    x = rr(1,5)
                    y = rr(1,5)
                    if self.Random_Matrix[x][y] == self.Random_Matrix[x][y+1] == \
		    self.Random_Matrix[x+1][y] == self.Random_Matrix[x+1][y+1] == 0:
                        break
                self.Random_Matrix[x][y] = self.Random_Matrix[x+1][y+1] = 1
                self.Random_Matrix[x][y+1] = self.Random_Matrix[x+1][y] = 2


       
        self.User_Matrix=[
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0],
            [0,0,0,0,0,0,0]
            ]
Ejemplo n.º 7
0
def experiment(N):
	cnt = [0 for i in xrange(365)]
	for i in xrange(N):
		cnt[rr(365)] += 1
	for x in cnt:
		if x > 1:
			return 1
	return 0
Ejemplo n.º 8
0
def random_timesequence(start, end, steps=3):
    seq = []
    for n in range(start, end):
        # Randomize the number of sub-steps,
        # but maintain the bounds and monotonicity
        # (e.g. 0, 0, 1, 1, 1, 2, 3, 3, 3)
        for i in range(rr(0, steps)):
            seq.append(n)
    return seq
Ejemplo n.º 9
0
def make_person():
    return {
        'name': faker.name(),
        'email': faker.email(),
        'address': faker.address(),
        'url': faker.url(),
        'created': dt.now(),
        'age': rr(1, 99)
    }
Ejemplo n.º 10
0
def rationals(max_nums):
    """Doesn't cover entirety of the rationals, just an example subset"""
    for n in range(0, max_nums):
        try:
            rand_example = rr(0, max_nums ** n)  # Make things interesting
            yield float(n) / float(rand_example), n, Fraction(n, rand_example)
        except ZeroDivisionError:
            yield 0,
    raise StopIteration
Ejemplo n.º 11
0
 def compute(self, recipe=1):
     """Don't be confused: the notion of a recipe is just for fun here.
     It has nothing to do with lightmaps -- it's just to experiment
     with example 'ascii lighting' for more interesting visualizations.
     """
     self.lighting = []
     pixels = self.height * self.width
     if recipe == 1:
         for k in xrange(pixels):
             self.lighting.append(rr(0, 255))
     elif recipe == 2:
         for k in xrange(pixels):
             self.lighting.append(rr(0, (k + 1) * 5))
     elif recipe == 3:
         for k in xrange(pixels):
             if self.width < self.height:
                 self.lighting.append(rr(self.width, self.height))
             else:
                 self.lighting.append(rr(self.height, self.width))
Ejemplo n.º 12
0
def emit(routing_key='info'):
    count = 0
    # Randomize to mimic "authenticity"
    time.sleep(float(rr(1, 10)) * 0.1)
    start.channel.basic_publish(
        exchange=start.EXCHANGE_NAME,
        routing_key=routing_key,
        body='MOAL Message! #{}'.format(count),
        properties=pika.BasicProperties(delivery_mode=2))
    count += 1
Ejemplo n.º 13
0
def friends(people, param_num):
	for ii, person in enumerate(people):
		# Send friend requests
		for nn in range(int(gauss(F_MEAN[param_num], F_DEVIATION[param_num]))):
			# Pick a person
			id = ri(0, PEOPLE - 1)
			# Skip self
			if id == ii:
				continue
			other_person = people[id]

			# Logic of accepting a friend request
			# Amount of previous friends
			# HARDCODE All numbers
			if len(other_person.friends) < 8 or (len(other_person.friends) < 12 and rr() < 0.7) or rr() < 0.3:
				prob = 0.6 - F_PROB_BONUS[param_num]
				# Mutual interests
				for jj, topic in enumerate(TOPICS):
					# Split topic
					if jj == 0:
						# No preference
						if other_person.preference == 0 or person.preference == 0:
							pass
						# Same preference
						elif person.preference == other_person.preference:
							# Shared interest
							prob += F_PROB_BONUS[param_num]
							# Bonus
							prob += 0.1
						# Different preference
						else:
							# Penalty
							prob -= 0.1
					# Rest
					else:
						# Shared interest
						if other_person.interests[topic] > 0 and person.interests[topic] > 0:
							prob += F_PROB_BONUS[param_num]
				# Accept of decline friend request
				if rr() < prob:
					person.friends.append(id)
					other_person.friends.append(ii)
Ejemplo n.º 14
0
 def _divvy_ram(self, ram):
     """This is an arbitrary, somewhat meaningless method, to simulate
     the notion of free blocks of ram that must be allocated and
     referenced via pointer. A given program may require X ram, but
     the location of available ram may be disparate, so various blocks have
     to be stored as a free linked list, or similar data structure.
     Since we've already covered linked lists, association lists, etc...,
     there isn't much value outside learning the context of this data
     structure, which tends to be in memory management."""
     subdivisions = rr(2, 20)  # Arbitrary number
     flist = []
     while subdivisions > 0:
         diff = rr(0, ram)
         # Store ram as [current block of memory, location]
         flist.append([diff, str(self.last_block).zfill(4)])
         ram = ram - diff
         self.last_block += 1
         subdivisions -= 1
         if DEBUG:
             print_info('Ram: {} / diff: {}'.format(ram, diff))
     return flist
Ejemplo n.º 15
0
 def create(self):
     for topic in self.interests:
         # Check if interested
         if self.interests[topic] != 0:
             # To create or not to create
             if rr() < self.pCreate:
                 # Create
                 for ii in range(ri(0, 3)):  # HARDCODE (0, 3)
                     # Add preference if necessary
                     pref = 0
                     if topic == TOPICS[0]:
                         pref = self.preference
                     self.outbox.append(Post(topic, 1, pref))
Ejemplo n.º 16
0
def make_person(omit=[]):
    val = {
        'name': faker.name(),
        'address': faker.address(),
        'url': faker.url(),
        'is_married': choice([True, False]),
        'created': '{}'.format(dt.now()),
        'age': rr(1, 99)
    }
    for _val in omit:
        if _val in val:
            val.pop(_val)
    return val
Ejemplo n.º 17
0
 def share(self):
     for post in self.buffer:
         # Probability of sharing and skip posts of opposite preference
         if (
             rr() < self.pShare
             and (post.preference == 0 or post.preference == self.preference)
             and self.interests[post.topic] != 0
         ):
             # Create new post for sharing
             pref = 0
             # Add preference if necessary
             if post.topic == TOPICS[0]:
                 pref = self.preference
             self.outbox.append(Post(post.topic, 2, pref))
Ejemplo n.º 18
0
 def mkxword(self):
   l = [k for k in self.d]
   counter = 0
   if self.words is None:
     self.words = []
   across = 0
   while True:
     counter += 1
     w = Ch(l)
     m, n = rr(16), rr(16)
     if len(self.words) == 24:
       print('correct exit point, hardwired n of 24', len(self.words))
       return
     
     elif across:
       if self.addwordacross(w, m, n) is True:
         l.pop(l.index(w))
         self.words.append((w, m, n, across)) 
         #tuple format (0 word, 1 m, 2 n, 3 across<bool> )
         across ^= 1
         
     elif across == 0:    
       if self.addworddown(w, m, n) is True:
         l.pop(l.index(w))
         self.words.append((w, m, n, across))
         across ^= 1
        
     elif counter > 55:
       print('self.words', self.words)
       print('len(self.words)', len(self.words), 'type', type(self.words))
       print('counter', counter)
       ridx = rr(len(self.words))
       word, idxm, idxn, across = self.words.pop(ridx)
       self.rmword(word, idxm, idxn, across)
       print('counter reset. removed word', word)
       counter = 0
       continue
Ejemplo n.º 19
0
def plotpolar(data=[], num=None):
    """data and num used to build a graph using matplotlib,
       data[0]  is title
       data[1] is which_quarter
       data[2] is organization_name
       data[3] is the list of radii
    """

    fig = figure(figsize=(10,10))
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True)
    #ax = gca()
    #ax.set_autoscale_on(False)
    #xmin,xmax,ymin,ymax
    ax.set_ylim(0,10)



    deg = [360/len(organization_labels) * x for x in range(1,len(organization_labels)+1)]
    theta = [i*pi/180 for i in deg]  # convert to radians
    #FIXME when possible reflect user input, atm random # of graph bars
    # random..
    if not data:
        radii = [rr(0,11) for x in range(len(organization_labels)-1)]
        radii.append(num)
    else:
        title_ext = data[0] #leave blank for no title
        which_quarter = data[1]
        organization_name = data[2]
        radii = data[3]

    #TODO creates graph bars
    bars = ax.bar(theta,radii, width=0.35, bottom=0.0, align='center')
    for r,bar in zip(radii, bars):
        bar.set_facecolor( cm.jet(r/10.))
        bar.set_alpha(0.5)

    #degree organization_labels
    ax.set_thetagrids(deg,organization_labels, frac= 1, fontsize=14, verticalalignment = 'top',weight ="bold", color = "blue",clip_on =True)
    #title
    ax.set_title(title_ext + " " + which_quarter + " " + organization_name , fontsize=30, weight="bold")

    canvas=FigureCanvas(fig)
    #String.IO, i believe allows us to treat our object as if it were a file.
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)


    #how to return it to simple in views
    return png_output
Ejemplo n.º 20
0
		def filter(self, buffer, interests, preference):
			ret = []
			bonus = 0
			for post in buffer:
				var bonus = 0
				if post.preference != 0:
					if post.preference == preference:
						bonus = 0.1
					else:
						bonus = -0.2
				if interests[post.topic] + bonus < 0:
					bonus = 0
				if rr() < interests[post.topic] + bonus:
					ret.append(post)
			return ret
Ejemplo n.º 21
0
def random_weighted_graph(size):
    """Creates random graph

    :size: int: number of nodes in graph
    :returns: nx.Graph object

    """
    nodes = size
    edges = nodes* (nodes/3)
    MAX_WEIGHT = 100
    G = nx.dense_gnm_random_graph(n=nodes, m=edges)
    # give our graph some random weights
    for edge in G.edges(): G.add_edge(*edge, weight = rr(MAX_WEIGHT))
    assert nx.is_connected(G) == True # make sure its connected
    return G
Ejemplo n.º 22
0
def kth_largest(A, k):
    """returns the kth element of an array if it were sorted

    :A: list
    :k: int
    :returns: int

        >>> kth_largest([5, 0, 1, 2], 1)
        1
    """
    if A == []: return None
    else:
        l = rr(len(A))
        A[0], A[l] = A[l], A[0]
        less, x, greater = partition(A, 0, len(A))
        if len(less) == k: return x[0]
        elif len(less) < k: return kth_largest(greater, k-(len(less)+len(x)))
        else: return kth_largest(less, k)
Ejemplo n.º 23
0
def run_sorting_trials(
        sorting_func, magnitudes=[10, 100, 1000], test_output=True):
    """Runs a bunch of trials of various magnitudes with a given
    func, using randomly generated numbers.
    Returns a dict of results for later inspection.
    Tailored specifically for sorting functions, by
    generating randomly mixed sequences of numbers."""
    results = {
        'function': sorting_func.func_name if hasattr(
            sorting_func, 'func_name') else 'builtin'
    }
    for magnitude in magnitudes:
        start = time.time()
        items = [rr(0, 999) for _ in range(magnitude)]
        sorted_res = sorting_func(items)
        end = time.time()
        results[magnitude] = {'time': end - start}
        if test_output:
            results[magnitude]['correct'] = sorted(items) == sorted_res
    return results
Ejemplo n.º 24
0
def random_matrix(rows=4, columns=4, min=1, max=100, choices=None):
    """Generate a matrix filled with random numbers.

    Kwargs:
        rows (int) - The number of rows.
        columns (int) - The number of columns for each row.
        min (int) - The minimum number to use in randrange
        max (int) - The maximum number to use in randrange
        choices (list) - The choices to choose from, if specified.
            If none specified, randrange(min, max) will be used.

    >>> random_matrix(rows=3, columns=3, min=1, max=2)
    [[94, 23, 50], [57, 28, 52], [94, 5, 45]]
    """
    matrix = []
    for row in range(rows):
        _row = []
        for _ in range(columns):
            if choices is not None:
                _row.append(choice(choices))
            else:
                _row.append(rr(min, max))
        matrix.append(_row)
    return matrix
Ejemplo n.º 25
0
if __name__ == '__main__':
    from os import getcwd
    from os import sys
    sys.path.append(getcwd())

from MOAL.helpers.display import Section
from MOAL.helpers.display import prnt
from MOAL.helpers.display import print_h2
from MOAL.helpers.datamaker import make_sparselist
from MOAL.helpers.datamaker import make_sparsematrix
from MOAL.helpers.text import gibberish2
from pprint import pprint as ppr
from random import randrange as rr

DEBUG = True if __name__ == '__main__' else False


if DEBUG:
    with Section('Sparse linear data structures'):
        max = 100
        density = 0.1
        items = {rr(0, max): gibberish2() for _ in range(int(max * density))}
        splist = make_sparselist(items, max)
        prnt('Sparse list', splist)

        sparse_data = {(x, x): gibberish2() for x in range(0, 10)}
        sparsematrix = make_sparsematrix(sparse_data, max, rows=10, cols=10)
        print_h2('Sparse matrix')
        ppr(sparsematrix)
Ejemplo n.º 26
0
num_stars = 25

# star parameters: number of pointy edges and radius
min_num_points = 5
max_num_points = 11
min_star_radius = 2
max_star_radius = 10

# star parameter 'thinness' is on a scale of 1 to 10
min_thin = 5
max_thin = 9

# draw the night sky
figure(facecolor='k')
cur_axes = gca()

# patch stars
for i in range(num_stars):
    new_star = star(rr(min_star_radius, max_star_radius),
        rr(0, img_size) , rr(0, img_size), 'w', \
        rr(min_num_points, max_num_points), \
        rr(min_thin, max_thin)/10.0)
    cur_axes.add_patch(new_star)

# modify axis behaviour
axis([0, img_size, 0, img_size])
axis('scaled')
axis('off')

# save the figure without the extra margins
savefig('../images/nightsky', facecolor='k', edgecolor='k')
Ejemplo n.º 27
0
def rand_day():
    return rr(1, 31)
from random import randrange as rr
fornavn = input("Skriv inn ditt fornavn: ")
etternavn = input("Skriv inn ditt etternavn: ")
print("Hei, " + fornavn + " " + "A" * (rr(2) + 1) + "a" * rr(6) + " " +
      etternavn + "!")
Ejemplo n.º 29
0
def liste_lancers(n):
    for k in range(n):
        print(rr(5)+1)
Ejemplo n.º 30
0
def random_thresh():
    return rr(10) / 10
Ejemplo n.º 31
0
def randGen(aList):
    while aList:
	yield aList.pop(rr(len(aList)))
Ejemplo n.º 32
0
"""Sort with random results

This sort creates a tempprecip file that is not ordered chronologically.
"""

from random import randrange as rr

tmprecs = list(open('c:/pydata/tmpprecip2.dat', 'r'))
tmprecs.sort(key=lambda x: rr(1, 100001))
open('c:/pydata/unorderedtmps.dat', 'w').writelines(tmprecs)
Ejemplo n.º 33
0
def dice_roll():
    return rr(1, 7) + rr(1, 7)
Ejemplo n.º 34
0
def madlibs():
    return render_template(
        "madlibs.html", 
        name1 = bank["name"][rr(0,len(bank["name"]))],
        name2 = bank["name"][rr(0,len(bank["name"]))],
        name3 = bank["name"][rr(0,len(bank["name"]))],
        v1    = bank["v"]   [rr(0,len(bank["v"]))],
        noun1 = bank["n"]   [rr(0,len(bank["n"]))],
        adv1  = bank['adv'] [rr(0,len(bank['adv']))],
        pl1   = bank['pl']  [rr(0,len(bank['pl']))],
        pl2   = bank['pl']  [rr(0,len(bank['pl']))],
        adj1  = bank['adj'] [rr(0,len(bank['adj']))],
        adj2  = bank['adj'] [rr(0,len(bank['adj']))],
        adj3  = bank['adj'] [rr(0,len(bank['adj']))],
        adj4  = bank['adj'] [rr(0,len(bank['adj']))],
        n1    = bank['n']   [rr(0,len(bank['n']))]
        )
 def move(self):
     """Docstring."""
     self.move_x = rr(self.movement_range[0], self.movement_range[1])
     self.move_y = rr(self.movement_range[0], self.movement_range[1])
     self.x += self.move_x
     self.y += self.move_y
Ejemplo n.º 36
0
    def test__divmod__(self):
        """
        Testing __divmod__ method :
            (d,r) = a.__divmod__(b)
            - > d.value() == a.value() // b.value()
            - > r.value() == a.value() % b.value()
        """
        verbose = 0  # to print the detail for this function

        def test_floordiv(A, B):
            floordiv1 = A.valeur() // B.valeur()
            if verbose >= 1:
                print(
                    """On regarde : A = {a}\n             B = {b}\n               On s'attend à avoir {aval} // {bval} = {afbval}"""
                    .format(a=A.binaire,
                            b=B.binaire,
                            aval=A.valeur(),
                            bval=B.valeur(),
                            afbval=floordiv1))
            floordiv2 = (A // B).valeur()
            if verbose >= 1:
                print(
                    "               Et on a : A // B = {afbvaldeux}\n".format(
                        afbvaldeux=floordiv2))
            return floordiv1, floordiv2

        def test_mod(A, B):
            mod1 = A.valeur() % B.valeur()
            if verbose >= 1:
                print(
                    """On regarde : A = {a}\n             B = {b}\n               On s'attend à avoir {aval} % {bval} = {afbval}"""
                    .format(a=A.binaire,
                            b=B.binaire,
                            aval=A.valeur(),
                            bval=B.valeur(),
                            afbval=mod1))
            mod2 = (A % B).valeur()
            if verbose >= 1:
                print("               Et on a : A % B = {afbvaldeux}\n".format(
                    afbvaldeux=mod2))
            return mod1, mod2

        for i in range(15):
            # Creating 2 numbers A & B, positive, A > B
            n = 1
            A, B = SInt(1), SInt(1)
            a, b = rr(127) + 1, rr(127) + 1
            A.binaire = bin(max(a, b))[2:].zfill(8)
            B.binaire = bin(min(a, b))[2:].zfill(8)
            # First case : divmod(A,B) : + > +

            if verbose >= 1:
                print(
                    "================================================================================"
                )
                print("On teste +A // +B")
            self.assertEqual(*test_floordiv(A, B))
            if verbose >= 1:
                print("Test de +A // +B réussi !!\n\n")

                print("On teste +A % +B")
            self.assertEqual(*test_mod(A, B))
            if verbose >= 1:
                print("Test de A % B réussi !!")
                print(
                    "================================================================================"
                )

            # First case : divmod(B,A) : + < +
            if verbose >= 1:
                print(
                    "================================================================================"
                )
                print("On teste +B // +A")
            self.assertEqual(*test_floordiv(B, A))
            if verbose >= 1:
                print("Test de +B // +A réussi !!")

                print("On teste +B % +A")
            self.assertEqual(*test_mod(B, A))
            if verbose >= 1:
                print("Test de B % A réussi !!")
                print(
                    "================================================================================"
                )

                # First case : divmod(-A,B) : - > + # SOLUTION : -A // B == -(A // B + 1)
                print(
                    "================================================================================"
                )
                print("On teste -A // +B")
            self.assertEqual(*test_floordiv(-A, B))
            if verbose >= 1:
                print("Test de -A // +B réussi !!")

                print("On teste -A % +B")
            self.assertEqual(*test_mod(-A, B))
            if verbose >= 1:
                print("Test de -A % B réussi !!")
                print(
                    "================================================================================"
                )

                # First case : divmod(A,-B) : + > -
                print(
                    "================================================================================"
                )
                print("On teste +A // -B")
            self.assertEqual(*test_floordiv(
                A, -B))  # SOLUTION : A // -B == -(A // B + 1)
            if verbose >= 1:
                print("Test de +A // -B réussi !!")

                print("On teste +A % -B")
            self.assertEqual(*test_mod(A, -B))
            if verbose >= 1:
                print("Test de A % -B réussi !!")
                print(
                    "================================================================================"
                )

                # First case : divmod(-B, A) : - < +
                print(
                    "================================================================================"
                )
                print("On teste -B // A")
            self.assertEqual(*test_floordiv(
                -B, A))  # SOLUTION : -B // A == -1 TOUT LE TEMPS
            if verbose >= 1:
                print("Test de -B // +A réussi !!")

                print("On teste -B % +A")
            self.assertEqual(*test_mod(-B, A))
            if verbose >= 1:
                print("Test de -B % +A réussi !!")
                print(
                    "================================================================================"
                )

                # First case : divmod(B, -A) : + < -
                print(
                    "================================================================================"
                )
                print("On teste +B // -A")
            self.assertEqual(*test_floordiv(B, -A))
            if verbose >= 1:
                print("Test de +B // -A réussi !!")

                print("On teste +B % -A")
            self.assertEqual(*test_mod(B, -A))
            if verbose >= 1:
                print("Test de B % -A réussi !!")
                print(
                    "================================================================================"
                )

                # First case : divmod(-A,-B) : - > -
                print(
                    "================================================================================"
                )
                print("On teste -A // -B")
            self.assertEqual(*test_floordiv(-A, -B))
            if verbose >= 1:
                print("Test de -A // -B réussi !!")

                print("On teste -A % -B")
            self.assertEqual(*test_mod(-A, -B))
            if verbose >= 1:
                print("Test de -A % -B réussi !!")
                print(
                    "================================================================================"
                )

                # First case : divmod(-B,-A) : - < -
                print(
                    "================================================================================"
                )
                print("On teste -B // -A")
            self.assertEqual(*test_floordiv(-B, -A))
            if verbose >= 1:
                print("Test de -B // -A réussi !!")

                print("On teste -B % -A")
            self.assertEqual(*test_mod(-B, -A))
            if verbose >= 1:
                print("Test de -B % -A réussi !!")
                print(
                    "================================================================================"
                )
def club_data(f, i):
    return f.company(), f.city(), [f.phone_number() for j in range(rr(1, 4))
                                   ], [(rr(2, 7), rr(1, 10)) for j in range(9)]
 def move_unique(self):
     """Docstring."""
     self.x += rr(-2, 3)
     self.y += rr(-2, 3)
Ejemplo n.º 39
0
def random_node(vals, nums, max_edges):
    return {
        'edges': [choice(nums) for _ in range(rr(0, max_edges))],
        'val': choice(vals)
    }
Ejemplo n.º 40
0
    def new_game(self):
        self.newgame = True

        obrazky = ['earth.jpg', 'bees.jpg', 'tesla.jpg']
        jpg_subor = 'obr/' + str(obrazky[rr(3)])

        # NACITA OBR:
        self.obrazok_original = Image.open(jpg_subor)
        obrazok = self.obrazok_original.resize((400, 400))  #format Image

        #MINIATURA (obrazok vpravo):
        self.miniatura_img = self.obrazok_original.resize(
            (120, 120))  #miniatura = maly obrazok vpravo
        prazdny = Image.new('RGB', (30, 30), 'white')
        self.miniatura_img.paste(prazdny, (90, 90))
        self.miniatura_img = ImageTk.PhotoImage(self.miniatura_img)
        self.canvas.create_image(430,
                                 10,
                                 image=self.miniatura_img,
                                 anchor='nw')

        #SELF.POLE - self.obrazok rozdeleny po kuskoch:
        self.pole = []
        for i in range(0, 400, 100):
            riadok = []
            for j in range(0, 400, 100):
                stvorcek = obrazok.crop((j, i, j + 100, i + 100))
                stvorcek.load()  #kvoli lazy vyhodnocovaniu
                stvorcek = ImageTk.PhotoImage(stvorcek)
                riadok.append(stvorcek)
            self.pole.append(riadok)

        #SELF.STVORCE - pole objektov triedy Stvorec:
        self.stvorce = []

        #SELF.INDEXY - pole indexov pre self.pole:
        #self.indexy =[[(0,0),(0,1)...]]
        self.indexy = []
        for i in range(4):
            riadok = []
            for j in range(4):
                riadok.append([i, j])
            self.indexy.append(riadok)

        #INDEXY_riesenie (kopia self.indexy - kvoli overeniu vitazstva):
        self.indexy_riesenie = [x[:] for x in self.indexy]

        self.poc_tahov = 0
        self.pridaj_stvorce()

        #Zmaze pocitadlo:
        self.poc_tahov = 0
        try:
            self.canvas.delete(self.pocitadlo)
        except AttributeError:
            pass

        #Vytvori pocitadlo:
##        a = tkinter.Label(self.canvas, 'AHOJTEEEE') #### TEST
        self.pocitadlo = self.canvas.create_text(300,
                                                 430,
                                                 font='arial 12',
                                                 text='pocet tahov: ' +
                                                 str(self.poc_tahov))

        self.load_game()
Ejemplo n.º 41
0
        cartesian_tree.encode(seq=[4, 3, 1, 2])
        cartesian_tree.encode(seq=[1, 4, 3, 2])
        cartesian_tree.encode(seq=[2, 4, 3, 1])
        cartesian_tree.encode(seq=[4, 3, 1, 2])
        # Case 5
        cartesian_tree.encode(seq=[4, 3, 1, 2, 5])
        # Case N
        cartesian_tree.encode(seq=[4, 3, 1, 2, 5, 6])
        cartesian_tree.encode(seq=[8, 4, 3, 1, 2, 5, 6, 7])

        # Unique sequences
        cartesian_tree.encode(seq=wikipedia)
        cartesian_tree.encode(seq=mersenne_primes)

        # Obscene / random large sizes for testing edge cases and performance.
        cartesian_tree.encode(seq=mersenne_primes)
        cartesian_tree.encode(seq=[rr(0, 9999) for n in range(16)])

        # More assertions from tree, to confirm we haven't lost
        # any parent classes functionality or somehow regressed.
        cartesian_tree.encode(seq=[2, 1, 3, 4, 6])
        assert cartesian_tree.is_descendant(2, 1)
        assert cartesian_tree.is_ancestor(1, 2)
        assert not cartesian_tree.is_descendant(1, 6)
        assert cartesian_tree.get_siblings(3) == [2, 3]
        assert cartesian_tree.get_root()['edges'] == [2, 3]

        for node in [(1, 1), (2, 2), (3, 2), (4, 3), (5, 3), (6, 4)]:
            d, res = node[0], node[1]
            assert cartesian_tree.node_depth(d) == res
Ejemplo n.º 42
0
def nonpc():
    firstname = "Test"
    lastname = "Name"

    # GENDER
    gender = random.choice(open('gender.txt').readlines())
    gender = gender.rstrip()

    # RACE
    race = random.choice(open('races.txt').readlines())
    race = race.split(' ', 1)[0]
    race = race.rstrip()

    if race == "Elf" and gender == "Female":
        firstname = random.choice(
            open('names/elf_female_altmer_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/elf_family_altmer_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Elf" and gender == "Male":
        firstname = random.choice(
            open('names/elf_male_altmer_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/elf_family_altmer_names.txt').readlines())
        lastname = lastname.rstrip()
        if rr(1, 101) == 1:
            gender = "Eunuch"
    elif race == "Dwarf" and gender == "Female":
        firstname = random.choice(
            open('names/dwarf_female_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/dwarf_family_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Dwarf" and gender == "Male":
        firstname = random.choice(
            open('names/dwarf_male_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/dwarf_family_names.txt').readlines())
        lastname = lastname.rstrip()
        if rr(1, 101) == 1:
            gender = "Eunuch"
    elif race == "Human" and gender == "Female":
        firstname = random.choice(
            open('names/human_female_breton_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/human_family_breton_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Human" and gender == "Male":
        firstname = random.choice(
            open('names/human_male_breton_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/human_family_breton_names.txt').readlines())
        lastname = lastname.rstrip()
        if rr(1, 21) == 1:
            gender == "Eunuch"
    elif race == "Ork" and gender == "Female":
        firstname = random.choice(
            open('names/ork_female_orsimer_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/ork_family_orsimer_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Ork" and gender == "Male":
        firstname = random.choice(
            open('names/ork_male_orsimer_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/ork_family_orsimer_names.txt').readlines())
        lastname = lastname.rstrip()
        if rr(1, 11) == 1:
            gender = "Eunuch"
    elif race == "Rakshasa" and gender == "Female":
        firstname = random.choice(
            open('names/cat_female_khajiit_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/cat_family_khajiit_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Rakshasa" and gender == "Male":
        firstname = random.choice(
            open('names/cat_male_khajiit_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/cat_family_khajiit_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Drachen" and gender == "Female":
        firstname = random.choice(
            open('names/drachen_female_argonian_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/drachen_family_argonian_names.txt').readlines())
        lastname = lastname.rstrip()
    elif race == "Drachen" and gender == "Male":
        firstname = random.choice(
            open('names/drachen_male_argonian_names.txt').readlines())
        firstname = firstname.rstrip()
        lastname = random.choice(
            open('names/drachen_family_argonian_names.txt').readlines())
        lastname = lastname.rstrip()
        if rr(1, 11) > 1:
            gender = "Eunuch"

    profession = random.choice(open('class.txt').readlines())
    weight = rr(1, 5)
    if weight == 1:
        level = rr(1, 5)
    elif weight == 2:
        level = rr(1, 9)
    elif weight == 3:
        level = rr(1, 13)
    else:
        level = rr(1, 17)
    profession = profession.rstrip()

    # EQUIPMENT
    condition = random.choice(open('armor/armor_condition.txt').readlines())
    condition = condition.rstrip()
    armor = random.choice(open('armor/armor_types.txt').readlines())

    # PRINT
    #print '"firstname" : "%s", "lastname" : "%s"' % (firstname, lastname)
    print '{"firstname" : "%s", "lastname" : "%s", "gender" : "%s", "race" : "%s", "profession" : "%s", "level" : "%d"}' % (
        firstname, lastname, gender, race, profession, level)
    return nonpc
Ejemplo n.º 43
0
def random_weight():
    return rr(-10, 10) / 10
Ejemplo n.º 44
0
    def loop(self, screen):
        if self.index >= len(self.todraw):
            if not rr(6) or len(self.todraw) > 1000:
                self.todraw = []
                self.index = 0

            color = utils.randcolor()
            q = rr(1, 100)

            a = self.circle_points_generator(
                (rr(screen.get_width()), rr(screen.get_height())),
                screen.get_width() / rr(1, 5), q * rr(1, 10))
            b = self.circle_points_generator(
                (rr(screen.get_width()), rr(screen.get_height())),
                screen.get_width() / rr(1, 5), q * rr(1, 10), q * rr(100))

            for _ in range(rr(1, 10) * q):
                self.todraw.append((color, next(a), next(b)))

        for i in range(self.index):
            c, a, b = self.todraw[i]
            pygame.draw.aaline(screen, c, a, b)

        self.index += 1
Ejemplo n.º 45
0
if DEBUG:
    with Section('Data structure - routing table'):
        rt = RoutingTable()

        # Values are randomly seeded and will not describe a
        # network topology appropriately, but are used for
        # illustrating the general idea.
        for n in range(4):
            # Create a test ip + random ips for using in code below
            ip = faker.ipv4() if n > 0 else '192.168.0.0'
            rt.add({
                'destination': ip,
                'network_mask': subnet_mask(),
                'gateway': faker.ipv4(),
                'interface': faker.ipv4(),
                'metric': rr(1, 10),
                'protocol': u'Local'
            })

        print(rt)
        print_simple('Destinations', rt.get_all('destination'))
        print_simple('Network Mask', rt.get_all('network_mask'))
        print_simple('Gateway', rt.get_all('gateway'))
        print_simple('Metrics', rt.get_all('metric'))
        print_simple('Network ID', rt.get_networkid('192.168.0.0'))

        _bin = encoders.dec_to_bin

        print('{} {} {} {}'.format(_bin(192), _bin(168), _bin(100), _bin(41)))
Ejemplo n.º 46
0
def random():
    rand = rr(0, Post.query.count())
    post = Post.query.all()[rand]
    return redirect('post/{}'.format(post.folder))
Ejemplo n.º 47
0
 def _value(self, token):
     return '(R:{})'.format(rr(len(token), 999))
Ejemplo n.º 48
0
Archivo: net.py Proyecto: microsoft/CCF
def expand_localhost():
    return ".".join((str(b) for b in (127, rr(1, 255), rr(1, 255), rr(2, 255))))
Ejemplo n.º 49
0
def lancer():
    i = rr(6)+1
    return i
Ejemplo n.º 50
0
def custompage():
    """Fake endpoint."""
    kwargs = dict(number=rr(1, 1000))
    return render_template('examples/custom.html', **kwargs)
Ejemplo n.º 51
0
def snmp_interface(i):
    data = {
        "name": "interface",
        "timestamp": int(time.time()),
        "fields": {
            "ifAdminStatus": rr(2),
            "ifInDiscards": rr(10),
            "ifInErrors": rr(10),
            "ifHCInUcastPkts": rr(10),
            "ifInOctets": rr(10),
            "ifHCInOctets": rr(10),
            "ifInUcastPkts": rr(10),
            "ifInUnknownProtos": rr(10),
            "ifLastChange": rr(100000000, 1000000000),
            "ifMtu": rr(10),
            "ifOperStatus": rr(2),
            "ifOutDiscards": rr(10),
            "ifOutErrors": rr(10),
            "ifHCOutUcastPkts": rr(10),
            "ifOutOctets": rr(10),
            "ifHCOutOctets": rr(10),
            "ifOutQLen": rr(10),
            "ifOutUcastPkts": rr(10),
            "ifPhysAddress": "aa:aa:aa:aa:aa:aa",
            "ifSpecific": ".0.0",
            "ifSpeed": rr(1000000000, 10000000000),
            "ifType": 161
        },
        "tags": {
            "agent_host": "tsds.telegraf.output.test.net",
            "host": "test.host.net",
            "ifDescr": "AggregateEthernet0",
            "ifIndex": "0",
            "ifName": 'et-0/0/{}'.format(str(i))
        }
    }
    return data
Ejemplo n.º 52
0
def gauge():
    """Fake endpoint."""
    return json.dumps({'data': rr(1, 100)})
Ejemplo n.º 53
0
    def status(self):
        return 'ON' if self.on else 'OFF'


class LightMonitor(Monitor):

    def __init__(self, coords):
        self.coords = coords
        # For fun
        self.on = choice([True, False])


class LightGrid:

    def __init__(self):
        self.lights = {}

    def __setitem__(self, id, coords):
        self.lights[id] = LightMonitor(coords)


if DEBUG:
    with Section('GRASP pure fabrication pattern'):
        grid = LightGrid()
        gridmon = GridMonitorService(grid)

        for _ in xrange(10):
            grid[uuid1()] = (rr(0, 1000), rr(0, 1000), rr(0, 1000))

        gridmon.check_status()
Ejemplo n.º 54
0
def pie():
    """Fake endpoint."""
    letters = list('abcde')
    if 'stress' in request.args:
        letters = range(STRESS_MAX_POINTS)
    return json.dumps({'data {}'.format(name): rr(1, 100) for name in letters})
Ejemplo n.º 55
0
def merge_sort(items, iteration=0, side=None):
    # `iteration` and `side` are used for testing purposes,
    # visualizing the recursive nature of the divide and conquer algorithm.
    _len = len(items)
    if _len < 2:
        return items
    pivot = _len // 2
    # Keep subdividing based on pivot,
    # until an empty list is all that is left.
    left = items[:pivot]
    right = items[pivot:]
    # Print each side, keeping track of recursive count to visually
    # indicate how many recursive calls were made.
    # print (side if side else '[ROOT]'), (iteration * 2) * '.', left, right
    return merge(
        merge_sort(left, iteration=iteration + 1, side='left'),
        merge_sort(right, iteration=iteration + 1, side='right'))


if __name__ == '__main__':
    with Section('Merge Sort'):
        results = run_sorting_trials(merge_sort)
        ppr(results)

    with Section('Merge Sort - integers'):
        ppr(merge_sort([rr(1, 9999) for _ in range(20)]))

    with Section('Merge Sort - floating point integers'):
        ppr(merge_sort([random() * float(rr(1, 9999)) for _ in range(20)]))
Ejemplo n.º 56
0
def rr_list(max_range=10):
    """Generate a list of random integers."""
    return [rr(0, 100) for i in range(max_range)]
Ejemplo n.º 57
0

if __name__ == '__main__':
    with Section('Number theory'):
        test_number(odd, 10)
        test_number(even, 10)
        test_number(exp, 10)
        [test_number(exp_custom, 10, n) for n in range(10)]
        test_number(lg, 10)
        [test_number(lg_custom, 10, n) for n in range(10)]
        test_number(square, 10)
        test_number(fibo, 10)
        test_number(cube, 10)
        test_number(rand, 10)
        test_number(triangle, 10)
        [test_number(gcd, rr(999, 9999), rr(999, 9999)) for _ in range(4)]

        funcs = [
            lambda x: x**2, lambda x: x * 2, lambda x: x // 2,
            lambda x: x * x - x // x + x
        ]

        [
            prnt('Series of series with: {}'.format(getsource(f)),
                 [map(f, (n for n in range(1, _))) for _ in fibo(8)])
            for f in funcs
        ]

        [
            prnt('Factor {}'.format(n), [f for f in factor(rr(100, 9999))][0])
            for n in range(4)
Ejemplo n.º 58
0
class Game(object):
    """
    Object of Game() is just a running game.
    Player are inputing thier names, answer the question about contiuning logs.
    Next there is coinflip to choice which player is moving next.
    """
    len_of_message_after_game = 40  # This var saying about minimum lenght of "winner" text and its lanes
    coinflip = rr(
        0, 2)  # As name say... make an coin flip, to make choice of 1st move
    # (i, j) Dict of allowed moves, that left in this game
    allowed_moves = {
        'a1': (2, 2),
        'b1': (2, 6),
        'c1': (2, 10),
        'a2': (6, 2),
        'b2': (6, 6),
        'c2': (6, 10),
        'a3': (10, 2),
        'b3': (10, 6),
        'c3': (10, 10)
    }

    def __init__(self):
        self.board_rows_2D_list = Board.board_from_file(
            Board())  # Taking an empty board from Board class
        """p_circe/ p_cross - listing moves of Player subclasses
        player_win_logs - listing logs of winners in rounds
        """
        self.p_circle_moves, self.p_cross_moves, self.player_win_logs = [], [], []
        # actual_player - after coin flip, I have to pass information, which player is moving... 0- Circle, 1 - Cross
        self.actual_player = -1
        """winning_type/ winning_pos - Helps to pass informations about lane to create - is it diagonal from left top,
                                    or left bottom or at 1/2/3 or a/b/c
        winning_type 1- \\ 2- / 3- - 4- |         winning_pos taking just 2/6/10 - which are ids` in-Board 
        """
        self.winning_type, self.winning_pos = [], []
        self.are_logs_loaded = ""  # Taking var from input (yes/no) - ask about contiunue/ start from scratch logs
        # Taking names from players
        self.name_of_player_one = " "  # empty placeholder
        self.player_circle = PlayerCircle(self.name_of_player_one)
        self.name_of_player_two = " "
        self.player_cross = PlayerCross(self.name_of_player_two)

        self.game_loop(True)  # Starting game and (take names plz)

    def game_loop(self, is_game_taking_names_logs_info):
        """
        Making a game loop that call other functions and count moves (Only one time in sesion You can give names)
        If players want rematch set every variable/ attribute to starting values.
        :param is_game_taking_names_logs_info: If game have 1st initialization I need to get names.
        In every next games in same session they use same names, so don't need for asking about names.
        :return: None
        """
        while is_game_taking_names_logs_info:  # if game have fresh start it need names and info what to to with logs
            print("Hello in my TicTacToe game")
            self.taking_logs_input()
            self.taking_names_input()
            is_game_taking_names_logs_info = False  # and in every game loop this shouldn't be asked
        are_we_still_playing = True  # if not exited, drawed or won
        does_player_said_exit = False  # does player said "exit" or not
        while are_we_still_playing:  # if there is no win/draw
            are_we_still_playing = not (
                self.is_victory())  # if there is no win, we're still playing
            if not are_we_still_playing:  # if we don't play, exit loop
                break
            count_moves = (
                (-1) * len(self.allowed_moves)
            ) + 9  # getting number of moves i.e: when there are 3 moves -3+9=6
            if count_moves == 9:  # if there was 9 moves and was no winner -  round is draw and end loop of playing
                self.player_win_logs.append('d')  # "remembering" this is draw
                self.drawing_message()
                break
            else:
                Board.print_board(self.board_rows_2D_list)
                if self.taking_a_player_move(
                ):  # making move, and when player said "exit" there is no more playing
                    does_player_said_exit = True
                    break
        if does_player_said_exit:  # if there was "exit"... game should be stopped
            print("\nGame has no winners or tie."
                  )  # print in new row and end game
            if self.are_logs_loaded == 'yes':  # from player answer about logs
                Logs.logs_with_load(
                    Logs(self.name_of_player_one, self.name_of_player_two,
                         self.player_win_logs))
            else:  # if they end any round I paste logs to .txt, coz I will overwrite it everytime
                Logs.logs_without_load(
                    Logs(self.name_of_player_one, self.name_of_player_two,
                         self.player_win_logs))
            return
        if self.player_win_logs[
                -1] != 'd':  # if in while we got "there is win", now I show text about it
            self.winning_message()
        are_you_want_rematch = input(
            "Are you want to play agine? (yes/whatever) ").lower(
            )  # asking about rematch
        if self.are_logs_loaded == 'yes':  # from player answer about logs
            if are_you_want_rematch != 'yes':  # if they stop playing, I'm pasting logs to .txt
                Logs.logs_with_load(
                    Logs(self.name_of_player_one, self.name_of_player_two,
                         self.player_win_logs))
        else:  # if they end any round I paste logs to .txt, coz I will overwrite it everytime
            Logs.logs_without_load(
                Logs(self.name_of_player_one, self.name_of_player_two,
                     self.player_win_logs))

        if are_you_want_rematch == 'yes':  # When there is rematch, I want to reset every value to starting values
            self.board_rows_2D_list = Board.board_making(Board())
            self.allowed_moves = {
                'a1': (2, 2),
                'b1': (2, 6),
                'c1': (2, 10),
                'a2': (6, 2),
                'b2': (6, 6),
                'c2': (6, 10),
                'a3': (10, 2),
                'b3': (10, 6),
                'c3': (10, 10)
            }
            self.p_circle_moves, self.p_cross_moves = [], []
            self.winning_type, self.winning_pos = [], []
            # self.coinflip = rr(0, 2)  # if starter player should be more randomized, than only at begining
            self.len_of_message_after_game = 40
            self.game_loop(
                False
            )  # Starting game agine, but now don't ask about names agine

    def taking_logs_input(self):
        """
        This function ask main host about loading logs (if they are exists) or start them from scratch.
        :return: None
        """
        while True:  # ask about logs as many times, as answer will be "yes" or "no"
            self.are_logs_loaded = input(
                "Do I have to load logs? (yes/no) ").lower()
            if self.are_logs_loaded == 'no' or self.are_logs_loaded == 'yes':  # if answer is good, break loop
                break

    def taking_names_input(self):
        """
        Taking names from both players and checking if they are have only letters in name.
        :return: None
        """
        self.name_of_player_one = ''
        while not self.name_of_player_one.isalpha(
        ):  # ask as many times, as answer will have only letters
            self.name_of_player_one = input("Give name of '" +
                                            self.player_circle.char +
                                            "' player: ").capitalize()
        self.player_circle = PlayerCircle(self.name_of_player_one)
        self.name_of_player_two = ''
        while not self.name_of_player_two.isalpha(
        ):  # ask as many times, as answer will have only letters
            self.name_of_player_two = input("Give name of '" +
                                            self.player_cross.char +
                                            "' player: ").capitalize()
        self.player_cross = PlayerCross(self.name_of_player_two)

    def is_victory(self):
        """
        Checking is anyone winner or not.
        :return: boolean values - True if someone winned game, False if noone is winner.
        """
        # Chacking only one of players with lastest move. If scored "win" adding it to logs and return "Game has won"
        if self.actual_player == 0:
            if self.win_rule(self.p_circle_moves
                             ):  # checking if it's won in single/multiple ways
                self.player_win_logs.append(
                    self.player_circle.char)  # adding win information to logs
                return True
        elif self.actual_player == 1:
            if self.win_rule(self.p_cross_moves):
                self.player_win_logs.append(self.player_cross.char)
                return True
        return False  # False when game has no winner yet

    def win_rule(self, move_list):
        """
        Checking win rules   1- \\ 2- / 3- - 4- |
        Diadonals are checked first, coz 'now there are two of them!'
        Then are checked rows, and at last columns one by one.
        All checking is done by checking out move_list (down below) for only 1 player at same time from thier
        own move list.
        :param move_list: list of moves from last moving player, only 1 at the time.
        :return: True only if someone is winner
        """
        self.diagonals(move_list)  # checking diagonals first
        move_list = sorted(
            move_list
        )  # not necessary, it's only for one of player - for current one
        dic = {
        }  # i will put there pair of lane(row/col):how_many_of_them i.e.: "c":1, "c":1
        short_str = ""  # taking 'char' from dic, when its value == 3
        short_str_list = [
        ]  # taking 'char' from dic, when its value == 3 and putting it in list, to get all of them(2)
        for each in move_list:
            for cha in each:  # checking every char in every move
                counter = 1  # counting iterations
                if cha in dic:  # reverse checking
                    dic[cha] = dic.get(
                        cha
                    ) + 1  # if char is in dic, incremente information of times they showed in
                    if dic[cha] > 2:  # if there is 3 of same chars, that mean we have winner and it's way of win
                        short_str = cha  # taking char form dic
                        short_str_list.append(
                            short_str
                        )  # putting this char into list to use it later
                else:
                    dic[cha] = counter  # if there is no char in dic, just add it with :value = 1

        if len(short_str_list) == 1:  # if there is only 1 win
            if short_str in ('1', '2', '3'):  # checking row number
                self.winning_pos.append(
                    int(short_str) * 4 -
                    2)  # getting good lane in middle of row
                self.winning_type.append(3)  # type 3 = row
            if short_str in ('a', 'b', 'c'):  # checking col letter
                self.winning_type.append(4)  # type 4 = column
                self.winning_pos.append(2 if (short_str == 'a') else 6 if (
                    short_str == 'b') else 10)
            # ^ translate letter to good middle column of board, to make there a lane
        elif len(short_str_list) == 2:  # if there is 2 connected lanes
            if short_str_list[1] in ['1', '2',
                                     '3']:  # there was tuple, here is list.
                self.winning_pos.append(int(short_str_list[1]) * 4 -
                                        2)  # same calculations as above
                self.winning_type.append(3)
                # ↓ with iformation about move - making right position on board to print lane↑
            if short_str_list[0] in ['a', 'b', 'c']:
                self.winning_type.append(4)
                self.winning_pos.append(2 if (
                    short_str_list[0] == 'a') else 6 if (
                        short_str_list[0] == 'b') else 10)
        if self.winning_type:  # if there is any win lane - that's mean there is winner
            return True

    def diagonals(self, move_list):
        """
        Checking if player won by making diagonal lane
        :param move_list: list of moves from last moving player, only 1 at the time.
        :return: False if there is no diagonal winner, not important.
        """
        move_set = set(
            move_list)  # changing moves to set... just to use set operations
        tuple_a1_c3 = ('a1', 'b2', 'c3')  # \ diagonal
        tuple_a3_c1 = ('a3', 'b2', 'c1')  # / diagonal
        if set(tuple_a1_c3).issubset(move_set):  # if winner is by \
            self.winning_type.append(1)
        if set(tuple_a3_c1).issubset(move_set):  # if winner is by /
            self.winning_type.append(2)
        return False  # if there is no winner

    def name_of_next_player(
            self, is_not_finished
    ):  # game is not finished  = change player, else dont.
        """
        This function is used to pick who make move if they are still playing or it don't change them
        if any of them is winner
        :param is_not_finished: boolean - True: change player to 2nd; False: giving name of player
        :return: ^ True: character of next player; False: name of the winner.
        """
        if is_not_finished:  # if players are playing
            self.coinflip += 1  # changing player to another to make him move
            # 0 = Circle, 1 = Cross
            if self.coinflip % 2 == 0:  # returning right name of Player
                self.actual_player = 0
                return self.player_circle.char
            else:
                self.actual_player = 1
                return self.player_cross.char

        if not is_not_finished:  # same stuff but without increasing coinflip so the players stay same = not change move
            if self.coinflip % 2 == 0:
                self.actual_player = 0
                return self.player_circle.name
            else:
                self.actual_player = 1
                return self.player_cross.name

    def taking_a_player_move(self):
        """
        Asking player about his move from input()
        :return: True - when player said "exit" -> quit current game
        """
        player_move = ""  # creating var
        choice = self.name_of_next_player(
            True)  # Allow to get charakter of next player
        is_valid = True  # just to call and end While loop
        while is_valid:
            player_move = input(
                "Please " + choice +
                " give a coords (z0 / exit): ").lower()  # taking str
            if player_move == 'exit':  # exiting from game
                return True
            if player_move in self.allowed_moves.keys(
            ):  # checking if player can make this move
                is_valid = False  # if player make valid move, he cannot be ask agine for move
                if self.actual_player == 0:  # if Player is Circle
                    self.p_circle_moves.append(
                        player_move)  # adding move to its moves list
                    coords = self.allowed_moves[
                        player_move]  # taking coords from dict, by "key"
                    self.board_rows_2D_list[coords[0]][coords[
                        1]] = self.player_circle.char  # changing value on board
                else:  # if Player is Cross
                    self.p_cross_moves.append(
                        player_move)  # adding move to its moves list
                    coords = self.allowed_moves[
                        player_move]  # taking coords from dict, by "key"
                    self.board_rows_2D_list[coords[0]][coords[
                        1]] = self.player_cross.char  # changing value on board
            else:
                print("You are not allowed to make this move!"
                      )  # if move was done / is beyond board
        else:
            self.allowed_moves.pop(
                player_move
            )  # removing move from allowed, coz it's already done

    @staticmethod
    def adding_message_border(len_text=40):
        """
        Adding dashed border above end game messages.
        :param len_text: How log this border should be
        :return: None
        """
        empty_str = ""  # empty string which i will fill with - to make lane, 2nd "oneliner" way is down below
        print(empty_str.rjust(len_text, '-'))  # printing lane above Tie
        # empty_str = "".rjust(self.len_empty, '-')  # nicer way to implement same thing, than above

    def drawing_message(self):
        """
        This function is printing centered TIE text.
        :return: None
        """
        tie_str_text = 'Tie'
        len_of_text = len(tie_str_text)
        len_text = (
            (self.len_of_message_after_game - len_of_text) // 2 + len_of_text
        )  # centering Tie text

        self.adding_message_border(self.len_of_message_after_game)
        print(tie_str_text.rjust(len_text, ' '))  # printing "drawing" text
        self.adding_message_border(self.len_of_message_after_game)

        Board.print_board(
            self.board_rows_2D_list)  # printing Board to show last move

    def winning_message(self):
        """
        This function is printing centred WINNER text
        :return: None
        """
        winning_str_formating = f"And the winner is: {self.name_of_next_player(False)}"
        # ^taking name without changing player^
        len_of_text = len(
            winning_str_formating)  # variable taking lenght of "winner" text
        if len_of_text > self.len_of_message_after_game:  # if "winner" text is longer than base 40
            self.len_of_message_after_game = len_of_text
        len_text = (
            (self.len_of_message_after_game - len_of_text) // 2 + len_of_text
        )  # variable that calculate center

        self.adding_message_border(self.len_of_message_after_game)
        print(winning_str_formating.rjust(
            len_text, " "))  # printing out "winning" text in middle of lanes
        self.adding_message_border(self.len_of_message_after_game)

        Board.showing_vitory_lane_on_board(self.board_rows_2D_list,
                                           self.winning_type,
                                           self.winning_pos)  # drawing lane
        Board.print_board(
            self.board_rows_2D_list
        )  # Calling Board to print itself changed in game to show it last time
Ejemplo n.º 59
0
 def _value(self, token):
     return '(R:{})'.format(rr(len(token), 999))
Ejemplo n.º 60
0
def rand(max_nums):
    for n in range(1, max_nums):
        yield rr(1, max_nums)
    raise StopIteration