blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d073bae6b3f47a06f07414c59ab770d41c1f6791
Ftoma123/100daysprograming
/day10.py
146
4.03125
4
x = 2 y = 3 # Python Arithmetic Operators print(x + y) #Python Assignment Operator x += 5 print(x) #Python Comparison Operators print(x > y)
1674840b195a21b3963bbd9595b5ae783cac55fd
Ftoma123/100daysprograming
/day9.py
347
4.03125
4
age = 36 text = "my age is {}" print(text.format(age)) apple = 3 banana = 5 streberry = 10 text1 = "I bought {} apples, {} bananas and {} straeberry." print(text1.format(apple, banana, streberry)) apple = 10 banana = 55 streberry = 30 text2 = "I bought {2} straeberry, {1} bananas and {0} apples." print(text2.format(apple, banana, streberry))
7dd6607c78cd394594364da8f9749cc2f88c8321
Ftoma123/100daysprograming
/day41.py
541
3.984375
4
#create object class MyClass: x = 5 p1 = MyClass() #تعريف لل opject print(p1.x) print('_______________') #___________ class person: def __init__(self, name, age): self.name = name self.age = age p1 = person('Jhon', 13) print(p1.name) print(p1.age) print('_______________') #___________ class person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfun(abc): print('my name is ', abc.name) p1 = person('Jhon', 12) p1.myfun()
6373d12759eabd9b3ffadbc995b49d28b9f6fae7
Ftoma123/100daysprograming
/day30.py
550
4.375
4
#using range() in Loop for x in range(6): print(x) print('____________________') #using range() with parameter for x in range(2,6): print(x) print('____________________') #using range() with specific increment for x in range(2,20,3): #(start, ende, increment) print(x) print('____________________') #else for x in range(0,6): print(x) else: print('finished') print('____________________') #nested loop adj = ['red', 'big', 'tasty'] fruits = ['Apple', 'Banana', 'Cherry'] for x in adj: for y in fruits: print(x, y)
5e4cacab4da0901737fdd51b59ed54802ac00d06
Ftoma123/100daysprograming
/day43.py
554
4.03125
4
#inheretance #parent class class person: def __init__(self, fname, lname): self.firstname = fname self.lastname = lname def printname(self): print(self.firstname, self.lastname) x = person('Jhon', 'Doe') x.printname() # Create a Child Class class student(person): pass s = student('Noura','Almulhim') s.printname() class student1(person): def __init__(self, fname, lname): person.__init__(self, fname, lname) #for not overridde init() from parent s1 =student1('Nasser', 'Almulhim') s1.printname()
ee980ea2f6d822a3118eb7845b0f3a63a0a241ad
QiaojuLiu/leetcj
/heap.py
1,944
3.765625
4
class PriorityQueueBase: class Item: __slots__ = '_key','_value' def __init__(self,k,v): self._key = k self._value = v def __lt__(self,other): return self._key < other._key #如果self_.key比other._key小,则返回True,否则,返回False。 def is_empty(self): return len(self) == 0 def __str__(self): return str(self._key) class HeapPriorityQueue(PriorityQueueBase): def __init__(self): self._data = [] def __len__(self): return len(self._data) def is_empty(self): return len(self) == 0 def add(self,key,value): self._data.append(self.Item(key,value)) self._upheap(len(self._data)-1) def min(self): if self.is_empty(): raise ValueError('Priority queue is empty') item = self._data[0] return (item._key,item._value) def remove_min(self): if self.is_empty(): raise ValueError('Priority queue is empty') self._swap(0,len(self._data)-1) item = self._data.pop() self._downheap(0) return (item._key,item._value) def _upheap(self,j): parent = (j-1)//2 if j > 0 and self._data[j] < self._data[parent]: self._data[j],self._data[parent] = self._data[parent],self._data[j] self._upheap(parent) def _downheap(self,j): if 2*j+1< len(self._data): left = 2*j+1 samll_child = left if 2*j+2 < len(self._data): #len(j+1)< len(self._data) right = 2*j + 2 if self._data[right] < self._data[left]: small_child = right if self._data[small_child] < self._data[j]: self._data[j],self._data[small_child]=self._data[samll_child],self._data[j] self._downheap(samll_child)
1083052e37b5556980972557425aeac95fa7931b
arensdj/math-series
/series_module.py
2,753
4.46875
4
# This function produces the fibonacci Series which is a numeric series starting # with the integers 0 and 1. In this series, the next integer is determined by # summing the previous two. # The resulting series looks like 0, 1, 1, 2, 3, 5, 8, 13, ... def fibonacci(n): """ Summary of fibonacci function: computes the fibonacci series which is a numeric series starting with integers 0 and 1. The next integer in series is determined by summing the previous two and looks like 0, 1, 1, 2, 3, 5, 8, 13, ... Parameters: n (int): positive integer n Returns: int: Returns the nth value of the fibonacci numbers """ array = [] index = 1 array.append(index) array.append(index) total = 0 for i in range(index, n): total = array[i - 1] + array[i] array.append(total) return array[i] # This function produces the Lucas Numbers. This is a related series of integers # that start with the values 2 and 1. # This resulting series looks like 2, 1, 3, 4, 7, 11, 18, 29, ... def lucas(n): """ Summary of lucas function: computes the lucas series which is a related series of integers that start with the values 2 and 1 and looks like 2, 1, 3, 4, 7, 11, 18, 29, ... Parameters: n (int): positive integer n Returns: int: Returns the nth value of the lucas numbers """ array = [] index = 1 array.append(index+1) array.append(index) total = 0 for i in range(index, n): total = array[i -1] + array[i] array.append(total) return array[i] # This function produces numbers from the fibonacci series if there are no # optional parameters. Invoking this function with the optional arguments 2 and 1 # will produce values from the lucas numbers. def sum_series(n, arg1=0, arg2=1): """ Summary of sum_series function: computes a series of numbers based on the arguments. One required argument will produce fibonacci numbers. One argument and optional arguments 2 and 1 produces the lucas series. Parameters: n (int): positive integer n arg1 (int): (optional) positive integer arg1 arg2 (int): (optional) positive integer arg2 Returns: int: Returns the nth value of either the fibonacci numbers or the lucas numbers """ array = [] total = 0 index = 1 # if optional arguments are not included in function call, produce # fibonacci numbers if ( (arg1 == 0) and (arg2 == 1) ): array.append(index) array.append(index) else: # optional numbers were included in function call. Produce lucas numbers array.append(index+1) array.append(index) for i in range(index, n): total = array[i - 1] + array[i] array.append(total) return array[i]
d11dcc3373cbb78044e5ce875b2bfd546156176c
kageus/Advent-of-Code-2020
/3.1.py
476
3.9375
4
# find any given value of a repeating string at X coordinate def lineValueAtTarget(line, target): if target > len(line): target = target % len(line) return line[target] dataInput = open("./input/input_3.txt").read().split("\n") treeCount = 0 currentLocation = 0 for line in dataInput: valueAtLocation = lineValueAtTarget(line, currentLocation) if valueAtLocation == "#": treeCount += 1 currentLocation += 3 print(treeCount)
0ec6562b7b18d03407237ac1054a71a8f3787e7d
froens/EnzymAnalyzer
/utils/FileUtils.py
2,342
4.03125
4
import csv def loaddata(file_name, max_rows = -1): """ Pre-processing Reading file into a list """ # Open file handle from data.csv file = open(file_name) # Read first line of the file # The first line contains information about the types in each column typeStr = file.readline() types = typeStr.rstrip().split(';') # Read second line of the file # The second line contains the header information for each column headerStr = file.readline() headerNames = headerStr.rstrip().split(';') # List for collecting row data, once they've been processed collectionList = list() # Iterate through each row in the file row_num = 0 for row in file: if 0 <= max_rows <= row_num: break # Split the row into columns columns = row.rstrip().split(";") # Initialize new dictionary to contain column values dictionary = dict() # For 0 to length of columns (number of columns) # For each column, create new entry in the dictionary with the name of the header # Insert converted value for column_i, valueStr in enumerate(columns): # Convert data type to the one described in the corresponding column in the first row if types[column_i] == "str": dictionary[headerNames[column_i]] = valueStr if types[column_i] == "float": valueStr = valueStr.replace(",", ".") dictionary[headerNames[column_i]] = float(valueStr) # Add collection to the list collectionList.append(dictionary) row_num = row_num + 1 # Close file handle, so other programs are able to use it file.close() return collectionList def load_targets(file_name): with open(file_name) as csvfile: reader = csv.DictReader(csvfile, delimiter=';', lineterminator='\n',) lst = [] for r in reader: lst.append(r) return {k: float(v.replace(',', '.')) for k, v in lst[0].items()} def write_to_csv(data): fieldnames = sorted([key for key in data[0]]) with open('transpose.csv', 'w') as csvfile: writer = csv.DictWriter(csvfile, delimiter=';', fieldnames=fieldnames, lineterminator='\n') writer.writeheader() writer.writerows(data)
31cac0bf6296afbb5219e8633226060296726e41
m32/endesive
/endesive/pdf/PyPDF2_annotate/util/geometry.py
4,446
4.0625
4
# -*- coding: utf-8 -*- """ Geometry ~~~~~~~~ Geometry utility functions :copyright: Copyright 2019 Autodesk, Inc. :license: MIT, see LICENSE for details. """ import math def normalize_rotation(rotate): if rotate % 90: raise ValueError('Invalid Rotate value: {}'.format(rotate)) while rotate < 0: rotate += 360 while rotate >= 360: rotate -= 360 return rotate def to_radians(degrees): return degrees * math.pi / 180 def rotate(degrees): """Return a homogenous rotation matrix by degrees :params int degrees: integer degrees :returns list: matrix rotated by degrees, 6-item list """ radians = to_radians(degrees) return [ math.cos(radians), math.sin(radians), -math.sin(radians), math.cos(radians), 0, 0, ] def translate(x, y): return [1, 0, 0, 1, x, y] def scale(x_scale, y_scale): return [x_scale, 0, 0, y_scale, 0, 0] def identity(): return [1, 0, 0, 1, 0, 0] def matrix_multiply(*args): """Multiply a series of matrices. len(args) must be at least two. If more than two matrices are specified, the multiplications are chained, with the left-most matrices being multiplied first. E.g. matrix_multiply(A, B, C) => (A*B)*C What this means for combining affine transformations is that they are applied in reverse order. For instance, to perform rotation R, scale S, and translation T, in that order, you would use: matrix_multiply(T, S, R) Each matrix is a 6-item homogenous matrix. """ if len(args) < 2: raise ValueError('Cannot multiply fewer than two matrices') r = _matrix_multiply(args[0], args[1]) for m in args[2:]: r = _matrix_multiply(r, m) return r def matrix_inverse(matrix): """Invert a 6-item homogenous transform matrix. A transform matrix [a, b, c, d, e, f] is part of a 3x3 matrix: a b 0 c d 0 e f 1 Invert it using the formula for the inverse of a 3x3 matrix from http://mathworld.wolfram.com/MatrixInverse.html """ a, b, c, d, e, f = matrix determinant = float(a * d - b * c) unscaled = [d, -b, -c, a, c * f - d * e, b * e - a * f] return [x / determinant for x in unscaled] def _matrix_multiply(A, B): a00, a01, a10, a11, a20, a21 = A b00, b01, b10, b11, b20, b21 = B b02, b12, b22 = 0, 0, 1 # We don't have to compute all entries of the new matrix during # multiplication, since any multiple of affine transformations is an affine # transformation, and therefore homogenous coordinates. c00 = b00 * a00 + b01 * a10 + b02 * a20 c01 = b00 * a01 + b01 * a11 + b02 * a21 c10 = b10 * a00 + b11 * a10 + b12 * a20 c11 = b10 * a01 + b11 * a11 + b12 * a21 c20 = b20 * a00 + b21 * a10 + b22 * a20 c21 = b20 * a01 + b21 * a11 + b22 * a21 return [c00, c01, c10, c11, c20, c21] def transform_point(point, matrix): """Transform point by matrix. :param list point: 2-item list :param list matrix: 6-item list representing transformation matrix :returns list: 2-item transformed point """ x, y = point a, b, c, d, e, f = matrix # This leaves out some unnecessary stuff from the fact that the matrix is # homogenous coordinates. new_x = x * a + y * c + e new_y = x * b + y * d + f return [new_x, new_y] def transform_vector(vector, matrix): """Transform a vector by a matrix. This is similar to transform_point, except that translation isn't honored. Think of a vector as displacement in space, and a point as, well, a point in space. :param list vector: 2-item list :param list matrix: 6-item list representing transformation matrix :returns list: 2-item transformed point """ x, y = vector a, b, c, d, _, _ = matrix new_x = x * a + y * c new_y = x * b + y * d return [new_x, new_y] def transform_rect(rect, matrix): """Transform a rectangle specified by two points (lower left and upper right) by a transformation matrix. :param list rect: [x1, y1, x2, y2] :param list matrix: transformation matrix :returns list: [x1, y1, x2, y2] with transformed points """ x1, y1 = transform_point(rect[:2], matrix) x2, y2 = transform_point(rect[2:], matrix) x1, x2 = sorted([x1, x2]) y1, y2 = sorted([y1, y2]) return [x1, y1, x2, y2]
393d6c46bd42073f373048e21364995525294461
kale887/Python3.6
/Practice/dict-2.py
847
3.640625
4
names = [] names.append({ 'first': 'Dam', 'last': 'yelo', 'suffix': '22'}) names.append({'fist': 'jane'}) for name in names: x = name.get('first') y = name.get('last') z = name.get('suffix') print(x,y,z) lelanddict = { "name": { "first": "Leland", "middle": "Dewitt", "last": "Stanford", "suffix": "Jr.", "title": "Mr." } "birth": { "date": 1868 - 05 - 14, "place": { "city": "Sacramento", "state": "California", "country": "United States" }, "death": { "date": "1884-03-13", "place": { "city": "Florence", "country": "Italy" } } } }
8cfcb5d95955bfd7b3cd75487c8f43c27eb2d575
pleeplee-robot/interface
/pleepleeapp/plant.py
758
3.59375
4
#!/usr/bin/env python3 import pygame from pygame.locals import * import sys import time class Plant: """Simple plant representation. Contains information of a plant. Attributes: pos_x: x coordinate of the plant. pos_y: y coordinate of the plant. width: width of the plant. height: height of the plant. picture_path: path to the picture file that represents the plant """ def __init__(self, pos_x, pos_y, width, height, picture_path): """Initialize the plant with position, dimension and picture path""" self.pos_x = pos_x self.pos_y = pos_y self.width = width self.height = height self.picture_path = picture_path self.time_to_water = 0
dc4e084a53efc0dae345eddafb5432ff050732cb
sameerraghuram/logical-timestamp
/process.py
9,218
4.03125
4
''' Write a program that computes vector clocks of events that occur in financial transactions. Three processes (1, 2, and 3) all start with balance = $1,000. At each process, one of the three events, namely withdraw, deposit, and send money to another process, happens once every five seconds chosen randomly. The amount of all the transactions must be less than $100. Display the vector clocks of each event. @author Sameer Raghuram @email sr3669@rit.edu, sameer.raghuram@gmail.com ''' import json import socket import time import random import threading import sys class Process: ''' One of the processes in our application. Has an initial balance of 1000. Performs one of three actions every 5 seconds: 1. Withdraw : Withdraws money from account 2. Send Money: Sends money to another process 3. Deposit: Deposits money into account (independently or when recieved from another process). Each of these actions has a vector timestamp associated with it. This timestamp will be displayed on the console. Each process starts with vector time (0,0,0) (for a 3-process system). ''' def __init__(self): self.vector_time = [0,0,0] self.PEER_LIST = ['glados.cs.rit.edu', 'doors.cs.rit.edu', 'hendrix.cs.rit.edu'] self.vector_index = self.PEER_LIST.index(socket.getfqdn()) self.balance = 1000 self.access_lock= threading.Lock() self.PORT = 23648 listener = self.create_listener(('0.0.0.0',self.PORT)) #Start accepting incoming connections thread = threading.Thread(target=self.accept_connections, args=[listener], daemon=True) thread.start() def increment_clock(self): ''' Increments the vector time index of the current process. :return: None :rtype: None ''' self.vector_time[self.vector_index] += 1 def compare_clocks(self, other_clock): ''' Compares the logical time registered for other processes in our vector time. Chooses maximum. :param other_clock: Vector time clock of the other process :type other_clock: List :return: None :rtype: None ''' for i in range(len(self.vector_time)): #Ignore our pprocess index if i == self.vector_index: pass #Else, choose maximum value else: self.vector_time[i] = max(self.vector_time[i], other_clock[i]) def create_listener(self,address): ''' Creates a server socket on the specified address. :param address: (address,port) :type address: Tuple :return: server socket :rtype: Socket ''' listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) listener.bind(address) listener.listen(12) return listener def accept_connections(self,listener): ''' Accepts a connection and creates another thread to handle it. :param listener: Our listening serversocket :type listener: Socket :return: None :rtype: None ''' while(True): client_socket,client_address = listener.accept() thread = threading.Thread(target=self.handle_connections, args=[client_socket], daemon= True) thread.start() def handle_connections(self, client_socket): ''' Handles a new connection. In our implementation, a process can only get one type of message - Deposit. :return: None :rtype: None ''' request_dict = json.loads(client_socket.recv(1024).decode()) request = request_dict['request'] message_dict = request_dict['message'] if request == 'DEPO': self.handle_deposit(message_dict) elif request == 'EXIT': print("Exitting") sys.exit(0) def handle_deposit(self, message_dict): ''' Deposits an amount of money either recieved form another pro cess or independently. :param message_dict: :type message_dict: :return: :rtype: ''' amount = message_dict['amount'] other_clock = message_dict['time'] sender = message_dict['sender'] #acquire access token self.access_lock.acquire() self.increment_clock() self.compare_clocks(other_clock) event_time = self.vector_time self.balance += amount event_balance = self.balance #release access token self.access_lock.release() #print message #Print event onto console print("Deposit {} from {} \n" "Event Balance: {} \n" "Event Time: {} \n" "********************************".format(amount, sender, event_balance, event_time)) def send_money(self, peer_choice = None): ''' Sends an amount of money to another proccess. The amount is randomly chosen and is always within 100. :return: :rtype: ''' amount = random.randint(1,100) request = 'DEPO' if not peer_choice: peers = self.PEER_LIST.copy() peers.remove(socket.getfqdn()) random_peer_choice_index = random.randint(0,len(peers)-1) random_peer_choice = peers[random_peer_choice_index] else: random_peer_choice = peer_choice #obtain access token self.access_lock.acquire() if not peer_choice: self.increment_clock() current_time = self.vector_time.copy() if not peer_choice: self.balance -= amount event_balance = self.balance #release access token self.access_lock.release() message_dict = {'amount':amount, 'sender':socket.getfqdn(), 'time':current_time} request_dict = {'request':request, 'message':message_dict} request_blob = json.dumps(request_dict).encode() #Send message send_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) send_sock.connect((random_peer_choice,self.PORT)) send_sock.send(request_blob) send_sock.close() #Print event onto console if not peer_choice: print("Sent {} to {} \n" "Event Balance: {} \n" "Event Time: {} \n" "********************************".format(amount, random_peer_choice, event_balance, current_time)) def withdraw_money(self): ''' Withdraws an amount of money from the account. The amount is randomly chosen and is always within 100. :return: None :rtype: None ''' amount = random.randint(1,100) #obtain access token self.access_lock.acquire() self.increment_clock() current_time = self.vector_time.copy() self.balance -= amount event_balance = self.balance #release access token self.access_lock.release() #Print event onto console print("Withdraw {} \n" "Event Balance: {} \n" "Event Time: {} \n" "********************************".format(amount, event_balance, current_time)) def send_exit(self): ''' Tells other processes to close. Called externally, on a keyboard close. :return: :rtype: ''' peers = self.PEER_LIST.copy() peers.remove(socket.getfqdn()) request_dict = {'request':'EXIT', 'message': {} } request_blob = json.dumps(request_dict).encode() for peer in peers: send_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) send_sock.connect((peer,self.PORT)) send_sock.send(request_blob) def do_things(process): ''' Does a withdraw, deposit or send money every 5 seconds. :param process: Our current process :type process: Process :return: None :rtype: None ''' while True: choice = random.randint(1,3) #Deposit money if choice == 1: process.send_money(socket.getfqdn()) #Send money elif choice == 2: process.send_money() #Withdraw money else: process.withdraw_money() time.sleep(5) if __name__ == '__main__': process = Process() try: while True: n = input("Please enter 1 to start doing things") if n == '1': break else: print("Please enter 1 ") do_things(process) except KeyboardInterrupt: print("Exitting") process.send_exit() except ConnectionRefusedError: print("Connection refused. Closing..")
b6e227e242259e9378e9dc5f39cf23a38ae48a66
Hariharan2199/python
/oddeve.py
83
4
4
x=int(input("enter the no ")) if(x%2==0): print("prime") else: print("odd")
fb99e7ad17beaa83dce50ff54768cab4571b9dd8
lixueyuan/Python_project
/third/GetUserInfo.py
300
3.78125
4
#----使用type()----判断系统自带的类型.例如int string 或则 ValueError等等这样的类型我们可以直接用type() #那么如果判断自己定义的class或者是通过集成创建的自定义类型我们就可以使用另一个函数来做判断 #isinstance() print('hello type')
adab5b52f203a6405486d65ac93cf132f5d0516b
nylasabrine/FinalProject
/countingletters.py
453
3.59375
4
''' Created on Nov 18, 2017 @author: ITAUser ''' def characterappearances(filename, mychar): f = open(filename , 'r') count = 0; run = True while run: text = f.read(1) text = text.lower() if text == mychar: count = count +1; if text == '': break print(count) characterappearances('constituton.txt' , 'a') #read the file #split the file #count the letters #print result
d9fd6aa251f76310607d6d6d992342cab8634e02
kurowsk1/code-club
/area of a circle.py
1,216
4.09375
4
from math import pi from sys import exit # this imports the math library, which contains various mathematical functions radius = input(">Enter circle radius in meters: ") # what follows the '=' sign assigns that value to the variable 'radius'. # The 'input' command lets the program know to wait for the user to input # some value. def intCheck (input): if str.isdigit(input): # The str.isdigit() method is detailed here: https://www.tutorialspoint.com/python/string_isdigit.htm return int(input) else: exit("Invalid entry") # Defines a function that takes an input ('input') and runs an 'if' statement. # If the input is a 'digit', the function returns the input converted to # an integer. If the input is not a 'digit' then the program is terminated. radius = intCheck(radius) # This is running the variable 'radius' through the intCheck function we defined earlier. area = pi*radius**2 # This defines a new variable; area. The pi function is used from the math # library and it is multiplied by the square of radius. Note the use of # the ** to raise radius to an index of 2 print ("The area of a circle with a radius of", radius, "meters is", area, "square meters") # Prints the result
07408aa7f4a093c25ea893f6ffb8ab01fcd3fd41
EdsonFragnan/CursoPython
/Parte_1/Semana_4/Exercicios_entregar/NumerosImpares.py
165
3.8125
4
valor = int(input('Digite o valor de n: ')) i = 0 valor_impar = 1 while i < valor: print(valor_impar) i = i + 1 valor_impar = valor_impar + 2
244e6d0dd7633646f3fd496a036ae000d8889d56
EdsonFragnan/CursoPython
/Parte_2/Semana_3/Exercicios_entregar/TipoTriangulo.py
922
3.84375
4
class Triangulo: def __init__(self, a, b, c): self.lA = a self.lB = b self.lC = c def tipo_lado(self): if self.lA <= 0 or self.lB <= 0 or self.lC <= 0: return False else: if self.lA + self.lB > self.lC and self.lB + self.lC > self.lA: if self.lA == self.lB and self.lA == self.lC and self.lB == self.lC: return 'equilátero' elif self.lA != self.lB and self.lA != self.lC and self.lB != self.lC: return 'escaleno' elif self.lA == self.lB or self.lA == self.lC or self.lB == self.lC: return 'isósceles' if self.lA**2 == self.lB**2+self.lC**2 or self.lB**2 == self.lA**2 + self.lC**2 or self.lC**2 == self.lA**2 + self.lB**2: return True else: return False
42d82aef93c878a2b548dd308d0a6e580419e82f
EdsonFragnan/CursoPython
/Parte_1/Semana_4/Exercicios_entregar/NumerosAdjacentes.py
386
3.953125
4
numero = int(input("Digite um numero: ")) anterior = numero % 10 numero = numero // 10; n_adjacente = False; pos = 0 while numero > 0 and not n_adjacente: atual = numero % 10 if atual == anterior: n_adjacente = True else: pos += 1 anterior = atual numero = numero // 10 if n_adjacente: print('sim') else: print('não')
a7fff59fb7b9c823e0690252b212479c30c0d117
EdsonFragnan/CursoPython
/Parte_2/Semana_4/Exercicios_entregar/SelectionSort.py
250
3.640625
4
def ordena(lista): for i in reversed(range(len(lista))): val = 0 for j in range(1, i + 1): if lista[j] > lista[val]: val = j lista[i], lista[val] = lista[val], lista[i] return lista
c454fdec7a34c4556ca9f65747ef810edb8b6ddc
EdsonFragnan/CursoPython
/Parte_1/Semana_3/Exercicios_entregar/LongePerto.py
319
3.984375
4
import math a = int(input('Digite um número para a:')) b = int(input('Digite um número para b:')) c = int(input('Digite um número para c:')) d = int(input('Digite um número para d:')) distancia = ((a - c)**2) + ((b - d)**2) if (math.sqrt(distancia) >= 10): print('longe') else: print('perto')
78194dddcdbfc0e301efc430d038907a7b7463e5
Spiderbeard/Python
/payrate.py
394
4.03125
4
hours = input("Enter the hours ") pay = input("Enter the payrate ") try: fhours = float(hours) fpay = float(pay) except: print("Error, Please enter a numeric input") quit() total = 0 if fhours <= 40: total = fhours * fpay else: extra = fhours - 40 print(extra) total = (fhours-extra) * fpay print(total) total += extra * (fpay * 1.5) print(total)
d218d9bf4cecadd1baf22e2632df726eff5b9cd5
pavensharma/python-bmi-calculator
/bmi_calculator.py
204
3.828125
4
weight = input("Insert your weight (in KG)") height = input("insert your height (M)") weight = float(weight) height = float(height) bmi = weight / (height**2) print(bmi) #Test #paven's comment here.
740dd14a07630424e5db6b373cb7347040c417c4
doness/eris
/actions/commands.py
4,023
3.734375
4
import dice import settings class Command: """The base Command class Attributes: message (str): The message to parse from Discord command (str): The parsed command help_message (str): The help message for a command admin_required (bool): Whether or not a user needs to be an admin to execute the command. channel_required (bool,: Whether or not the command has to have been initiated from a channel to be executed. """ message = None command = None help_message = None admin_required = False channel_required = False def __init__(self, client, message): self.client = client self.message = message parts = message.content.split(' ', 1) self.command = parts[0] # TODO : make this separate into multiple args for multi-part commands if len(parts) > 1: self.args = parts[1] else: self.args = None def __str__(self): return self.help_message def __repr__(self): return "Command(command={0}, message={1}".format(self.command, self.message) def execute(self): """The main execution method for Command types This should be overridden by classes that extend Command. Returns: string """ raise NotImplementedError() class HelpCommand(Command): """Show the user a help message This will show a help message: Commands !command1 - this command does something !command2 - this command does something as well """ command = '!help' help_message = '{} - Show this message'.format(command) def execute(self): return self._get_help_string() @staticmethod def _get_help_string(): """Builds the help message to display Returns: string: the help message """ help_string = '\n'.join([command.help_message for command in command_list]) return 'Commands\n{}'.format(help_string) class EchoCommand(Command): """Echo text back to the user/channel.""" command = '!echo' help_message = '{} - Echo chamber'.format(command) def execute(self): if not self.args: # Quote Starbuck message = "Nothin' but the rain" else: message = self.args return message class RollCommand(Command): """Roll dice""" command = '!roll' help_message = '{} - Roll dice: !roll 3d6'.format(command) def execute(self): try: if self.args: return self._roll(self.args) else: return self._roll(settings.DEFAULT_DIE_ROLL) except: return 'Those dice were loaded.' @staticmethod def _roll(message): """Rolls dice given a message Args: message (str): A description of the dice to roll. Returns: list[int]: The result of the roll(s) """ result = dice.roll(message) return result class KillCommand(Command): """Kill Eris""" command = '!kill' help_message = '{} - Kills the bot'.format(command) admin_required = True channel_required = True def execute(self): quit() def get_command_from_message(message): """Parse the command from a Discord message Args: message: The received Discord message Returns: string: The parsed command """ return message.content.split(' ', 1)[0] def get_command_from_list(message): """Get a command from the command_list given a command string Args: message: The received message from Discord Returns: Command: The command that was found. None if no matches. """ command_string = get_command_from_message(message) command = [c for c in command_list if c.command == command_string] return command[0] if command else None command_list = [HelpCommand, EchoCommand, RollCommand, KillCommand]
64ef27d91c24c113f5ec215237c6e6cd6a479c40
AlieFries/ProjectEuler
/project_euler_12_2.py
633
3.6875
4
def divisors(n): count = 0 if n % 2 == 0: n = n/2 count += 1 while n % 2 == 0: n = n/2 count += 1 divisors = count+1 div = 3 while n != 1: count = 0 while n % div == 0: n = n/div count += 1 divisors = divisors*(count + 1) div += 2 return divisors largest_count = 0 most_factors = 0 for i in range(3, 20000): tri = i*(i+1)/2 if divisors(tri) > largest_count: largest_count = divisors(tri) most_factors = tri if divisors(tri) > 500: break print largest_count print most_factors
fd55697157167c82a9c6a4f2ea3b432de136a9f7
AlieFries/ProjectEuler
/project_euler_12.py
1,543
3.765625
4
##first generate a list of triangle numbers, formula for tri numbers, n(n+1)/2 triangles = [] ##for i in range(1,100): ## num = 0 ## for a in range(1, i+1): ## num += a ## triangles.append(num) ##print triangles ##generate larger tris based on formula largest_count = 0 most_factors = 0 for i in range(12000, 12500): tri = i*(i+1)/2 count = 0 for n in range(1, tri): if tri % n == 0: count += 1 if count > largest_count: largest_count = count most_factors = tri ##now figure out how many factors each element of triangles has ##largest_count = 0 ##tris_with_fact_count = [] ##most_factors = 0 ##for item in triangles: ## count = 0 ## for n in range(1, item/2+1): ## if item % n == 0: ## count += 1 ## tris_with_fact_count.append([item, count]) ## if count > largest_count: ## largest_count = count ## most_factors = item ##print tris_with_fact_count print largest_count print most_factors ##compute number of factors using prime factorization most_divisors = 0 for n in range(6, 100): count = 0 if n % 2 == 0: n = n/2 count += 1 while n % 2 == 0: n = n/2 count += 1 divisors = count+1 div = 3 while n != 1: count = 0 while n % div == 0: n = n/div count += 1 divisors = divisors*(count + 1) div += 2 if divisors > most_divisors: most_divisors = divisors ##print divisors print most_divisors
c519ba762f6623c5c473525d7d50334b32c1c4a1
jonathanryding/Assignments
/Spreading Law of droplets, Project 1.py
33,947
4.03125
4
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d #Spreading Law of droplets, Project 1 #Determine the spreading law (relationship between the speed of the contact line and the contact angle) of picolitre droplets using the spherical cap approximation. #function definitions for manipulating data sets given def radiusSpeed(radius, time): #calculates the discrete derivative of radii list input. v = [] #empty array created in order to save values step by step R = radius t = time for i in range ( 0 , len(radius) - 1 ): dR = R[i +1] - R[i] dt = t[i+1] - t[i] v_step = dR / dt v.append(v_step) #forward divided difference scheme, velocities are approximated to be the difference of the radii at the point and one time step ahead, divided by the time step. #alt. schemes could be a backward difference divide scheme or a central divided scheme. return v def meanOf2Array(array1, array2): #calculates the mean between elements of the same index across 2 arrays (lists). mean = [] for i in range(0, len(array1)): mean_step = np.mean( (array1[i], array2[i]) ) #np.mean calculates average of elements written. mean.append(mean_step) #adds to initially empty array continually until all are computed return mean def meanOf3Array(array1, array2, array3): #calculates the mean between elements of the same index across 3 arrays (lists). mean = [] for i in range(0, len(array1)): mean_step = np.mean( (array1[i], array2[i], array3[i]) ) mean.append(mean_step) return mean def stdevOf2Array(array1, array2): stdev = [] for i in range(0, len(array1)): stdev_step = np.std( (array1[i], array2[i])) #np.std in a similar way to np.mean stdev.append(stdev_step) return stdev def stdevOf3Array(array1, array2, array3): #calculates the standard deviation of elements that have the same index in 3 arrays (lists) through the same method as stdevOf2Array(array1, array2) stdev = [] for i in range(0, len(array1)): stdev_step = np.std( (array1[i], array2[i], array3[i]) ) stdev.append(stdev_step) return stdev def propagatedErrorOnV(ErrorOnRadius, timestep): #Defining a function to use for error propagation DV = [] DR = ErrorOnRadius for i in range ( 0 , len(DR) - 1 ): #length of radii - 1 as a point was used in calculation DV_step =(pow(( pow( (DR[i +1]),2) + pow((DR[i]),2) ), 0.5)/ timestep) #uncertainties on the radii in front and at the point are added in quadrature, due to how the velocity was defined as the forward discrete derivative. #alternatively, could create a polynomial fit to the time-evolution of the radius graph, then differentiate that but that would include an error from the fit. DV.append(DV_step) return DV def heightArray(radius): #calculate the droplet (height at the centre) given the radius using the spherical cap approximation and output as an array. # height = [] for i in range(0, (len(radius) - 1) ): Hpoly = [1, 0 , 3 * pow(radius[i] , 2), -(6 * vol / np.pi)] #polynomial of h from a spherical top of a sphere. a= np.roots(Hpoly) #np.roots returns the roots of a polynomial of order n that is given in a rank-1 array of length n + 1, where the array elements are the coefficients of decreasing order. #e.g. inputting [a, b, c] corresponds to polynomial ax^2 + bx + c = 0 #https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.roots.html height.append(np.real(a[2])) #roots where h is non-negative and real are selected. Negative and imaginary heights have no physical significance. #Units of h are micrometres (radii is micrometres and volume micrometres cubed) return height def thetaArray(radius, height): #calculates the contact angle using heights calculated by heightArray(radius) of the droplet to the surface and organises in an array. #expect contacts angles to be less than pi/2 (hydrophilic) theta = [] for i in range(0, (len(radius) - 1) ): #in range 0 to number of data points - 1 as there is one les data point in the velocity lists than the radii lists. #This makes the velocity and theta data sets the same size so they can be plotted to observe the spreading law. #I have chosen to remove the last velocity as there are more results in that region of the contact angle and I would expect the drop to become stationary after a long period of time. theta_step = np.pi / 2 - np.arctan( (pow(radius[i],2) - pow(height[i], 2)) / (2 * radius[i] * height[i]) ) #from geometry of a spherical cap, where theta is angle from the base of the cap to the tangent of the sphere. theta.append(theta_step) return theta def reducedChiSquared(Ydata, Yfit, Yerr, Nparameters): #calculates the reduced chi-squared of a general fit to data step-by-step by summing the square of each residual and dividing by the number of degrees of freedom of the fit. #Yfit is the array of velocities from the fitted curve at the same angle as Ydata. #chi-squared is an indicator of how appropriate the fit is to the data. chiold = 0 #initial chi-squared value begins at 0. for i in range(0, len(Ydata)): #calculating the weighted sum of the residuals squared for each data point chi_step = pow( ((Ydata[i] - Yfit[i])/Yerr[i]) , 2 ) chiSquared = chi_step + chiold chiold = chiSquared reduChiSquare = (chiSquared / (len(Ydata) - Nparameters) ) #To calculate the reduced chi-squared, divide the chi-squared by the number of degrees of freedom. This is equal to the number of data points used minus the number of parameteres of the fit. return reduChiSquare def interpolate(X , Xspacing, Ydata): Finterpolated = interp1d(X, Ydata, kind = "linear", fill_value = "extrapolate") #returns a function that uses interpolation to find the value of new points #smooths data sets that shows small isolated errors #spline interpolation approximates the function by a mean of series of polynomials (series over adjacedent intervals, each has a continuous derivative) #'kind:' specifies the order of spline polynomials used, e.g. a linear spline is a continiuous function formed by connecting linear segments, a cubic spline connects cubic segments Y = Finterpolated(Xspacing) #evenly spaced, interpolated data points return(Y) opened = 0 #reading in data for two droplets spreading on two different surfaces try: data11 = np.loadtxt("Top_view_drop_1_data_run1.txt") data12 = np.loadtxt("Top_view_drop_1_data_run2.txt") data13 = np.loadtxt("Top_view_drop_1_data_run3.txt") data21 = np.loadtxt("Top_view_drop_2_data_run1.txt") data22 = np.loadtxt("Top_view_drop_2_data_run2.txt") t1 = data11[:,0] #time since spreading started, measured in seconds for the first droplet R1_1 = data11[:,1] #instantaneous radii in micrometres. #run 1, drop 1 R2_1 = data12[:,1] #run 2 R3_1 = data13[:,1] #run3 t2 = data21[:,0] #second drop 2 data, time in seconds. R1_2 = data21[:,1] # radii #run 1, drop 2 R2_2 = data22[:,1] #run 2 opened = 1 print("Files loaded in") except: print("Files could not be opened") #volume of drops vol = 7600 #7.6 picolitres, 7600 micrometres cubed #The volume of the droplet was the same for all data sets. if opened == 1: #opened successfully, begin data manipulation and analysis #drop 1, using functions to maniupulate data given meanR_1 = meanOf3Array(R1_1, R2_1, R3_1) #Array (list) containing the means of all drop 1 data sets where the first index is at t = 0s *All radii measured in micrometres. stdErrR_1 = stdevOf3Array(R1_1, R2_1, R3_1) #Standard deviation of all data from drop 1 V1_1 = radiusSpeed(R1_1, t1) #Contact speed of the first data set, for drop 1 V2_1= radiusSpeed(R2_1, t1) #Contact speed of the second data set, for drop 1 V3_1 = radiusSpeed(R3_1, t1) #Contact speed of the third data set, for drop 1 meanV_1 = meanOf3Array(V1_1, V2_1, V3_1) #Array containing mean contact speeds of drop 1 stdErrV_1 = stdevOf3Array(V1_1, V2_1, V3_1) #Data spreads (standard deviation) of the contact speed of drop 1 H1_1 = heightArray(R1_1) #The spherical cap model heights of the data set 1, from drop 1 H2_1 = heightArray(R2_1) #The spherical cap model heights of the data set 2, from drop 1 H3_1 = heightArray(R3_1) #The spherical cap model heights of the data set 3, from drop 1 meanH_1 = meanOf3Array(H1_1, H2_1, H3_1) #Mean drop heights of drop 1 stdErrH_1 = stdevOf3Array(H1_1, H2_1, H3_1) #Data spreads of drop 1 theta1_1 = thetaArray(R1_1, H1_1) #Contact angles calculated from heights for data set 1 from drop 1 theta2_1 = thetaArray(R2_1, H2_1) #Contact angles for data set 2 from drop 1 theta3_1 = thetaArray(R3_1, H3_1) #Contact angles for data set 3 from drop 1 meanTheta_1 = meanOf3Array(theta1_1, theta2_1, theta3_1) #Mean contact angles for drop 1 stdErrTheta_1 = stdevOf3Array(theta1_1, theta2_1, theta3_1) #Standard deviations for drop 1 #drop 2 meanR_2 = meanOf2Array(R1_2, R2_2) #Mean radii for drop 2 stdErrR_2 = stdevOf2Array(R1_2, R2_2) #Standard deviations from the mean radii, drop 2 V1_2 = radiusSpeed(R1_2, t2) #Contact speed of the first data set of drop 2 V2_2= radiusSpeed(R2_2, t2) #Contact speed of the second data set of drop 2 meanV_2 = meanOf2Array(V1_2, V2_2) #Mean contact speeds of drop 2 stdErrV_2 = stdevOf2Array(V1_2, V2_2) #Standard deviations of the contact speed of drop 2 H1_2 = heightArray(R1_2) #The spherical cap model height of the data set 1, from drop 2 H2_2 = heightArray(R2_2) #The spherical cap model height of the data set 2, from drop 2 meanH_2 = meanOf2Array(H1_2, H2_2) #Mean drop heights of drop 2 stdErrH_2 = stdevOf2Array(H1_2, H2_2) #Standard deviations of drop 2 theta1_2 = thetaArray(R1_2, H1_2) #Contact angles for data set 1 from drop 2 theta2_2 = thetaArray(R2_2, H2_2) #Contact angles for data set 2 from drop 2 meanTheta_2 = meanOf2Array(theta1_2, theta2_2) #Mean contact angles from drop 2 stdErrTheta_2 = stdevOf2Array(theta1_2, theta2_2) #Standard deviations from drop 2 #Errors on contact speeds and angles can be propagated from the initial standard deviation of the data sets given. #This will be done in order to compare the errors and the more appropriate errors will be chosen. #Propagating errors to velocity: errV_1 = propagatedErrorOnV(stdErrR_1, (t1[1]-t1[0]) ) errV_2 = propagatedErrorOnV(stdErrR_2, (t2[1]-t2[0]) ) #Assuming error on time is negligible, use function as defined earlier #Propagating errors to drop height: errH_1 = [] #empty height error arrays to append errors to as they are calculated errH_2 = [] for i in range(0, len(stdErrR_1)-1): errH1_step = (3*stdErrR_1[i])/(meanH_1[i] + (2* vol)/(np.pi * pow(meanH_1[i], 2))) errH1_step = stdErrR_1[i] * pow( ((2 * vol /np.pi *meanH_1[i]) - (pow(meanH_1[i], 2)/3)),0.5) /((vol / (np.pi*pow(meanH_1[i], 2))) + (meanH_1[i]/3) ) #errors estimated by rewriting Hpoly = [1, 0 , 3 * pow(radius[i] , 2), -(6 * vol / np.pi)] so R is a function of h, f(h). # R(h) = sqrt(( 2*volume / pi* h) - (h^2 / 3) ) #Then error on h = error on r / |partial d/dh(f(h))| evaluated at each point #partial d/dh(f(h)) is -( vol / (pi * h^2) + h / 3) * ( 2 * vol / pi*h - h^2 /3)^-0.5 errH_1.append(errH1_step) errH2_step = stdErrR_2[i] * pow( ((2 * vol /np.pi *meanH_2[i]) - (pow(meanH_2[i], 2)/3)),0.5) /((vol / (np.pi*pow(meanH_2[i], 2))) + (meanH_2[i]/3) ) errH_2.append(errH2_step) errTheta_1 = [] #empty theta error arrays to append errors to as they are calculated errTheta_2 = [] for i in range(0, len(meanH_1)): errTheta_1step =( ( 9 * vol ) / ( pow((((2*vol )/ (np.pi * meanH_1[i])) - (pow(meanH_1[i], 2))/ 3 ), 0.5)*(3*vol + np.pi * meanH_1[i])) )* errH_1[i] errTheta_2step =( ( 9 * vol ) / ( pow((((2*vol )/ (np.pi * meanH_2[i])) - (pow(meanH_2[i], 2))/ 3 ), 0.5)*(3*vol + np.pi * meanH_2[i])) )* errH_2[i] errTheta_1.append(errTheta_1step) errTheta_2.append(errTheta_2step) #Equation for contact angle is rewritten so it only a function of h. Then the error on theta = error on h * |partial d/dh(f(h))| #The errors of R and h cannot be adde in quadrature as it is assumed that variables are independent. #simpler partial d/dh(f(h)) form confirmed by using www.wolframalpha.com: #https://www.wolframalpha.com/input/?i=%E2%88%82%2F%E2%88%82x(+-arctan(+++++++++(V%2F(%CF%80x)+-+2(x%5E2)%2F3)+%2F+(x%E2%88%9A(2V%2F%CF%80x+-+x%5E2+%2F3+)++++)+) #Plot the time-evolution of the average radius of the spreading droplets print("Plotting the time-evolution of the average radius of droplets 1 & 2") plt.plot(t1, meanR_1) plt.title("Time-evolution of the radius (Drop 1)") plt.xlabel("Time, s") plt.ylabel("Radius, μm/s") plt.errorbar(t1, meanR_1, yerr = stdErrR_1, ecolor = "r") plt.show() #Plot the time-evolution of the average radius of the spreading droplet plt.plot(t2, meanR_2) plt.title("Time-evolution of the radius (Drop 2)") plt.xlabel("Time, s") plt.ylabel("Radius, μm/s") plt.errorbar(t2, meanR_2, yerr = stdErrR_2, ecolor = "r") plt.show() #Plots showing errors and then choosing an error method based on the results overall. print("Displaying results from two error evaluation methods") plt.plot(meanTheta_1, meanV_1) plt.title("Errors from using spread of the contact speed and angle (Drop 1)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_1, meanV_1, xerr = stdErrTheta_1, yerr = stdErrV_1, ecolor = "r") plt.show() plt.plot(meanTheta_1, meanV_1) plt.title("Errors from propagation (Drop 1)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_1, meanV_1, xerr = errTheta_1, yerr = errV_1, ecolor = "g") plt.show() #spreading laws with different errors methods for drop 2 plt.plot(meanTheta_2, meanV_2) plt.title("Errors from using spread of the contact speed and angle (Drop 2)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_2, meanV_2, xerr = stdErrTheta_2, yerr = stdErrV_2, ecolor = "r") plt.show() plt.plot(meanTheta_2, meanV_2) plt.title("Errors from propagation (Drop 2)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_2, meanV_2, xerr = errTheta_2, yerr = errV_2, ecolor = "g") plt.show() #drop1, Propagated errors on contact speed appear reasonable, with the exception of the point near 0.034 radians. #drop1, Propagated errors on contact angle are generally the same order as the data spread errors, with some appearing too small to be true. #Data spread is good for large amounts of data #drop1, Propagated errors on the contact angle are much larger than the data spread. #Will be using the errors from the data spread for fitting quadratics, cubic, De Gennes law and Cox-Voinox law to the spreading law data. #quadratic fits, drop 1 print("Displaying results from fits to Drop 1 data using errors from data spread.") (quadcoef1, quadcovr1) = np.polyfit(meanTheta_1, meanV_1, 2 , cov = True) quadcovr1 = np.array(quadcovr1).ravel() quadfitline1 = [] for i in range(0, len(meanTheta_1)): polyfitline = quadcoef1[0]*np.power(meanTheta_1[i], 2) + quadcoef1[1]*meanTheta_1[i] + quadcoef1[2] quadfitline1.append(polyfitline) errquadcoef1_1 = np.sqrt(quadcovr1[0]) errquadcoef2_1 = np.sqrt(quadcovr1[4]) errquadcoef3_1 = np.sqrt(quadcovr1[8]) plt.plot(meanTheta_1, meanV_1) plt.plot(meanTheta_1, quadfitline1) plt.title("Spreading law for Drop 1. Quadratic fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_1, meanV_1, xerr = stdErrTheta_1, yerr = stdErrV_1, ecolor = "r") plt.show() quadredChiSqu_1 = reducedChiSquared(meanV_1, quadfitline1, stdErrV_1, 3) #calculate reduced chisquared of fit print("The best fitted quadratic is: U(θ) = (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) θ + (%5.2f ± %5.2f) " %(quadcoef1[0], errquadcoef1_1, quadcoef1[1], errquadcoef2_1, quadcoef1[2], errquadcoef3_1)) print("This has reduced chi-squared: %5.2f" %quadredChiSqu_1) #cubic (cubicoef1, cubicovr1) = np.polyfit(meanTheta_1, meanV_1, 3 , cov = True) cubicovr1 = np.array(cubicovr1).ravel() cubicfitline1 = [] for i in range(0, len(meanTheta_1)): polyfitline = cubicoef1[0]*np.power(meanTheta_1[i], 3) + cubicoef1[1]*np.power(meanTheta_1[i],2) + cubicoef1[2]*meanTheta_1[i] + cubicoef1[3] cubicfitline1.append(polyfitline) errcubicoef1_1 = np.sqrt(cubicovr1[0]) errcubicoef2_1 = np.sqrt(cubicovr1[5]) errcubicoef3_1 = np.sqrt(cubicovr1[10]) errcubicoef4_1 = np.sqrt(cubicovr1[15]) plt.plot(meanTheta_1, meanV_1) plt.plot(meanTheta_1, cubicfitline1) plt.title("Spreading law for Drop 1. Cubic fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_1, meanV_1, xerr = stdErrTheta_1, yerr = stdErrV_1, ecolor = "r") plt.show() CUBICredChiSqu_1 = reducedChiSquared(meanV_1, cubicfitline1, stdErrV_1, 4) print("The best fitted cubic is: U(θ) = (%5.2f ± %5.2f) θ^3 + (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) θ + (%5.2f ± %5.2f) " %(cubicoef1[0], errcubicoef1_1, cubicoef1[1], errcubicoef2_1, cubicoef1[2], errcubicoef3_1, cubicoef1[3], errcubicoef4_1)) print("This fit has reduced chi-squared: %5.2f" %CUBICredChiSqu_1) #De Gennes law (DeGcoef1, DeGcovr1) = np.polyfit( (np.power(meanTheta_1, 2)), meanV_1, 1 , cov = True) DeGcovr1 = np.array(DeGcovr1).ravel() DeGfitline1 = [] for i in range(0, len(meanTheta_1)): fitline = DeGcoef1[0]*pow(meanTheta_1[i], 2) + DeGcoef1[1] DeGfitline1.append(fitline) errDeGcoef1_1 = np.sqrt(DeGcovr1[0]) errDeGcoef2_1 = np.sqrt(DeGcovr1[3]) plt.plot(meanTheta_1, meanV_1) plt.plot(meanTheta_1, DeGfitline1) plt.title("Spreading law for Drop 1. De Gennes fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_1, meanV_1, xerr = stdErrTheta_1, yerr = stdErrV_1, ecolor = "r") plt.show() DeGredChiSqu_1 = reducedChiSquared(meanV_1, DeGfitline1, stdErrV_1, 2) print("The best De Gennes fit is: U(θ) = (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) " %(DeGcoef1[0], errDeGcoef1_1, DeGcoef1[1], errDeGcoef2_1 )) print("This fit has reduced chi-squared: %5.2f" %DeGredChiSqu_1) # Cox- Voinox law (coxcoef1, coxcovr1) = np.polyfit( (np.power(meanTheta_1, 3)), meanV_1, 1 , cov = True) coxcovr1 = np.array(coxcovr1).ravel() COXfitline1 = [] for i in range(0, len(meanTheta_1)): fitline = coxcoef1[0]*pow(meanTheta_1[i], 3) + coxcoef1[1] COXfitline1.append(fitline) errcoxcoef1_1 = np.sqrt(coxcovr1[0]) errcoxcoef2_1 = np.sqrt(coxcovr1[3]) plt.plot(meanTheta_1, meanV_1) plt.plot(meanTheta_1, COXfitline1) plt.title("Spreading law for Drop 1 Cox-Voinox fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_1, meanV_1, xerr = stdErrTheta_1, yerr = stdErrV_1, ecolor = "r") plt.show() COXredChiSqu_1 = reducedChiSquared(meanV_1, COXfitline1, stdErrV_1, 2) print("The best Cox-Voinox fit is: U(θ) = (%5.2f ± %5.2f) θ^3 + (%5.2f ± %5.2f) " %(coxcoef1[0], errcoxcoef1_1, coxcoef1[1], errcoxcoef2_1 )) print("This fit has reduced chi-squared: %5.2f" %COXredChiSqu_1) #Interpolate contact angle and contact speed time-evolutions for less jagged data and more uniform data. #smoothing by spline interpolation on data sets for contact speed and angle for all 3 sets, and approximate errors on both by stdev X1 = np.linspace(meanTheta_1[0], meanTheta_1[-1], len(meanV_1)) # evenly spaced array of points where I want to interpolate my data to interpolatedV1_1 = interpolate(theta1_1, X1, V1_1) interpolatedV2_1 = interpolate(theta2_1, X1, V2_1) interpolatedV3_1 = interpolate(theta3_1, X1, V3_1) #interpolating evenly spread points from all sets of data then taking the mean and stdev for an estimate to the uncertainty on velocity meanIntV_1 = meanOf3Array(interpolatedV1_1, interpolatedV2_1, interpolatedV3_1) #taking the mean of all the interpolation results stdErrIntV_1 = stdevOf3Array(interpolatedV1_1, interpolatedV2_1, interpolatedV3_1) #standard deviation as an approximation of the error plt.plot(X1, meanIntV_1) plt.title("Spreading law for Drop 1 with interpolated data.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(X1, meanIntV_1, yerr= stdErrIntV_1, ecolor = "g") plt.show() #applying cox-voinox and de gennes fits again to now interpolated data #De Gennes law interpolated data (intDeGcoef1, intDeGcovr1) = np.polyfit( (np.power(X1, 2)), meanIntV_1, 1 , cov = True) intDeGcovr1 = np.array(intDeGcovr1).ravel() intDeGfitline1 = [] for i in range(0, len(X1)): fitline = intDeGcoef1[0]*pow(X1[i], 2) + intDeGcoef1[1] intDeGfitline1.append(fitline) intErrDeGcoef1_1 = np.sqrt(intDeGcovr1[0]) intErrDeGcoef2_1 = np.sqrt(intDeGcovr1[3]) plt.plot(X1, meanIntV_1) plt.plot(X1, intDeGfitline1) plt.title("Spreading law for Drop 1. De Gennes fit. (Interpolated data)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(X1, meanIntV_1, yerr = stdErrV_1, ecolor = "r") plt.show() intDeGredChiSqu_1 = reducedChiSquared(meanIntV_1, intDeGfitline1, stdErrIntV_1, 2) print("The best De Gennes fit is: U(θ) = (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) " %(intDeGcoef1[0], intErrDeGcoef1_1, intDeGcoef1[1], intErrDeGcoef2_1 )) print("This fit has reduced chi-squared: %5.2f" %intDeGredChiSqu_1) #cox-voinox law interpolated data (intcoxcoef1, intcoxcovr1) = np.polyfit( (np.power(X1, 3)), meanIntV_1, 1 , cov = True) intcoxcovr1 = np.array(intcoxcovr1).ravel() intcoxfitline1 = [] for i in range(0, len(X1)): fitline = intcoxcoef1[0]*pow(X1[i], 3) + intcoxcoef1[1] intcoxfitline1.append(fitline) intErrcoxcoef1_1 = np.sqrt(intcoxcovr1[0]) intErrcoxcoef2_1 = np.sqrt(intcoxcovr1[3]) plt.plot(X1, meanIntV_1) plt.plot(X1, intcoxfitline1) plt.title("Spreading law for Drop 1. Cox-Voinox fit. (Interpolated data)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(X1, meanIntV_1, yerr = stdErrV_1, ecolor = "r") plt.show() intcoxredChiSqu_1 = reducedChiSquared(meanIntV_1, intcoxfitline1, stdErrIntV_1, 2) print("The best Cox-Voinox fit is: U(θ) = (%5.2f ± %5.2f) θ^3 + (%5.2f ± %5.2f) " %(intcoxcoef1[0], intErrcoxcoef1_1, intcoxcoef1[1], intErrcoxcoef2_1 )) print("This fit has reduced chi-squared: %5.2f" %intcoxredChiSqu_1) #Using interpolated data has made it clearer to see that the de Gennes law is a better fit to larger contact angles. #drop 2 #quadratic fit, similar to method before (quadcoef2, quadcovr2) = np.polyfit(meanTheta_2, meanV_2, 2 , cov = True) quadcovr2 = np.array(quadcovr2).ravel() quadfitline2 = [] for i in range(0, len(meanTheta_2)): polyfitline = quadcoef2[0]*np.power(meanTheta_2[i], 2) + quadcoef2[1]*meanTheta_2[i] + quadcoef2[2] quadfitline2.append(polyfitline) errquadcoef1_2 = np.sqrt(quadcovr2[0]) errquadcoef2_2 = np.sqrt(quadcovr2[4]) errquadcoef3_2 = np.sqrt(quadcovr2[8]) plt.plot(meanTheta_2, meanV_2) plt.plot(meanTheta_2, quadfitline2) plt.title("Spreading law for Drop 2. Quadratic fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_2, meanV_2, xerr = stdErrTheta_2, yerr= stdErrV_2, ecolor = "g") plt.show() quadredChiSqu_2 = reducedChiSquared(meanV_2, quadfitline2, stdErrV_2, 3) print("The best fitted quadratic is: U(θ) = (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) θ + (%5.2f ± %5.2f) " %(quadcoef2[0], errquadcoef1_2, quadcoef2[1], errquadcoef2_2, quadcoef2[2], errquadcoef3_2)) print("This has reduced chi-squared: %5.2f" %quadredChiSqu_2) #A different fit may be more appropriate for Drop 2 (smaller contact angles) as the fit suggests contact speed begins to increase at lower contact angles (essentially when the droplet is almost fully spread out over its surface. This does not make sense physically as we expect that the contact speed slows as the drop reaches its miniumum contact angle. ) #cubic fit, similar to method before (cubicoef2, cubicovr2) = np.polyfit(meanTheta_2, meanV_2, 3 , cov = True) cubicovr2 = np.array(cubicovr2).ravel() cubicfitline2 = [] for i in range(0, len(meanTheta_2)): polyfitline = cubicoef2[0]*np.power(meanTheta_2[i], 3) + cubicoef2[1]*np.power(meanTheta_2[i],2) + cubicoef2[2]*meanTheta_2[i] + cubicoef2[3] cubicfitline2.append(polyfitline) errcubicoef1_2 = np.sqrt(cubicovr2[0]) errcubicoef2_2 = np.sqrt(cubicovr2[5]) errcubicoef3_2 = np.sqrt(cubicovr2[10]) errcubicoef4_2 = np.sqrt(cubicovr2[15]) plt.plot(meanTheta_2, meanV_2) plt.plot(meanTheta_2, cubicfitline2) plt.title("Spreading law for Drop 2. Cubic fit. ") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_2, meanV_2, xerr = stdErrTheta_2, yerr= stdErrV_2, ecolor = "g") plt.show() CUBICredChiSqu_2 = reducedChiSquared(meanV_2, cubicfitline2, stdErrV_2, 4) print("The best fitted cubic is: U(θ) = (%5.2f ± %5.2f) θ^3 + (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) θ + (%5.2f ± %5.2f) " %(cubicoef2[0], errcubicoef1_2, cubicoef2[1], errcubicoef2_2, cubicoef2[2], errcubicoef3_2, cubicoef2[3], errcubicoef4_2)) print("This fit has reduced chi-squared: %5.2f" %CUBICredChiSqu_2) #De Gennes law, similar to method before (DeGcoef2, DeGcovr2) = np.polyfit( (np.power(meanTheta_2, 2)), meanV_2, 1 , cov = True) DeGcovr2 = np.array(DeGcovr2).ravel() DeGfitline2 = [] for i in range(0, len(meanTheta_2)): fitline = DeGcoef2[0]*pow(meanTheta_2[i], 2) + DeGcoef2[1] DeGfitline2.append(fitline) errDeGcoef1_2 = np.sqrt(DeGcovr2[0]) errDeGcoef2_2 = np.sqrt(DeGcovr2[3]) plt.plot(meanTheta_2, meanV_2) plt.plot(meanTheta_2, DeGfitline2) plt.title("Spreading law for Drop 2. De Gennes fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_2, meanV_2, xerr = stdErrTheta_2, yerr= stdErrV_2, ecolor = "g") plt.show() DeGredChiSqu_2 = reducedChiSquared(meanV_2, DeGfitline2, stdErrV_2, 2) print("The best De Gennes fit is: U(θ) = (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) " %(DeGcoef2[0], errDeGcoef1_2, DeGcoef2[1], errDeGcoef2_2 )) print("This fit has reduced chi-squared: %5.2f" %DeGredChiSqu_2) # Cox- Voinox law, similar to method before (coxcoef2, coxcovr2) = np.polyfit( (np.power(meanTheta_2, 3)), meanV_2, 1 , cov = True) coxcovr2 = np.array(coxcovr2).ravel() COXfitline2 = [] for i in range(0, len(meanTheta_2)): fitline = coxcoef2[0]*pow(meanTheta_2[i], 3) + coxcoef2[1] COXfitline2.append(fitline) errcoxcoef1_2 = np.sqrt(coxcovr2[0]) errcoxcoef2_2 = np.sqrt(coxcovr2[3]) plt.plot(meanTheta_2, meanV_2) plt.plot(meanTheta_2, COXfitline2) plt.title("Spreading law for Drop 2. Cox-Voinox fit.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(meanTheta_2, meanV_2, xerr = stdErrTheta_2, yerr= stdErrV_2, ecolor = "g") plt.show() COXredChiSqu_2 = reducedChiSquared(meanV_2, COXfitline2, stdErrV_2, 2) print("The best Cox-Voinox fit is: U(θ) = (%5.2f ± %5.2f) θ^3 + (%5.2f ± %5.2f) " %(coxcoef2[0], errcoxcoef1_2, coxcoef2[1], errcoxcoef2_2 )) print("This fit has reduced chi-squared: %5.2f" %COXredChiSqu_2) #interpolated fits, similar to method before X2 = np.linspace(meanTheta_2[0], meanTheta_2[-1], len(V1_2)) # evenly spaced array of points where I want to interpolate my data to interpolatedV1_2 = interpolate(theta1_2, X2, V1_2) interpolatedV2_2 = interpolate(theta2_2, X2, V2_2) meanIntV_2 = meanOf2Array(interpolatedV1_2, interpolatedV2_2) stdErrIntV_2 = stdevOf2Array(interpolatedV1_2, interpolatedV2_2) plt.plot(X2, meanIntV_2) plt.title("Spreading law for Drop 2 with interpolated data.") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(X2, meanIntV_2, yerr= stdErrIntV_2, ecolor = "g") plt.show() #De Gennes law interpolated data (intDeGcoef2, intDeGcovr2) = np.polyfit( (np.power(X2, 2)), meanIntV_2, 1 , cov = True) intDeGcovr2 = np.array(intDeGcovr2).ravel() intDeGfitline2 = [] for i in range(0, len(X2)): fitline = intDeGcoef2[0]*pow(X2[i], 2) + intDeGcoef2[1] intDeGfitline2.append(fitline) intErrDeGcoef1_2 = np.sqrt(intDeGcovr2[0]) intErrDeGcoef2_2 = np.sqrt(intDeGcovr2[3]) plt.plot(X2, meanIntV_2) plt.plot(X2, intDeGfitline2) plt.title("Spreading law for Drop 2. De Gennes fit. (Interpolated data)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(X2, meanIntV_2, yerr = stdErrIntV_2, ecolor = "r") plt.show() intDeGredChiSqu_2 = reducedChiSquared(meanIntV_2, intDeGfitline2, stdErrIntV_2, 2) print("The best De Gennes fit is: U(θ) = (%5.2f ± %5.2f) θ^2 + (%5.2f ± %5.2f) " %(intDeGcoef2[0], intErrDeGcoef1_2, intDeGcoef2[1], intErrDeGcoef2_2 )) print("This fit has reduced chi-squared: %5.2f" %intDeGredChiSqu_2) #Cox-voinox law interpolated data (intcoxcoef2, intcoxcovr2) = np.polyfit( (np.power(X2, 3)), meanIntV_2, 1 , cov = True) intcoxcovr2 = np.array(intcoxcovr2).ravel() intcoxfitline2 = [] for i in range(0, len(X2)): fitline = intcoxcoef2[0]*pow(X2[i], 3) + intcoxcoef2[1] intcoxfitline2.append(fitline) intErrcoxcoef1_2 = np.sqrt(intcoxcovr2[0]) intErrcoxcoef2_2 = np.sqrt(intcoxcovr2[3]) plt.plot(X2, meanIntV_2) plt.plot(X2, intcoxfitline2) plt.title("Spreading law for Drop 2. Cox-Voinox fit. (Interpolated data)") plt.xlabel("Contact angle, radians") plt.ylabel("Contact speed, μm/s") plt.errorbar(X2, meanIntV_2, yerr = stdErrIntV_2, ecolor = "r") plt.show() intcoxredChiSqu_2 = reducedChiSquared(meanIntV_2, intcoxfitline2, stdErrIntV_2, 2) print("The best Cox-Voinox fit is: U(θ) = (%5.2f ± %5.2f) θ^3 + (%5.2f ± %5.2f) " %(intcoxcoef2[0], intErrcoxcoef1_2, intcoxcoef2[1], intErrcoxcoef2_2 )) # U(θ) = (5430.96 ± 414.80) θ^3 - 34.13 ± 5.05 print("This fit has reduced chi-squared: %5.1f" %intcoxredChiSqu_2) #These results agree with that De Gennes law is a better fit for small contact angles compared to Cox_Voinox law, and vice versa for larger angles. #However, more measurements are necessary because there are not enough data sets for the error calculated by the standard deviation to be reliable #On surface 1, the velocity scale (U0) can be estimated to be 6397. ± 145.34 micrometres per second, this was the calculated coefficient of theta squared from the Cox-Voinox fit #On surface 2, the velocity scale (U0) can be estimated to be 5430. ± 414.80 micrometres per second.
05fe3505d7bf1f29518c190a6d4c328c9e918098
longkyle/blackjack
/test_blackjack.py
10,863
3.78125
4
#!/usr/bin/env python """ unittests for blackjack.py """ __author__ = "Kyle Long" __email__ = "long.kyle@gmail.com" __date__ = "08/26/2019" __copyright__ = "Copyright 2019, Kyle Long" __python_version__ = "3.7.4" import unittest import blackjack as bj from blackjack import Card, Deck, Hand, Dealer, Gambler class TestBlackjack(unittest.TestCase): def test_deal_and_reset_hands(self): """ Make sure deal() gives each player 2 cards and that it removes 2 cards from the deck for each player. Make sure reset_hands clears each players hands. """ # create 3 gamblers players = [] total_players = 4 for i in range(total_players - 1): gambler = bj.Gambler(f'Player {i+1}') gambler.money = 500 players.append(gambler) # create dealer dealer = bj.Dealer() players.append(dealer) # create, shuffle, & deal deck num_decks = 1 deck = bj.Deck(num_decks=num_decks) deck.create() deck.shuffle() bj.deal(players, deck, test=True) # check that each player got 2 cards for i in range(total_players): self.assertEqual(len(players[i].hands[0].cards), 2) # check that Deck.deal() removed 2*num_players cards from deck self.assertEqual(num_decks * 52 - total_players * 2, len(deck.cards)) # reset hands & check for accuracy bj.reset_hands(players) result = False for p in players: if p.hands: result = True self.assertFalse(result) def test_check_dealer_for_blackjack(self): """ Test that check_dealer_for_blackjack() function accurately recognizes when the dealer has been dealt a blackjack. """ # create dealer & hand dealer = bj.Dealer() hand = bj.Hand() dealer.hands.append(hand) # 10, ace check card1 = bj.Card('Hearts', '*', 10) card2 = bj.Card('Hearts', '*', 1) hand.cards.append(card1) hand.cards.append(card2) self.assertTrue(bj.check_dealer_for_blackjack([dealer])) # ace, 10 check hand.first_iter = True hand.blackjack = False dealer.hands[0].cards[0].value = 1 dealer.hands[0].cards[1].value = 10 self.assertTrue(bj.check_dealer_for_blackjack([dealer])) # ace, 5 check hand.first_iter = True hand.blackjack = False dealer.hands[0].cards[1].value = 5 self.assertFalse(bj.check_dealer_for_blackjack([dealer])) def test_flatten_list(self): """ Create nested list & flatten it using flatten_list. Check for accuracy. """ my_list = [1, [2, [3, 3], 2], 1, [2, 2], 1] result = bj.flatten_list(my_list) self.assertEqual(result, [1, 2, 3, 3, 2, 1, 2, 2, 1]) def test_determine_winners(self): """ Test that the dealer hits at the appropriate times and that winning hands are appropriated updated as such. """ # setup deck deck = Deck() deck.create() deck.shuffle() # setup gambler, dealer & hands dealer = Dealer() dealer_hand = Hand() dealer.hands.append(dealer_hand) gambler = Gambler("Test") gambler_hand = Hand() gambler.hands.append(gambler_hand) players = [gambler, dealer] # must hit a soft 17 (A, 6) gambler_hand.final_value = 20 dealer_hand.cards.append(Card('Hearts', 'Ace', 1)) dealer_hand.cards.append(Card('Hearts', 'Six', 6)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) > 2) # must hit on 16 or less (K, 6) self.reset_hand_attrs(dealer_hand) dealer_hand.cards.append(Card('Hearts', 'King', 10)) dealer_hand.cards.append(Card('Hearts', 'Six', 6)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) > 2) # check dealer bust (K, 6, J) dealer_hand.cards.pop() dealer_hand.cards.append(Card('Hearts', 'Jack', 10)) bj.determine_winners(players, deck) self.assertTrue(dealer_hand.busted) self.assertTrue(gambler_hand.win) # check dealer stands on 17 (K, 7) self.reset_hand_attrs(dealer_hand) dealer_hand.cards.append(Card('Hearts', 'King', 10)) dealer_hand.cards.append(Card('Hearts', 'Seven', 7)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) == 2) # gambler wins with 20 to dealer's 17 self.assertTrue(gambler_hand.win) # check dealer stands on soft 18 (Ace, 7) self.reset_hand_attrs(dealer_hand) dealer_hand.cards.append(Card('Hearts', 'Ace', 1)) dealer_hand.cards.append(Card('Hearts', 'Seven', 7)) bj.determine_winners(players, deck) self.assertTrue(len(dealer_hand.cards) == 2) def test_settle_up(self): """ Test that settle_up() function accurately updates each players .money attribute for various outcomes. """ # setup players dealer = Dealer() player = Gambler('Test') players = [player, dealer] # setup hands dealer_hand = Hand() dealer.hands.append(dealer_hand) hand = Hand() player.hands.append(hand) # check loss player.money = 500 hand.wager = 100 bj.settle_up(players) self.assertEqual(player.money, 400) # check win hand.win = True bj.settle_up(players) self.assertEqual(player.money, 500) # check push hand.win = False hand.push = True bj.settle_up(players) self.assertEqual(player.money, 500) # check insurance w/ dealer blackjack dealer_hand.blackjack = True hand.insurance = True bj.settle_up(players) self.assertEqual(player.money, 550) hand.insurance = False bj.settle_up(players) self.assertEqual(player.money, 550) # check insurance w/o dealer blackjack dealer_hand.blackjack = False hand.insurance = True bj.settle_up(players) self.assertEqual(player.money, 500) hand.insurance = False bj.settle_up(players) self.assertEqual(player.money, 500) # check Blackjack hand.push = False hand.blackjack = True bj.settle_up(players) self.assertEqual(player.money, 650) # check blackjack with fractional dollars hand.wager = 5 bj.settle_up(players) self.assertEqual(player.money, 657.5) # check dealer blackjack dealer_hand.blackjack = True hand.blackjack = False bj.settle_up(players) self.assertEqual(player.money, 652.5) def reset_hand_attrs(self, hand): """ Non-test method that resets a hand to it's original state. Used in other test methods for cleanup in between similar assert calls. args: hand (class): Hand() object """ hand.cards = [] hand.wager = None hand.blackjack = False hand.win = False hand.push = False hand.double_down = False hand.split = [] hand.busted = False hand.final_value = None hand.first_iter = True class TestCard(unittest.TestCase): def test_get_card_str(self): """ Test that get_card_str() returns the appropriate str representation of a card. Also test that it works with hidden cards. """ card = Card('Hearts', 'King', 10) self.assertEqual(card.get_card_str(), 'King of Hearts') card.hidden = True self.assertEqual(card.get_card_str(), '**') class TestDeck(unittest.TestCase): def test_deck_size(self): """ Make sure each deck is exactly 52 cards Check for each shoe size. """ for i in range(bj.MIN_DECKS, bj.MAX_DECKS + 1): deck = Deck(num_decks=i) deck.create() self.assertEqual(len(deck.cards), 52 * i) def test_shuffle(self): """ Make sure Deck.shuffle is randomized """ deck1 = Deck(num_decks=1) deck2 = Deck(num_decks=1) deck1.shuffle() deck2.shuffle() self.assertNotEqual(deck1, deck2) class TestHand(unittest.TestCase): def test_deal_card(self): """ Test that dealing a card removes 1 card from the deck and adds 1 card to the hand. """ self.deck = Deck(num_decks=1) self.deck.create() self.deck.shuffle() self.hand = Hand() self.hand.deal_card(self.deck) self.assertEqual(len(self.deck.cards), 51) self.assertEqual(len(self.hand.cards), 1) def test_check_busted(self): """ Check to see if a hand is a bust (> 21) or not. """ # hand is busted self.hand = Hand() self.hand.cards.append(Card('Hearts', 'King', 10)) self.hand.cards.append(Card('Hearts', 'Three', 3)) self.hand.cards.append(Card('Hearts', 'Jack', 10)) self.hand.check_busted() self.assertTrue(self.hand.busted) # hand is not busted self.hand = Hand() self.hand.cards.append(Card('Hearts', 'King', 10)) self.hand.cards.append(Card('Hearts', 'Three', 3)) self.hand.cards.append(Card('Hearts', 'Six', 6)) self.hand.check_busted() self.assertFalse(self.hand.busted) def test_get_hand_value(self): """ Make sure get_hand_value() returns accurate hand values. """ # test hand values with Aces self.hand = Hand() self.hand.cards.append(Card('Hearts', 'Ace', 1)) self.hand.cards.append(Card('Spades', 'Ace', 1)) self.hand.cards.append(Card('Hearts', 'Six', 6)) hand_values = self.hand.get_hand_value() self.assertEqual(hand_values, [8, 18]) # test hand values with hidden card (Dealer) self.hand.cards[2].hidden = True hand_values = self.hand.get_hand_value() self.assertEqual(hand_values, [2, 12]) # test hand values with hidden card included (Dealer) hand_values = self.hand.get_hand_value(include_hidden=True) self.assertEqual(hand_values, [8, 18]) class TestGambler(unittest.TestCase): def test_buy_in(self): """ Make sure buy_in() adds money to the .money attribute. """ self.gambler = Gambler("Test") self.gambler.buy_in(test=True) self.assertEqual(self.gambler.money, 500) if __name__ == '__main__': unittest.main()
a8b4639a8a2de162236ba3ced3ce9229a2d1579d
Nadjamac/Mod1_BlueEdtech
/Aula11_Dicionários/Aula11_Dicionarios_Conteúdo.py
1,012
4.15625
4
#Criando uma lista de tuplas -> estrutura de dados que associa um elemento a outro # lista = [("Ana" , "123-456") , ("Bruno" , "321-654") , ("Cris" , "213 - 546") , ("Daniel" , "231 - 564") , ("Elen" , "111-222")] #Sintaxe de um dicionário # dicionario = {"Ana" : "123-456"} #Criando um dicionário # lista_dicionario = dict(lista) # print(lista_dicionario) # Acessando um valor dentro de um dicionário #O valor é acessado pela chave do dicionário # print(lista_dicionario["Ana"]) # print(lista_dicionario.get("Ana")) # nome = input("Digite um nome: ") # print(lista_dicionario.get(nome , "Valor não encontrado!") atores_vingadores = {"Chris Evans" : "Capitão América" , "MArk Ruffalo" : "Hulk" , "Tom Hiddeltston" : "Loki" , "Chris Hemworth" : "Thor" , "Robert Downey Jr" : "Homem de Ferro" , "Scarlett Johansson" : "Viúva Negra"} ator = input("Digite o nome do ator: ") print(atores_vingadores.get(ator , "O nome não existe!")) #interagindo com chave e valor for chave , valor in atores_vingadores.items(): print(f"O valor da chave {chave} é: {valor}")
2234f840e1255a3344d3d614ce17f7f7866ed5ab
Nadjamac/Mod1_BlueEdtech
/Aula12_Dicionários_CodeLAB/Exercicio 4.py
663
3.75
4
import random import operator import time print("JOGO DOS DADOS: ") tuplas = () lista = [] for n in range(4): jogador = input("Digite seu nome: ") print("DIGITE ENTER PARA SORTEAR O DADO") input() numero = random.randint(1,10) tuplas = (jogador , numero) lista.append(tuplas) lista_dict = dict(lista) lista_ordem = sorted(lista_dict.items(), key=operator.itemgetter(1)) vencedor = max(lista_dict.items(), key=operator.itemgetter(1))[0] print("O vencedor é: ") time.sleep(1.5) print(vencedor) time.sleep(0.5) print("\nRESULTADO FINAL: \n") for nome , valor in lista_dict.items(): print(f"O valor do dado para {nome} foi: {valor}")
3bd5f1f83a5af71b6c828a46a514980f003cbefb
Nadjamac/Mod1_BlueEdtech
/Aula06_Funções/Exercicio 5.py
401
3.75
4
def IMC(peso, altura): return peso / (altura ** 2) pes = input("Digite seu peso (em kg): ").replace(",", ".") altur = input("Digite sua altura (em metros): ").replace(",", ".") peso = float(pes) altura = float(altur) imc = IMC(peso , altura) #O termo ":.2f" determina o número de casas decimais a ser printado. Ideal para casos envolvendo valores monetários!! print(f"Seu IMC é {imc:.2f}.")
8705e55c581ac9450487d731fe71b6e473f4ce6f
Nadjamac/Mod1_BlueEdtech
/Aula13_Dicionarios/Exercicio 1.py
556
3.765625
4
aniversario = dict() while True: nome = input("Digite o nome da celebridade ou 0 para sair: ") if nome == "0": break data_aniversario = input("Digite a data de nascimento da celebridade (dd/mm/yyy): ") aniversario [nome] = data_aniversario print("Seja bem-vindo ao nosso calendário. Sabemos a data de nascimento das seguintes celebridades: ") for item in aniversario: print(item) print() nome = input("Digite um nome de uma celebridade para saber sua data de nascimento: ") print(aniversario.get(nome , "Nome não encontrado!"))
a39314b3433f54bfb937e3cbc297bc65b5a9f06a
Nadjamac/Mod1_BlueEdtech
/Aula07_Funcoes/Projeto.py
1,551
3.984375
4
#Função Gasto com hospedagem def custo_hotel(noites): custoh = 140 * noites return custoh #Função Gasto com avião def custo_aviao(cidade): custoav = 0 if cidade == "São Paulo": custoav = 312 elif cidade == "Porto Alegre": custoav = 447 elif cidade == "Recife": custoav = 831 elif cidade == "Manaus": custoav = 986 else: custoav = "Não temos opções para esse destino" return custoav #Função Aluguel com Carro def custo_carro(dias): custocar = dias * 40 if dias >= 7: custocar = (dias * 40) - 50 elif 3 <= dias < 7: custocar = (dias * 40) - 20 return custocar #Função de custo total def custo_total(cidade , dias): #Se o usuário incluir uma cidade fora do escopo da questão não como calcular o valor do custo total if cidade == "São Paulo" or cidade == "Porto Alegre" or cidade == "Recife" or cidade == "Manaus": custotot = custo_hotel(dias) + custo_aviao (cidade) + custo_carro(dias) else: custotot = "Não temos opções para esse destino" return custotot cidade = input("Escolha seu destino: \n") dias = int(input("Digite a quantidade de dias da sua viagem: \n")) #Dependendo do resultado da função custo_total(), o programa printa o preço da viagem ou que o destino é inválido if custo_total(cidade, dias) == "Não temos opções para esse destino": print(custo_total(cidade , dias)) else: print("O custo total da viagem é:", custo_total(cidade , dias), "reais.")
c2b9eb159e9a7b6ab65f12c9cde16bc0c7a089c4
Nadjamac/Mod1_BlueEdtech
/Aula06_Funções/Desafio.py
2,564
3.96875
4
def data_escrita(data): #Dividindo a string para analisar mês, dia e ano dia = int(data[:2]) mes = data[3:5] ano = int(data[6:]) #Caso a pessoa coloque um mês acima de 13 if mes > "12" or mes == "00": print("Data Inválida!") #Teste para os dias dos meses. Alguns tem que ter até 31 dias, outros até 30 if mes == "01": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Janeiro de {ano}.") elif mes == "03": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Março de {ano}.") elif mes == "05": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Maio de {ano}.") elif mes == "07": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Julho de {ano}.") elif mes == "08": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Agosto de {ano}.") elif mes == "10": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Dezembro de {ano}.") elif mes == "12": if dia > 31: print ("Data Inválida!") else: print (f"{dia} de Janeiro de {ano}.") elif mes == "04": if dia > 30: print("Data Inválida!") else: print (f"{dia} de Abril de {ano}.") elif mes == "06": if dia > 30: print("Data Inválida!") else: print (f"{dia} de Junho de {ano}.") elif mes == "09": if dia > 30: print("Data Inválida!") else: print (f"{dia} de Setembro de {ano}.") elif mes == "11": if dia > 30: print("Data Inválida!") else: print (f"{dia} de Novembro de {ano}.") #O mês de Fevereiro é especial pq depende se o ano é bissexto ou não. #O ano é bissexto quando é divisivel por 4 ou 400 mas não divisivel por 100 elif mes == "02": if (ano % 4 == 0 or ano % 100 != 0) or ano % 400 == 0: if dia > 29: print("Data Inválida!") else: print (f"{dia} de Fevereiro de {ano}.") else: if dia > 28: print("Data Inválida!") else: print (f"{dia} de Fevereiro de {ano}.") data = input("Digite uma data (Formato DD/MM/AAA): ") data_escrita(data)
91f48e903b5e760c065457d3b12f1ef4e50438e0
hamzzy/pymeet_abk_datastructure
/trees.py
303
3.859375
4
class Tree: def __init__(self,root,left=None,right=None): self.root=root self.left=left self.right=right def __str__(self): return (str(self.root)+", left child :"+str(self.left)+ ", right child :" +str(self.right)) tree=Tree(5,Tree(3,1,4),Tree(8,7,9)) print(tree)
4c8924ce678b8ee4d0ab61fb3f8a07003723bd41
karinabk/CSCI235_Programming_Languages
/python/Python3/KarinaBekbayeva.py
798
3.625
4
from matrix import * from vector import * from rational import * def tests(): m1 = Matrix(Rational(1, 2), Rational(1, 3), Rational(-2, 7), Rational(2, 8)) m2 = Matrix(Rational(-1, 3), Rational(2, 7), Rational(2, 5), Rational(-1, 7)) m3 = Matrix(1, 2, 3, 4) v = Vector(1, 2) print("m1xm2:") print(m1@m2) print("inverse of m1:") print(m1.inverse()) print("(m 1 × m 2 ) × m 3 - m 1 × (m 2 × m 3 )") print((m1@m2)@m3 - (m1@(m2@m3))) print("m 1 ×(m 2 +m 3 ) - m 1 ×m 2 +m 1 ×m 3:") print(m1@(m2+m3) - (m1 @ m2 + m1@m3)) print("m 1 (m 2 (v)) - (m 1 × m 2 )(v)") print(m1(m2(v)) - (m1@m2)(v)) print("det(m 1 ).det(m 2 ) - det(m 1 × m 2 )") print(m1.determinant()*m2.determinant() - (m1@m2).determinant()) print("m1 × inv(m1) - I:") print(m1@m1.inverse() - Matrix(1, 0, 0, 1))
90b06d21bfe6f67f9dc9f56dd980ce5c12016329
softwarelikeyou/CS303E
/gridtest.py
2,520
3.609375
4
#function that finds product def max_prod (a): max_p = a[0] * a[1] for i in range (1, len(a) - 1): prod = a[i] * a[i + 1] if (prod > max_p): max_p = prod return max_p def main(): #open file for reading file = 'testcase1.txt' ##file = 'grid.txt' file = 'testcase2.txt' file = 'testcase3.txt' in_file = open(file, "r") #read the dimension of the grid dim = in_file.readline() dim = dim.strip() dim = int(dim) #create an empty grid and populate it grid = [] for i in range (dim): row = in_file.readline() row = row.strip() row = row.split() for j in range (dim): row[j] = int(row[j]) grid.append(row) in_file.close() maximum = 0; # find horizontal max for row in grid: for i in range (0, len(row) - 3): product = 1 for j in range (i, i+ 4): product *= int(row[j]) if product > maximum: maximum = product # find vertical max, but first rotate grid 90 degrees to the left rotated = [] for j in range(dim): row = [] for i in range(dim): row.append(int(grid[i][j])) rotated.append(row) for row in rotated: for i in range (0, len(row) - 3): product = 1 for j in range (i, i+ 4): product *= int(row[j]) if product > maximum: maximum = product # find diagonal max left to right i = 0 while i < dim - 3: for k in range(dim-3 - i): product = 1 for j in range(k, k+4): product *= grid[j+i][j] if product > maximum: maximum = product i += 1 i = 0 while i < dim - 3: for k in range(dim-3 - i): product = 1 for j in range(k, k+4): product *= grid[j][j+i] if product > maximum: maximum = product i += 1 # find diagonal max right to left i = 0 while i < dim - 3: for k in range(dim-3 - i): product = 1 for j in range(k, k+4): product *= grid[j+i][dim-1-j] if product > maximum: maximum = product i += 1 i = 0 while i < dim - 3: for k in range(dim-3-i): product = 1 for j in range(k, k+4): product *= grid[j][dim-1-j-i] if product > maximum: maximum = product i += 1 print('The greatest product is', maximum, end='.') main()
5cb6d2c013ba4417f7d1cd16bf4eb0155c25b9d1
softwarelikeyou/CS303E
/dad_dna.py
2,148
3.9375
4
# File: DNA.py # Description: Print the longest sequence of nucleotides for given the DNA sequence pairs # Student Name: Courntey C. Thomas # Student UT EID: cct685 # Course Name: CS 303E # Unique Number: 1 # Date Created: 3/25/2016 # Date Last Modified: 3/26/2016 import os.path import sys def substr (st): pieces = [] wnd = len (st) while (wnd > 0): start_idx = 0 while ((start_idx + wnd) <= len(st)): piece = st[start_idx : start_idx + wnd] pieces.append(piece) start_idx += 1 wnd = wnd - 1 return pieces def main(): if os.path.exists('DNA.txt') == False: print('Please ensure DNA.txt is located in the same directory as this program') sys.exit() file = open('DNA.txt', 'r') lines = [line.strip() for line in file] file.close() numberOfPairs = int(lines.pop(0)) print('Longest Common Sequences', end='\n\n') for index in range(0,numberOfPairs): sequence1 = lines.pop(0).upper() sequence2 = lines.pop(0).upper() if len(sequence1) > 80 or len(sequence2) > 80: print('Sequence nucleotide count cannot be greater than 80') pieces1 = substr(sequence1) pieces2 = substr(sequence2) matches = [] matchesLength = 0 matchesCount = 1 for piece1 in pieces1: for piece2 in pieces2: if piece1 == piece2: if len(piece1) >= matchesLength: matches.append(piece1) matchesLength = len(piece1) description = 'Pair ' + str(index+1) + ':' if len(matches) == 0: print(description, 'No Common Sequence Found') for match in matches: if matchesCount == 1: matchesCount += 1 print(description, match) else: print(match.rjust(12, ' ')) print(' ', end='\n') main() ##Longest Common Sequences ## ##Pair 1: TCG ## ##Pair 2: TGAT ## GGAC ## ##Pair 3: No Common Sequence Found ##3 ##GAAGGTCGAA ##CCTCGGGA ##ATGATGGAC ##GTGATAAGGACCC ##AAATTT ##GGGCCC
e833a47aaeee846b2b39d5ca1629fd6a5a79a76f
softwarelikeyou/CS303E
/dad_creditcard.py
1,796
4.0625
4
## This function checks if a credit card number is valid def is_valid(cc_num): parts = list(str(cc_num)) parts.reverse() odds = list() for i in range(len(parts)-1,-1,-1): if isEven(i) == False: odds.append(sumDigits(int(parts[i])*2)) evens = list() for i in range(len(parts)-1,-1,-1): if isEven(i) == True: evens.append(int(parts[i])) total = 0 for odd in odds: total += int(odd) for even in evens: total += int(even) if total % 10 == 0: return True else: return False ## This function returns the type of credit card def cc_type(cc_num): if str(cc_num).startswith('34') or str(cc_num).startswith('37'): return 'American Express' if str(cc_num).startswith('6001') or str(cc_num).startswith('644') or str(cc_num).startswith('65'): return 'Discover' if str(cc_num).startswith('50') or str(cc_num).startswith('51') or str(cc_num).startswith('52') or str(cc_num).startswith('53') or str(cc_num).startswith('54') or str(cc_num).startswith('55'): return 'MasterCard' if str(cc_num).startswith('4'): return 'Visa' def isEven(number): return number % 2 == 0 def sumDigits(number): result = 0 parts = list(str(number)) for part in parts: result += int(part) return result def main(): cc = int(input("Enter 15 or 16-digit credit card number: ")) if len(str(cc)) < 15: print('\nNot a 15 or 16-digit number') return if len(str(cc)) > 16: print('\nNot a 15 or 16-digit number') return if is_valid(cc) == True: print('\nValid', cc_type(cc), 'credit card number') else: print('\nInvalid credit card number') main()
795b824edc5cc5d8c0b265bba8a3a2f4d7b73c82
OWCramer/Pokemon-Text-Edition-WIP-
/main.py
11,403
3.515625
4
#Gets Program and Screens Ready import screens import random import os import time from termcolor import colored, cprint import sprites import scenarios #Defines how to clear def clear(): os.system('cls' if os.name=='nt' else 'clear') #defines a loading bar def fake_load(): load_bar = "=" x = 20 for i in range(21): end_cap = " "*x print ("Loading...") print ("[" + load_bar + end_cap + ']') x = x - 1 load_bar = load_bar + "=" time.sleep(.1) clear() #Main Title Screen print ("Welcome to Pokemon Text Edition (Now in Python!)") screens.screen_title() print ("") input('To begin your journey press enter') clear() fake_load() '''Professor Dialogue''' #Professor Startup print ("Hello,\n Weclome to the Unova Region. I'm professor Aurea Juniper, and I heard you were interested in the world of pokemon!") while True: print("Is that true?(Yes/No)") ready_choice = input(': ') ready_choice = ready_choice.lower() #Exit Screen if ready_choice == 'no': clear() print ('Fine No Game!') screens.screen_error() quit() elif ready_choice == "yes": break else: print("I need a Yes/No answer") scenarios.error() continue #Aurea Juniper Dialougue asks if user wants Pokemon def do_you_want(): while True: pokemon_own = input(': ') pokemon_own = pokemon_own.lower() if pokemon_own == 'no': clear() print ("Well maybe I'll ask another time.") screens.screen_error() quit() elif pokemon_own == 'yes': print ('Before we get you a pokemon,') break else: print ("I need a Yes or No answer!") scenarios.error() print ("Did you want a Pokemon?") print ("That's great to hear. I'm excited to help you begin your adventure.") while True: print ("Have you ever seen a Pokemon (Yes/No)") seen_pokemon = input(': ') seen_pokemon = seen_pokemon.lower() if seen_pokemon == "yes": print ("Thats wonderful, I noticed that you don't have a pokemon of youre own. Would you like one?(Yes/No)") do_you_want() break elif seen_pokemon == "no": print ("Oh! Well then how would you like a pokemon of your own?(Yes/No)") do_you_want() break else: print ("I need a Yes or No answer!") scenarios.error() continue #gets users Name while True: print ('what is your name?') name = str(input(': ')) print ("So your name is " + name + " ? (Yes/No)") confirm = input(': ') confirm = confirm.lower() if confirm == 'no': continue elif confirm == 'yes': break else: print ("I need a Yes or No answer!") scenarios.error() clear() #continue dialogue print ('Nice to meet you ' + name + "!") #chosing pokemon print ("Now that I know your name you can choose a pokemon!") pokemon_list = [] pokemon_list_rival = [] pokemon_list_pc = [] while True: print ('Which pokemon would you like to choose?(Snivy/Oshawott/Tepig)') pokemon_choice = input(": ") pokemon_choice = pokemon_choice.lower() if pokemon_choice == 'snivy': are_you_sure = input('Are you sure you want Snivy?(Yes/No): ') are_you_sure=are_you_sure.lower() if are_you_sure == 'yes': cprint('You chose Snivy', "green") pokemon_list.append("Snivy") pokemon_list_rival.append("Oshawott") time.sleep(1.5) input("Press Enter to continue") clear() break elif are_you_sure == 'no': continue else: print ("I need a Yes or No Answer") continue if pokemon_choice == 'oshawott': are_you_sure = input('Are you sure you want Oshawott?(Yes/No): ') are_you_sure=are_you_sure.lower() if are_you_sure == 'yes': cprint('You chose Oshawott', "blue") pokemon_list.append("Oshawott") pokemon_list_rival.append("Tepig") time.sleep(1.5) input("Press Enter to continue") clear() break elif are_you_sure == 'no': continue else: print ("I need a Yes or No Answer") continue if pokemon_choice == 'tepig': are_you_sure = input('Are you sure you want Tepig?(Yes/No): ') are_you_sure=are_you_sure.lower() if are_you_sure == 'yes': cprint('You chose Tepig', "red") pokemon_list.append("Tepig") pokemon_list_rival.append("Snivy") time.sleep(1.5) input("Press Enter to continue") clear() break elif are_you_sure == 'no': continue else: print ("I need a Yes or No Answer") continue else: print ("Please Check the Spelling of the PKMN name you typed!") scenarios.error() #Meeting rival sprites.rival() rival_name = ("Silver") print ("Hey im your rival Silver!\nI got my first Pokemon today to! Lets Battle!") time.sleep(1.5) input("Press enter to continue.") clear() fake_load() #Starts fight def rival_fight(): TF = True class Rival_pokemon_B1(): global pokemon_list_rival def __init__(self, BaseHP = 20): self.name = pokemon_list_rival[0] self.Lv = 5 self.move_one = "Scratch" self.move_one_attack = 7 self.move_two = "Growl" self.move_two_attack = 0 self.BaseHP = BaseHP MoveCC = 100 MoveMC = MoveCC * 2 self.HP = 50 #(C)haracter (P)okemon (S)lot class CPS1(): def __init__(self, BaseHP = 50): self.BaseHP = BaseHP self.Lv = 5 self.name = pokemon_list[0] self.HP = 0.02 * self.Lv * self.BaseHP * 10 MoveCC = 20 MoveMC = MoveCC * 2 EPNeeded = 10 self.EP = 0.0 self.move_one = "Tackle" self.move_one_attack = 10 self.move_one_CC = 40 self.move_two = "Growl" self.move_two_attack = 0 self.move_two_CC = 40 self.move_three = "Empty" self.move_three_attack = 0 self.move_three_CC = 40 self.move_four = "Empty" self.move_four_attack = 0 self.move_four_CC = 40 self.EP = 0.0 self.EPNeeded = 10 RB = Rival_pokemon_B1() CB = CPS1() misschance = random.randint(1,80) if misschance == 26: misschanceBool = True else: misschanceBool = False critchance = random.randint(1,40) if critchance == 7: critchanceBool = True else: critchanceBool = False def Player_fight_prompt(): global TF moveSelectOption = input(": ").capitalize() clear() print() if moveSelectOption == CB.move_one: TF = False print(CB.name + " used " + CB.move_one) if misschanceBool == True: print ("Attack Missed") else: if critchanceBool == True: CB.move_one_attack = CB.move_one_attack * 2 RB.HP = RB.HP - CB.move_one_attack CB.move_one_attack = CB.move_one_attack / 2 print("Critical hit") else: RB.HP = RB.HP - CB.move_one_attack print("Attack hit") elif moveSelectOption == CB.move_two: TF = False print(CB.name + " used " + CB.move_two) if misschanceBool == True: print ("Attack Missed") else: if critchanceBool == True: CB.move_two_attack = CB.move_two_attack * 2 RB.HP = RB.HP - CB.move_two_attack CB.move_two_attack = CB.move_two_attack / 2 print("Critical hit") else: RB.HP = RB.HP - CB.move_two_attack print("Attack hit") elif moveSelectOption == CB.move_three: TF = False print(CB.name + " used " + CB.move_three) if misschanceBool == True: print ("Attack Missed") else: if critchanceBool == True: CB.move_three_attack = CB.move_three_attack * 2 RB.HP = RB.HP - CB.move_three_attack CB.move_three_attack = CB.move_three_attack / 2 print("Critical hit") else: RB.HP = RB.HP - CB.move_three_attack print("Attack hit") elif moveSelectOption == CB.move_four: TF = False print(CB.name + " used " + CB.move_four) if misschanceBool == True: print ("Attack Missed") else: if critchanceBool == True: CB.move_four_attack = CB.move_four_attack * 2 RB.HP = RB.HP - CB.move_four_attack CB.move_four_attack = CB.move_four else: RB.HP = RB.HP - CB.move_four_attack print("Attack hit") elif moveSelectOption == "Back": attack_while_loop() else: print ("Thats not an option! (Type Back)") return Player_fight_prompt() print (name + ": Go, " + CB.name + ".") print ("Rival: Sent out, " + RB.name + ".") print () qwert = input("Press Enter To Continue...") clear() def attack_while_loop(): while(RB.HP > 0): print () print ("Rival: " + name + ":") print (RB.name + " Lv." + str(RB.Lv) + " " + CB.name + " Lv." + str(CB.Lv)) print ("HP: " + str(RB.HP) + " " + "HP: " + str(round(CB.HP))) print () print ("[Fight] [Bag] [Run] [Pokemon]") print ("-----------------------------") OptionUI = input(": ").lower() if CB.move_two == "Empty": CB.move_two = " " if CB.move_three == "Empty": CB.move_three = " " if CB.move_four == "Empty": CB.move_four = " " if OptionUI == "fight": print(CB.move_one + " " + CB.move_two) print(CB.move_three + " " + CB.move_four) print(" Back") if CB.move_two == " ": CB.move_two = "Empty" if CB.move_three == " ": CB.move_three = "Empty" if CB.move_four == " ": CB.move_four = "Empty" Player_fight_prompt() print() Enemy_attack_option = random.randint(1,3) if Enemy_attack_option < 3: print ("Rival's " + RB.name + " used " + RB.move_one) CB.HP = CB.HP - RB.move_one_attack print ("Attack hit") else: print("Rival's " + RB.name + " used " + RB.move_two) CB.HP = CB.HP - RB.move_two_attack print ("Attack hit") if OptionUI == "bag": print() print("You dont have anything in there yet!") attack_while_loop() if OptionUI == "run": print() print("You cant run from trainer Battles!") attack_while_loop() if OptionUI == "pokemon": print() print("You only have one pokemon!") attack_while_loop() attack_while_loop() print("You gained 17 XP for defeating " + RB.name) CB.EP = CB.EP + 17 if CB.EP >= CB.EPNeeded: CB.Lv = CB.Lv + 1 CB.EP = CB.EP - CB.EPNeeded CB.EPNeeded = CB.EPNeeded * .5 print(CB.name + " leveled up to Lv." + str(CB.Lv) + "!") print("You need " + CB.EP - CB.EPNeeded + "XP to level up again!") rival_fight() #ends fight #Continues Story clear() print ("Thanks for playing this is a WIP")
036e6228ddb9c7728ec2464a86e0dea8b5165799
biofoolgreen/python_data_structure
/recursion/int2str.py
1,167
3.765625
4
''' @Description: 递归-整数转换为任一进制的字符串 @Version: @Author: biofool2@gmail.com @Date: 2019-01-03 11:53:27 @LastEditTime: 2019-01-03 17:29:19 @LastEditors: Please set LastEditors ''' class Stack(object): def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items) def int2str(n, base=10): cvt_str = "0123456789ABCDEF" if n < base: return cvt_str[n] else: return int2str(n//base, base) + cvt_str[n%base] # 使用栈帧实现递归 def int2str_stack(n, base=10): cvt_str = "0123456789ABCDEF" rstack = Stack() while n > 0: if n < base: rstack.push(cvt_str[n]) else: rstack.push(cvt_str[n%base]) n = n // base res = "" while not rstack.isEmpty(): res += str(rstack.pop()) return res if __name__ == "__main__": print(int2str(1453, 2)) print(int2str_stack(1453, 2))
b255edf560d1fff3759e8e21091a86ab1169f4f9
TristanGRZ77/summer2018
/20180828/calculatrice2.py
3,438
3.546875
4
from Tkinter import* import Tkinter as Tk from math import * # t correspond au chiffre saisi # y correspond a l'operateur utilise # n correspond au nombre de valeurs que compose un facteur t, y, n = 0, 0, 1 # fonction qui permet l'affichage de facteurs a plusieurs chiffres def nombre(x): global t, n t = t * 10 + x z.set(str(t)) # fonctions liees aux boutons chiffres qui saisissent les valeurs desirees def x(_nombre): nombre(_nombre) #def x0(): # nombre(0.) #def x1(): # nombre(1.) #def x2(): # nombre(2.) #def x3(): # nombre(3.) #def x4(): # nombre(4.) #def x5(): # nombre(5.) #def x6(): # nombre(6.) #def x7(): # nombre(7.) #def x8(): # nombre(8.) #def x9(): # nombre(9.) # t1 correspond au deuxieme facteur de l'operation # fonctions d'operation def aplus(): global y, t1, t, n y, t1, n = '+', t, 1 t = 0 def amoins(): global y, t1, t, n y, t1, n = '-', t, 1 t = 0 def afois(): global y, t1, t, n y, t1, n = '*', t, 1 t = 0 def adiv(): global y, t1, t, n y, t1, n = '/', t, 1 t = 0 def aegal(): global t, t1, n if y == '+': z.set(str((t1 + t))) t = t1 + t elif y == '-': z.set(str((t1 - t))) t = t1 - t elif y == '*': z.set(str((t1 * t))) t = t1 * t elif y == '/': if t == 0: z.set(str("Erreur, impossible")) else: z.set(str((t1 / t))) t = t1 / t t1, n = 0, 1 root.after(1500, clear) def clear(): global t, t1, n, z, y t, t1, n, y = 0, 0, 0, 0 z.set(str('0')) root = Tk.Tk() btn1 = Button(root, text = "1", command = x(1)) btn1.grid(column = 0, row = 0) btn2 = Button(root, text = "2", command = x2) btn2.grid(column = 1, row = 0) btn3 = Button(root, text = "3", command = x3) btn3.grid(column = 2, row = 0) btn4 = Button(root, text = "4", command = x4) btn4.grid(column = 0, row = 1) btn5 = Button(root, text = "5", command = x5) btn5.grid(column = 1, row = 1) btn6 = Button(root, text = "6", command = x6) btn6.grid(column = 2, row = 1) btn7 = Button(root, text = "7", command = x7) btn7.grid(column = 0, row = 2) btn8 = Button(root, text = "8", command = x8) btn8.grid(column = 1, row = 2) btn9 = Button(root, text = "9", command = x9) btn9.grid(column = 2, row = 2) btnc = Button(root, text = "C", command = clear) btnc.grid(column = 0, row = 3) btn0 = Button(root, text = "0", command = x0) btn0.grid(column = 1, row = 3) btnr = Button(root, text = "=", command = aegal) btnr.grid(column = 2, row = 3) btna = Button(root, text = "+", command = aplus) btna.grid(column = 3, row = 0) btns = Button(root, text = "-", command = amoins) btns.grid(column = 3, row = 1) btnm = Button(root, text = "*", command = afois) btnm.grid(column = 3, row = 2) btnd = Button(root, text = "/", command = adiv) btnd.grid(column = 3, row = 3) z = StringVar() entree = Entry(root, textvariable = z) entree.grid(column = 4, row = 3) z.set("0.") btnquit = Button(root, text = 'Quitter', command = root.destroy) btnquit.grid(column = 4, row = 0) root.mainloop()
2f49772d571ad2ead3fc16d68b281176e58c036d
betsybaileyy/MadLibs
/main.py
2,186
4
4
def madlib_go(): print("Welcome to MadLibs") print("Please fill in the prompts to complete the spooky Halloween story!") # asking user input emphasis_adjective = user_input("Enter an emphasis adjective: ") article_of_clothing = user_input("Enter an article of clothing: ") verb_one = user_input("Enter a verb: ") fictional_city = user_input("Enter a fictional city: ") adjective_one = user_input("Enter an adjective: ") plural_proper_noun = user_input("Enter a plural proper noun: ") noun_one = user_input("Enter a verb: ") noun_two = user_input("Enter a noun: ") food = user_input("Enter a food: ") beverage = user_input("Enter a beverage: ") adjective_two = user_input("Enter an adjective: ") noun_three = user_input("Enter a noun: ") verb_two = user_input("Enter a verb: ") adjective_three = user_input("Enter an adjective: ") print("Happy Halloween! It’s time to get " + emphasis_adjective + " spooky. Get your " + article_of_clothing + " on and prepare to " + verb_one + " around the town. Every year on October 31st, " + fictional_city + " hosts the " + adjective_one + " party and " + plural_proper_noun + " never forget to come. It is important to greet everyone by saying ‘ " + noun_one + " or " + noun_two + " .’ We will eat lots of " + food + " and drink " + beverage + " . Bring your finest " + adjective_two + " " + noun_three + " and don’t forget to " + verb_two + " because this is the most " + adjective_three + " day of the year.") def user_input(prompt): user_input = input(prompt) return user_input madlib_go() # # # print(""" Happy Halloween! It’s time to get # (emphasis adjective) spooky. Get your (article of clothing) # on and prepare to (verb) around the town. Every year on October 31st, # (fictional city) hosts the (adjective) party and (plural proper noun) never forget to come. # It is important to greet everyone by saying “ (noun) or (noun) “. We will eat lots of (food) and drink (beverage). # Bring your finest (adjective) (noun) and don’t forget to (verb) because this is the most (adjective) day of the year.""")
37e4df3125d423e99c519dcb31867178fb0a6823
PyconUK/dojo18
/team7/color_changes.py
1,445
3.609375
4
""" pgzero - training ground for pygame """ WIDTH = 300 HEIGHT = 300 # SUMMER = () def get_closer_color(src_color, target_color): """ e.g. is src is (128, 0, 0) and target is (64, 64, 0), will output (127, 1, 0) movin all rgb components closer to target """ result_color = list(src_color) for i in range(3): if result_color[i] == target_color[i]: continue elif result_color[i] > target_color[i]: result_color[i] -= 1 else: result_color[i] += 1 return tuple(result_color) SPRING = (0, 0, 255) SUMMER = (255, 0, 0) AUTUMN = (0, 255, 0) WINTER = (255, 255, 255) season_colors = [ SPRING, SUMMER, AUTUMN, WINTER ] ci = 0 current_color = season_colors[0] target_color = season_colors[1] def draw(): def move_colors(): def move_it(): global ci global current_color global target_color if current_color == target_color: ci = (ci + 1) % len(season_colors) print('ci = {}'.format(ci)) current_color = season_colors[ci] target_color = season_colors[(ci + 1) % len(season_colors)] current_color = get_closer_color(current_color, target_color) print(current_color, target_color) screen.fill(current_color) clock.schedule_unique(move_it, 0.1) move_it() move_colors()
3eee5c8b446e281d0ed30646a57fa57a27a42057
badlovv/avito-analytics-academy
/Python/HW2/work.py
4,508
3.5
4
from csv import reader, writer, Sniffer from collections import defaultdict from warnings import warn from typing import List def user_interface() -> int: """Asks user for a query""" print('1. Вывести все отделы') print('2. Вывести сводный отчёт по отделам') print('3. Сохранить сводный отчёт в виде csv-файла') q = None while q not in [1, 2, 3]: try: q = int(input('Номер запроса:')) except ValueError: print('Введите только число - 1, 2 или 3') return q def main(q: int) -> None: """Handles users queries. 1: print departments list; 2: print departments summary; 3: save departments summary to csv file. Asks user for the next query after successful execution. """ employees = load_csv() dep_data = group_by(employees, "отдел", "оклад") try: if q == 1: departments_summary(dep_data, 'list_only') elif q == 2: departments_summary(dep_data, 'print') elif q == 3: departments_summary(dep_data, 'to_csv') print('Сводный отчет по отделам сохранен в csv-файл.') res = True except BaseException as e: warn(f'An error "{e}" occurred') res = False if res: again = None while again not in ['y', 'n', 'yes', 'no']: again = input('Запрос выполнен успешно. Выполнить новый запрос? [y/n]\n:') if again[0] == 'y': ans = user_interface() main(ans) else: return def departments_summary(dep_data: dict, output: str = '') -> List[List]: """Computes salaries summary for each department and returns the data with header as a list of lists. Performs additional actions if output specified. """ if output == 'list_only': print('Список отделов:') print('\n'.join(dep_data.keys())) header = ['Отдел', 'Численность', 'Вилка зарплат', 'Средняя зарплата'] summary = [] for i, (dep, vals) in enumerate(dep_data.items()): summary.append([dep]) summary[i].append(len(vals)) summary[i].append(f'{int(min(vals))}-{int(max(vals))}') summary[i].append(round(sum(vals)/len(vals), 2)) h_summary = [header] + summary if output == 'print': print('Сводный отчет по отделам:') print_table(h_summary) elif output == 'to_csv': to_csv(h_summary) return h_summary def group_by(data: List[List], by: str = 'отдел', field: str = 'оклад') -> dict: """Groups the 'field' column by categories in 'by' column from 'data'""" pos = col_position_handler(data[0], by, field) groups_data = defaultdict(list) for d in data[1:]: group = d[pos[0]].split('->')[0].strip() try: value = float(d[pos[1]].strip()) groups_data[group].append(value) except ValueError: warn(f'Non-numeric data in column "{field}"!') return groups_data def col_position_handler(header: list, by: str, field: str) -> list: """Returns positions of 'by' and 'field' in 'header' as a list. Used by group_by function. """ positions = {} for i, h in enumerate(header): h = h.lower() if h == by.strip().lower(): positions[0] = i elif h == field.strip().lower(): positions[1] = i return list(positions.values()) def load_csv(path: str = 'employees.csv') -> List[List]: try: with open(path) as f: dialect = Sniffer().sniff(f.read(1024)) f.seek(0) rdr = reader(f, dialect) return list(rdr) except FileNotFoundError: warn(f'File not found. Please, make sure to place {path} file in the directory!') exit(1) def print_table(data: list) -> None: """Pretty print data in table-like format """ row_format = "{:>20}|" * (len(data[0])) for line in data: print(row_format.format(*line)) def to_csv(data: List[List], path: str = 'summary.csv', delimiter: str = ',') -> None: with open(path, 'w', newline='') as f: wrtr = writer(f, delimiter=delimiter) wrtr.writerows(data) if __name__ == '__main__': main(user_interface())
a2339a66c432796ec7dc5bb3407e67700101c5ef
arielsilveira/Bioinformatica
/Levenshtein.py
916
3.59375
4
from numpy import array,zeros import functions as func def levenshtein(seqA, seqB): if(len(seqA) != len(seqB)): print("Tamanho da sequência diferente!") return result = zeros(( len(seqA) + 1, len(seqB) +1)) for i in range(0, len(seqA) + 1): result[i][0] = i for i in range(0, len(seqB) + 1): result[0][i] = i sum = 0 for i in range(1, len(seqA) + 1): for j in range(1, len(seqB) + 1): if seqA[i - 1] == seqB[j - 1]: sum = 0 else: sum = 1 result[i][j] = min(result[i-1][j] + 1, min(result[i][j-1] + 1, result[i-1][j-1] + sum)) print("Matrix:") func.printMatrix(result) print("\nResult = ", result[len(seqA)][len(seqB)]) func.finalFunction() func.clearScreen()
d77641147c6c31c9722c45f68a7418e3223a9b28
kay-kay-t/Python
/exeptions.py
867
3.8125
4
try: age = int(input("Age: ")) xfactor = 10 / age except ValueError: print("You didn't enter a valid age.") except ZeroDivisionError: print("Age can't be 0") # Or: except (ValueError, ZeroDivisionError): print("You didn't enter a valid age.") else: print("No exceptions were thrown") # To use a function after exceptions (like close a file): try: file = open("app.py") age = int(input("Age: ")) xfactor = 10 / age except (ValueError, ZeroDivisionError): print("You didn't enter a valid age.") else: print("No exceptions were thrown") finally: file.close() # Or you can use with statement to relese resources (so no need in finally cloth) with open("app.py") as file: print("File opened") # from timeit import timeit # with this function you can see execution time of code
4ce78bcf0b9df48a5326e32eb7df819f5f438230
ankeoderij/vbtl-dodona
/sequentie 7.py
334
3.5625
4
gewicht = int(input("Hoeveel gram weegt het pakje? ")) afstand = int(input("Hoeveel kilometer moet het pakje afleggen? ")) begonnen_gewicht = (gewicht + 19) // 20 begonnen_afstand = (afstand + 9) // 10 prijs = 2 + begonnen_gewicht * 0.4 + begonnen_afstand * 0.3 print("Prijs voor het versturen van het pakje:", prijs, "euro")
54d66d65233208c7b7849dff1b1793cba8ee6df3
tanmaya-lakhera11/NewPyRepo
/Scripts/Test1.py
324
3.78125
4
import datetime as dt def string_formatting(): ls = [2019, 9, 20, 12, 30, 20] date = dt.datetime(*ls) print(date) print('year is {0:%Y} month is {0:%B} day is {0:%d}'.format(date)) dict = {'a':1,'b':2} for i ,j in dict.items(): print(i,j) if __name__ == '__main__': string_formatting()
e7189b646cedb06f82885acbe6801cb776aa9a96
chocolate1337/python_base
/lesson_011/01_shapes.py
1,122
4.125
4
# -*- coding: utf-8 -*- import simple_draw as sd # На основе вашего кода из решения lesson_004/01_shapes.py сделать функцию-фабрику, # которая возвращает функции рисования треугольника, четырехугольника, пятиугольника и т.д. # # Функция рисования должна принимать параметры # - точка начала рисования # - угол наклона # - длина стороны # # Функция-фабрика должна принимать параметр n - количество сторон. def get_polygon(n): def geometry(point, angle=30, length=100): point_1 = point for angles in range(0, n - 1, 1): v = sd.get_vector(point, angle=angles * (360 // n) + angle, length=length) point = v.end_point v.draw() sd.line(point_1, point) return geometry draw_triangle = get_polygon(n=3) draw_triangle(point=sd.get_point(200, 200), angle=1, length=50) sd.pause() # зачет!
774dbebeb95e9e3a23fa16b358ecdb31b09dee42
chocolate1337/python_base
/lesson_003/07_wall.py
999
3.6875
4
# -*- coding: utf-8 -*- # (цикл for) import simple_draw as sd # Нарисовать стену из кирпичей. Размер кирпича - 100х50 # Использовать вложенные циклы for # Подсказки: # Для отрисовки кирпича использовать функцию rectangle # Алгоритм должен получиться приблизительно такой: # # цикл по координате Y # вычисляем сдвиг ряда кирпичей # цикл координате X # вычисляем правый нижний и левый верхний углы кирпича # рисуем кирпич delta = 0 for y in range(0, 650, 50): delta += 50 for x in range(delta, 650, 100): point = sd.Point(x, y) point1 = sd.Point(x + 100, y + 50) sd.rectangle(point, point1, sd.COLOR_ORANGE, 2) delta -= 100 sd.pause() # зачет!
432be1681cbb2b65cfb35fc16a9df3fcf810059e
puran1218/automate-the-boring-stuff-with-python
/strip_regex.py
470
3.703125
4
import re def strip_charactor(charactor, strip_char = ''): if strip_char == '': return charactor.strip() else: charactor = charactor.strip() charactorRegex = re.compile(strip_char) return charactorRegex.sub('', charactor) charactor = input("Please input the full charactor: ") strip_char = input("Please input the charactor you want to striped: ") strip_charactor = strip_charactor(charactor, strip_char) print(strip_charactor)
5661b3cfd0809585ec43e6b5a7605b6b4d06f70d
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/equilibrium-index-6.py
1,442
3.671875
4
"""Equilibrium index""" from itertools import (accumulate) # equilibriumIndices :: [Num] -> [Int] def equilibriumIndices(xs): '''List indices at which the sum of values to the left equals the sum of values to the right.''' def go(xs): '''Left scan from accumulate, right scan derived from left''' ls = list(accumulate(xs)) n = ls[-1] return [i for (i, (x, y)) in enumerate(zip( ls, [n] + [n - x for x in ls[0:-1]] )) if x == y] return go(xs) if xs else [] # TEST ------------------------------------------------- # main :: IO () def main(): '''Tabulated test results''' print( tabulated('Equilibrium indices:\n')( equilibriumIndices )([ [-7, 1, 5, 2, -4, 3, 0], [2, 4, 6], [2, 9, 2], [1, -1, 1, -1, 1, -1, 1], [1], [] ]) ) # GENERIC ------------------------------------------------- # tabulated :: String -> (a -> b) -> [a] -> String def tabulated(s): '''heading -> function -> input List -> tabulated output string''' def go(f, xs): def width(x): return len(str(x)) w = width(max(xs, key=width)) return s + '\n' + '\n'.join([ str(x).rjust(w, ' ') + ' -> ' + str(f(x)) for x in xs ]) return lambda f: lambda xs: go(f, xs) if __name__ == '__main__': main()
89002b33bc9f0c1fd61e1e4ba9e4230389e66f65
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/determine-if-a-string-is-numeric-4.py
834
3.609375
4
def numeric(literal): """Return value of numeric literal or None if can't parse a value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: return cast(literal) except ValueError: pass return None tests = [ '0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04', '0.123', '(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', '-0xABC', '0x1a1', '12.5%', '1/2', '½', '3¼', 'π', 'Ⅻ', '1,000,000', '1 000', '- 001.20e+02', 'NaN', 'inf', '-Infinity'] for s in tests: print("%14s -> %-14s %-20s is_numeric: %-5s str.isnumeric: %s" % ( '"'+s+'"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() ))
498007231374040d3bc01f9ee9e7ba7a39c2b91b
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/identity-matrix-1.py
358
3.671875
4
def identity(size): matrix = [[0]*size for i in range(size)] #matrix = [[0] * size] * size #Has a flaw. See http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists for i in range(size): matrix[i][i] = 1 for rows in matrix: for elements in rows: print elements, print ""
40110347352307713768d75f5752b1347cfee561
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/generator-exponential-2.py
1,715
3.890625
4
'''Exponentials as generators''' from itertools import count, islice # powers :: Gen [Int] def powers(n): '''A non-finite succession of integers, starting at zero, raised to the nth power.''' def f(x): return pow(x, n) return map(f, count(0)) # main :: IO () def main(): '''Taking the difference between two derived generators.''' print( take(10)( drop(20)( differenceGen(powers(2))( powers(3) ) ) ) ) # GENERIC ------------------------------------------------- # differenceGen :: Gen [a] -> Gen [a] -> Gen [a] def differenceGen(ga): '''All values of ga except any already seen in gb.''' def go(a, b): stream = zip(a, b) bs = set([]) while True: xy = next(stream, None) if None is not xy: x, y = xy bs.add(y) if x not in bs: yield x else: return return lambda gb: go(ga, gb) # drop :: Int -> [a] -> [a] # drop :: Int -> String -> String def drop(n): '''The sublist of xs beginning at (zero-based) index n.''' def go(xs): if isinstance(xs, list): return xs[n:] else: take(n)(xs) return xs return lambda xs: go(xs) # take :: Int -> [a] -> [a] # take :: Int -> String -> String def take(n): '''The prefix of xs of length n, or xs itself if n > length xs.''' return lambda xs: ( xs[0:n] if isinstance(xs, list) else list(islice(xs, n)) ) # MAIN --- if __name__ == '__main__': main()
4da1ef2fb9c9d01be7726c46f132cf7030777d73
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/align-columns-4.py
867
3.703125
4
txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column.""" parts = [line.rstrip("$").split("$") for line in txt.splitlines()] max_widths = {} for line in parts: for i, word in enumerate(line): max_widths[i] = max(max_widths.get(i, 0), len(word)) for i, justify in enumerate([str.ljust, str.center, str.rjust]): print(["Left", "Center", "Right"][i], " column-aligned output:\n") for line in parts: for j, word in enumerate(line): print(justify(word, max_widths[j]), end=' ') print() print("- " * 52)
6e15e94ea286d90775ca14edb709e771872003c0
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/set-puzzle-1.py
1,168
3.578125
4
#!/usr/bin/python from itertools import product, combinations from random import sample ## Major constants features = [ 'green purple red'.split(), 'one two three'.split(), 'oval diamond squiggle'.split(), 'open striped solid'.split() ] deck = list(product(list(range(3)), repeat=4)) dealt = 9 ## Functions def printcard(card): print(' '.join('%8s' % f[i] for f,i in zip(features, card))) def getdeal(dealt=dealt): deal = sample(deck, dealt) return deal def getsets(deal): good_feature_count = set([1, 3]) sets = [ comb for comb in combinations(deal, 3) if all( [(len(set(feature)) in good_feature_count) for feature in zip(*comb)] ) ] return sets def printit(deal, sets): print('Dealt %i cards:' % len(deal)) for card in deal: printcard(card) print('\nFound %i sets:' % len(sets)) for s in sets: for card in s: printcard(card) print('') if __name__ == '__main__': while True: deal = getdeal() sets = getsets(deal) if len(sets) == dealt / 2: break printit(deal, sets)
b713856a759343c2233678f18a77ef18edf174c8
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/abundant,-deficient-and-perfect-number-classifications-2.py
2,632
3.578125
4
'''Abundant, deficient and perfect number classifications''' from itertools import accumulate, chain, groupby, product from functools import reduce from math import floor, sqrt from operator import mul # deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int) def deficientPerfectAbundantCountsUpTo(n): '''Counts of deficient, perfect, and abundant integers in the range [1..n]. ''' def go(dpa, x): deficient, perfect, abundant = dpa divisorSum = sum(properDivisors(x)) return ( succ(deficient), perfect, abundant ) if x > divisorSum else ( deficient, perfect, succ(abundant) ) if x < divisorSum else ( deficient, succ(perfect), abundant ) return reduce(go, range(1, 1 + n), (0, 0, 0)) # --------------------------TEST-------------------------- # main :: IO () def main(): '''Size of each sub-class of integers drawn from [1..20000]:''' print(main.__doc__) print( '\n'.join(map( lambda a, b: a.rjust(10) + ' -> ' + str(b), ['Deficient', 'Perfect', 'Abundant'], deficientPerfectAbundantCountsUpTo(20000) )) ) # ------------------------GENERIC------------------------- # primeFactors :: Int -> [Int] def primeFactors(n): '''A list of the prime factors of n. ''' def f(qr): r = qr[1] return step(r), 1 + r def step(x): return 1 + (x << 2) - ((x >> 1) << 1) def go(x): root = floor(sqrt(x)) def p(qr): q = qr[0] return root < q or 0 == (x % q) q = until(p)(f)( (2 if 0 == x % 2 else 3, 1) )[0] return [x] if q > root else [q] + go(x // q) return go(n) # properDivisors :: Int -> [Int] def properDivisors(n): '''The ordered divisors of n, excluding n itself. ''' def go(a, x): return [a * b for a, b in product( a, accumulate(chain([1], x), mul) )] return sorted( reduce(go, [ list(g) for _, g in groupby(primeFactors(n)) ], [1]) )[:-1] if 1 < n else [] # succ :: Int -> Int def succ(x): '''The successor of a value. For numeric types, (1 +). ''' return 1 + x # until :: (a -> Bool) -> (a -> a) -> a -> a def until(p): '''The result of repeatedly applying f until p holds. The initial seed value is x. ''' def go(f, x): v = x while not p(v): v = f(v) return v return lambda f: lambda x: go(f, x) # MAIN --- if __name__ == '__main__': main()
9432070a5c89616231109b69d4e2bfbea89704bf
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/polynomial-long-division.py
838
3.5
4
# -*- coding: utf-8 -*- from itertools import izip from math import fabs def degree(poly): while poly and poly[-1] == 0: poly.pop() # normalize return len(poly)-1 def poly_div(N, D): dD = degree(D) dN = degree(N) if dD < 0: raise ZeroDivisionError if dN >= dD: q = [0] * dN while dN >= dD: d = [0]*(dN - dD) + D mult = q[dN - dD] = N[-1] / float(d[-1]) d = [coeff*mult for coeff in d] N = [fabs ( coeffN - coeffd ) for coeffN, coeffd in izip(N, d)] dN = degree(N) r = N else: q = [0] r = N return q, r if __name__ == '__main__': print "POLYNOMIAL LONG DIVISION" N = [-42, 0, -12, 1] D = [-3, 1, 0, 0] print " %s / %s =" % (N,D), print " %s remainder %s" % poly_div(N, D)
af2f4552ca30807bf7ad855f28986e53a43fccbb
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/sieve-of-eratosthenes-13.py
1,874
3.671875
4
def primes(): for p in [2,3,5,7]: yield p # base wheel primes gaps1 = [ 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8 ] gaps = gaps1 + [ 6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ] # wheel2357 def wheel_prime_pairs(): yield (11,0); bps = wheel_prime_pairs() # additional primes supply p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put sieve = {}; n = 13; ni = 1 # into sieve dict; init cndidate, wheel ndx while True: if n not in sieve: # is not a multiple of previously recorded primes if n < q: yield (n, ni) # n is prime with wheel modulo index else: npi = pi + 1 # advance wheel index if npi > 47: npi = 0 sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel p, pi = next(bps); q = p * p # advance next prime and prime square to put else: s, si = sieve.pop(n) nxt = n + s * gaps[si] # move current cull position up the wheel si = si + 1 # advance wheel index if si > 47: si = 0 while nxt in sieve: # ensure each entry is unique by wheel nxt += s * gaps[si] si = si + 1 # advance wheel index if si > 47: si = 0 sieve[nxt] = (s, si) # next non-marked multiple of a prime nni = ni + 1 # advance wheel index if nni > 47: nni = 0 n += gaps[ni]; ni = nni # advance on the wheel for p, pi in wheel_prime_pairs(): yield p # strip out indexes
873874e4acd45562961776f95250bd2fb3eb0b79
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/vector-products.py
968
3.921875
4
def crossp(a, b): '''Cross product of two 3D vectors''' assert len(a) == len(b) == 3, 'For 3D vectors only' a1, a2, a3 = a b1, b2, b3 = b return (a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1) def dotp(a,b): '''Dot product of two eqi-dimensioned vectors''' assert len(a) == len(b), 'Vector sizes must match' return sum(aterm * bterm for aterm,bterm in zip(a, b)) def scalartriplep(a, b, c): '''Scalar triple product of three vectors: "a . (b x c)"''' return dotp(a, crossp(b, c)) def vectortriplep(a, b, c): '''Vector triple product of three vectors: "a x (b x c)"''' return crossp(a, crossp(b, c)) if __name__ == '__main__': a, b, c = (3, 4, 5), (4, 3, 5), (-5, -12, -13) print("a = %r; b = %r; c = %r" % (a, b, c)) print("a . b = %r" % dotp(a,b)) print("a x b = %r" % (crossp(a,b),)) print("a . (b x c) = %r" % scalartriplep(a, b, c)) print("a x (b x c) = %r" % (vectortriplep(a, b, c),))
a66cec30e74673564f3d79ac5637143ca0bf1185
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/singly-linked-list-element-definition.py
759
3.9375
4
class LinkedList(object): """USELESS academic/classroom example of a linked list implemented in Python. Don't ever consider using something this crude! Use the built-in list() type! """ class Node(object): def __init__(self, item): self.value = item self.next = None def __init__(self, item=None): if item is not None: self.head = Node(item); self.tail = self.head else: self.head = None; self.tail = None def append(self, item): if not self.head: self.head = Node(item) self.tail = self.head elif self.tail: self.tail.next = Node(item) self.tail = self.tail.next else: self.tail = Node(item) def __iter__(self): cursor = self.head while cursor: yield cursor.value cursor = cursor.next
49de075fd9986b8219800e4c7ad9b8c07e733afc
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/last-friday-of-each-month-3.py
430
3.796875
4
import calendar c=calendar.Calendar() fridays={} year=raw_input("year") add=list.__add__ for day in reduce(add,reduce(add,reduce(add,c.yeardatescalendar(int(year))))): if "Fri" in day.ctime() and year in day.ctime(): month,day=str(day).rsplit("-",1) fridays[month]=day for item in sorted((month+"-"+day for month,day in fridays.items()), key=lambda x:int(x.split("-")[1])): print item
6c1b5451242f66fde307473089ed150ad69e1974
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/echo-server-3.py
2,751
3.546875
4
#!usr/bin/env python import socket import threading HOST = 'localhost' PORT = 12321 SOCKET_TIMEOUT = 30 # This function handles reading data sent by a client, echoing it back # and closing the connection in case of timeout (30s) or "quit" command # This function is meant to be started in a separate thread # (one thread per client) def handle_echo(client_connection, client_address): client_connection.settimeout(SOCKET_TIMEOUT) try: while True: data = client_connection.recv(1024) # Close connection if "quit" received from client if data == b'quit\r\n' or data == b'quit\n': print('{} disconnected'.format(client_address)) client_connection.shutdown(1) client_connection.close() break # Echo back to client elif data: print('FROM {} : {}'.format(client_address,data)) client_connection.send(data) # Timeout and close connection after 30s of inactivity except socket.timeout: print('{} timed out'.format(client_address)) client_connection.shutdown(1) client_connection.close() # This function opens a socket and listens on specified port. As soon as a # connection is received, it is transfered to another socket so that the main # socket is not blocked and can accept new clients. def listen(host, port): # Create the main socket (IPv4, TCP) connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) connection.bind((host, port)) # Listen for clients (max 10 clients in waiting) connection.listen(10) # Every time a client connects, allow a dedicated socket and a dedicated # thread to handle communication with that client without blocking others. # Once the new thread has taken over, wait for the next client. while True: current_connection, client_address = connection.accept() print('{} connected'.format(client_address)) handler_thread = threading.Thread( \ target = handle_echo, \ args = (current_connection,client_address) \ ) # daemon makes sure all threads are killed if the main server process # gets killed handler_thread.daemon = True handler_thread.start() if __name__ == "__main__": try: listen(HOST, PORT) except KeyboardInterrupt: print('exiting') pass
bbb80cbc56d5f9c83ecaf1c35223a5d0f98b18c1
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/day-of-the-week-2.py
1,944
3.75
4
'''Days of the week''' from datetime import date from itertools import islice # xmasIsSunday :: Int -> Bool def xmasIsSunday(y): '''True if Dec 25 in the given year is a Sunday.''' return 6 == date(y, 12, 25).weekday() # main :: IO () def main(): '''Years between 2008 and 2121 with 25 Dec on a Sunday''' xs = list(filter( xmasIsSunday, enumFromTo(2008)(2121) )) total = len(xs) print( fTable(main.__doc__ + ':\n\n' + '(Total ' + str(total) + ')\n')( lambda i: str(1 + i) )(str)(index(xs))( enumFromTo(0)(total - 1) ) ) # GENERIC ------------------------------------------------- # enumFromTo :: (Int, Int) -> [Int] def enumFromTo(m): '''Integer enumeration from m to n.''' return lambda n: list(range(m, 1 + n)) # index (!!) :: [a] -> Int -> a def index(xs): '''Item at given (zero-based) index.''' return lambda n: None if 0 > n else ( xs[n] if ( hasattr(xs, "__getitem__") ) else next(islice(xs, n, None)) ) # unlines :: [String] -> String def unlines(xs): '''A single string formed by the intercalation of a list of strings with the newline character. ''' return '\n'.join(xs) # FORMATTING --------------------------------------------- # fTable :: String -> (a -> String) -> # (b -> String) -> (a -> b) -> [a] -> String def fTable(s): '''Heading -> x display function -> fx display function -> f -> xs -> tabular string. ''' def go(xShow, fxShow, f, xs): ys = [xShow(x) for x in xs] w = max(map(len, ys)) return s + '\n' + '\n'.join(map( lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)), xs, ys )) return lambda xShow: lambda fxShow: lambda f: lambda xs: go( xShow, fxShow, f, xs ) # MAIN -- if __name__ == '__main__': main()
33ed6c5779d837798853c9187da251414c937e09
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/longest-string-challenge.py
568
3.828125
4
import fileinput # This returns True if the second string has a value on the # same index as the last index of the first string. It runs # faster than trimming the strings because it runs len once # and is a single index lookup versus slicing both strings # one character at a time. def longer(a, b): try: b[len(a)-1] return False except: return True longest, lines = '', '' for x in fileinput.input(): if longer(x, longest): lines, longest = x, x elif not longer(longest, x): lines += x print(lines, end='')
641a53abbc374c18de6f5d98ce9466f9fa858925
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/zig-zag-matrix-4.py
356
3.6875
4
COLS = 9 def CX(x, ran): while True: x += 2 * next(ran) yield x x += 1 yield x ran = [] d = -1 for V in CX(1,iter(list(range(0,COLS,2)) + list(range(COLS-1-COLS%2,0,-2)))): ran.append(iter(range(V, V+COLS*d, d))) d *= -1 for x in range(0,COLS): for y in range(x, x+COLS): print(repr(next(ran[y])).rjust(3), end = ' ') print()
9a95dc9c43f8435729db22c217b6836af58c1dd5
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/range-extraction-4.py
2,219
3.609375
4
'''Range extraction''' from functools import reduce # rangeFormat :: [Int] -> String def rangeFormat(xs): '''Range-formatted display string for a list of integers. ''' return ','.join([ rangeString(x) for x in splitBy(lambda a, b: 1 < b - a)(xs) ]) # rangeString :: [Int] -> String def rangeString(xs): '''Start and end of xs delimited by hyphens if there are more than two integers. Otherwise, comma-delimited xs. ''' ys = [str(x) for x in xs] return '-'.join([ys[0], ys[-1]]) if 2 < len(ys) else ( ','.join(ys) ) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Test''' xs = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39 ] print( __doc__ + ':\n[' + '\n'.join(map( lambda x: ' ' + repr(x)[1:-1], chunksOf(11)(xs) )) + " ]\n\n -> '" + rangeFormat(xs) + "'\n" ) # GENERIC ------------------------------------------------- # chunksOf :: Int -> [a] -> [[a]] def chunksOf(n): '''A series of lists of length n, subdividing the contents of xs. Where the length of xs is not evenly divible, the final list will be shorter than n.''' return lambda xs: reduce( lambda a, i: a + [xs[i:n + i]], range(0, len(xs), n), [] ) if 0 < n else [] # splitBy :: (a -> a -> Bool) -> [a] -> [[a]] def splitBy(p): '''A list split wherever two consecutive items match the binary predicate p. ''' # step :: ([[a]], [a], a) -> a -> ([[a]], [a], a) def step(acp, x): acc, active, prev = acp return (acc + [active], [x], x) if p(prev, x) else ( (acc, active + [x], x) ) # go :: [a] -> [[a]] def go(xs): if 2 > len(xs): return xs else: h = xs[0] ys = reduce(step, xs[1:], ([], [h], h)) # The accumulated sublists, and the current group. return ys[0] + [ys[1]] return lambda xs: go(xs) # MAIN --- if __name__ == '__main__': main()
7162d0631de035b9022d05a1ad13ea4db3feb812
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/natural-sorting.py
5,291
3.59375
4
# -*- coding: utf-8 -*- # Not Python 3.x (Can't compare str and int) from itertools import groupby from unicodedata import decomposition, name from pprint import pprint as pp commonleaders = ['the'] # lowercase leading words to ignore replacements = {u'ß': 'ss', # Map single char to replacement string u'ſ': 's', u'ʒ': 's', } hexdigits = set('0123456789abcdef') decdigits = set('0123456789') # Don't use str.isnumeric def splitchar(c): ' De-ligature. De-accent a char' de = decomposition(c) if de: # Just the words that are also hex numbers de = [d for d in de.split() if all(c.lower() in hexdigits for c in d)] n = name(c, c).upper() # (Gosh it's onerous) if len(de)> 1 and 'PRECEDE' in n: # E.g. ʼn LATIN SMALL LETTER N PRECEDED BY APOSTROPHE de[1], de[0] = de[0], de[1] tmp = [ unichr(int(k, 16)) for k in de] base, others = tmp[0], tmp[1:] if 'LIGATURE' in n: # Assume two character ligature base += others.pop(0) else: base = c return base def sortkeygen(s): '''Generate 'natural' sort key for s Doctests: >>> sortkeygen(' some extra spaces ') [u'some extra spaces'] >>> sortkeygen('CasE InseNsItIve') [u'case insensitive'] >>> sortkeygen('The Wind in the Willows') [u'wind in the willows'] >>> sortkeygen(u'\462 ligature') [u'ij ligature'] >>> sortkeygen(u'\335\375 upper/lower case Y with acute accent') [u'yy upper/lower case y with acute accent'] >>> sortkeygen('foo9.txt') [u'foo', 9, u'.txt'] >>> sortkeygen('x9y99') [u'x', 9, u'y', 99] ''' # Ignore leading and trailing spaces s = unicode(s).strip() # All space types are equivalent s = ' '.join(s.split()) # case insentsitive s = s.lower() # Title words = s.split() if len(words) > 1 and words[0] in commonleaders: s = ' '.join( words[1:]) # accent and ligatures s = ''.join(splitchar(c) for c in s) # Replacements (single char replaced by one or more) s = ''.join( replacements.get(ch, ch) for ch in s ) # Numeric sections as numerics s = [ int("".join(g)) if isinteger else "".join(g) for isinteger,g in groupby(s, lambda x: x in decdigits)] return s def naturalsort(items): ''' Naturally sort a series of strings Doctests: >>> naturalsort(['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda']) ['The 39 steps', 'The 40th step more', 'Wanda', 'The Wind in the Willows'] ''' return sorted(items, key=sortkeygen) if __name__ == '__main__': import string ns = naturalsort print '\n# Ignoring leading spaces' txt = ['%signore leading spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Ignoring multiple adjacent spaces (m.a.s)' txt = ['ignore m.a.s%s spaces: 2%+i' % (' '*i, i-2) for i in range(4)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Equivalent whitespace characters' txt = ['Equiv.%sspaces: 3%+i' % (ch, i-3) for i,ch in enumerate(reversed(string.whitespace))] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Case Indepenent sort' s = 'CASE INDEPENENT' txt = [s[:i].lower() + s[i:] + ': 3%+i' % (i-3) for i in range(1,5)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Numeric fields as numerics' txt = ['foo100bar99baz0.txt', 'foo100bar10baz0.txt', 'foo1000bar99baz10.txt', 'foo1000bar99baz9.txt'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Title sorts' txt = ['The Wind in the Willows','The 40th step more', 'The 39 steps', 'Wanda'] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Equivalent accented characters (and case)' txt = ['Equiv. %s accents: 2%+i' % (ch, i-2) for i,ch in enumerate(u'\xfd\xddyY')] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Separated ligatures' txt = [u'\462 ligatured ij', 'no ligature',] print 'Text strings:'; pp(txt) print 'Normally sorted :'; pp(sorted(txt)) print 'Naturally sorted:'; pp(ns(txt)) print '\n# Character replacements' s = u'ʒſßs' # u'\u0292\u017f\xdfs' txt = ['Start with an %s: 2%+i' % (ch, i-2) for i,ch in enumerate(s)] print 'Text strings:'; pp(txt) print 'Normally sorted :'; print '\n'.join(sorted(txt)) print 'Naturally sorted:'; print '\n'.join(ns(txt))
d2d443f4d1138561f6a67fca48407469290185d9
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/accumulator-factory-2.py
151
3.546875
4
def accumulator(sum): def f(n): nonlocal sum sum += n return sum return f x = accumulator(1) x(5) print(accumulator(3)) print(x(2.3))
d818d77f017fb908113dbdffbbaafa2b301d5999
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/fibonacci-n-step-number-sequences-3.py
549
3.671875
4
from itertools import islice, cycle def fiblike(tail): for x in tail: yield x for i in cycle(xrange(len(tail))): tail[i] = x = sum(tail) yield x fibo = fiblike([1, 1]) print list(islice(fibo, 10)) lucas = fiblike([2, 1]) print list(islice(lucas, 10)) suffixes = "fibo tribo tetra penta hexa hepta octo nona deca" for n, name in zip(xrange(2, 11), suffixes.split()): fib = fiblike([1] + [2 ** i for i in xrange(n - 1)]) items = list(islice(fib, 15)) print "n=%2i, %5snacci -> %s ..." % (n, name, items)
73d6b5c8babfaf09c356c6cc3a5514d4a54cde52
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/determine-if-a-string-is-numeric-3.py
387
3.671875
4
def is_numeric(literal): """Return whether a literal can be parsed as a numeric value""" castings = [int, float, complex, lambda s: int(s,2), #binary lambda s: int(s,8), #octal lambda s: int(s,16)] #hex for cast in castings: try: cast(literal) return True except ValueError: pass return False
e3d423874c1393e42d6847372fdccd073086a89f
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/maze-solving.py
1,747
4.03125
4
# python 3 def Dijkstra(Graph, source): ''' + +---+---+ | 0 1 2 | +---+ + + | 3 4 | 5 +---+---+---+ >>> graph = ( # or ones on the diagonal ... (0,1,0,0,0,0,), ... (1,0,1,0,1,0,), ... (0,1,0,0,0,1,), ... (0,0,0,0,1,0,), ... (0,1,0,1,0,0,), ... (0,0,1,0,0,0,), ... ) ... >>> Dijkstra(graph, 0) ([0, 1, 2, 3, 2, 3], [1e+140, 0, 1, 4, 1, 2]) >>> display_solution([1e+140, 0, 1, 4, 1, 2]) 5<2<1<0 ''' # Graph[u][v] is the weight from u to v (however 0 means infinity) infinity = float('infinity') n = len(graph) dist = [infinity]*n # Unknown distance function from source to v previous = [infinity]*n # Previous node in optimal path from source dist[source] = 0 # Distance from source to source Q = list(range(n)) # All nodes in the graph are unoptimized - thus are in Q while Q: # The main loop u = min(Q, key=lambda n:dist[n]) # vertex in Q with smallest dist[] Q.remove(u) if dist[u] == infinity: break # all remaining vertices are inaccessible from source for v in range(n): # each neighbor v of u if Graph[u][v] and (v in Q): # where v has not yet been visited alt = dist[u] + Graph[u][v] if alt < dist[v]: # Relax (u,v,a) dist[v] = alt previous[v] = u return dist,previous def display_solution(predecessor): cell = len(predecessor)-1 while cell: print(cell,end='<') cell = predecessor[cell] print(0)
0cc9c46d04c155a1f052a3d70505d2d1407fc053
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/tree-traversal-1.py
2,172
3.71875
4
from collections import namedtuple Node = namedtuple('Node', 'data, left, right') tree = Node(1, Node(2, Node(4, Node(7, None, None), None), Node(5, None, None)), Node(3, Node(6, Node(8, None, None), Node(9, None, None)), None)) def printwithspace(i): print(i, end=' ') def dfs(order, node, visitor): if node is not None: for action in order: if action == 'N': visitor(node.data) elif action == 'L': dfs(order, node.left, visitor) elif action == 'R': dfs(order, node.right, visitor) def preorder(node, visitor = printwithspace): dfs('NLR', node, visitor) def inorder(node, visitor = printwithspace): dfs('LNR', node, visitor) def postorder(node, visitor = printwithspace): dfs('LRN', node, visitor) def ls(node, more, visitor, order='TB'): "Level-based Top-to-Bottom or Bottom-to-Top tree search" if node: if more is None: more = [] more += [node.left, node.right] for action in order: if action == 'B' and more: ls(more[0], more[1:], visitor, order) elif action == 'T' and node: visitor(node.data) def levelorder(node, more=None, visitor = printwithspace): ls(node, more, visitor, 'TB') # Because we can def reverse_preorder(node, visitor = printwithspace): dfs('RLN', node, visitor) def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'): ls(node, more, visitor, 'BT') if __name__ == '__main__': w = 10 for traversal in [preorder, inorder, postorder, levelorder, reverse_preorder, bottom_up_order]: if traversal == reverse_preorder: w = 20 print('\nThe generalisation of function dfs allows:') if traversal == bottom_up_order: print('The generalisation of function ls allows:') print(f"{traversal.__name__:>{w}}:", end=' ') traversal(tree) print()
aac29ec5cf86cb36d9ad4095241a2c1eb022a29f
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/gui-maximum-window-dimensions.py
384
3.640625
4
#!/usr/bin/env python3 import tkinter as tk # import the module. root = tk.Tk() # Create an instance of the class. root.state('zoomed') # Maximized the window. root.update_idletasks() # Update the display. tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())), font=("Helvetica", 25)).pack() # add a label and set the size to text. root.mainloop()
dc956f51e6ea0e2c13af3c1e9dc41af645b4ae14
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/primality-by-trial-division-3.py
373
3.90625
4
def prime3(a): if a < 2: return False if a == 2 or a == 3: return True # manually test 2 and 3 if a % 2 == 0 or a % 3 == 0: return False # exclude multiples of 2 and 3 maxDivisor = a**0.5 d, i = 5, 2 while d <= maxDivisor: if a % d == 0: return False d += i i = 6 - i # this modifies 2 into 4 and viceversa return True
9ac58f57d11ec323e55ef5095a52eab64632febc
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/globally-replace-text-in-several-files.py
131
3.796875
4
import fileinput for line in fileinput.input(inplace=True): print(line.replace('Goodbye London!', 'Hello New York!'), end='')
ce9d1cd697671c12003a39b17ee7a9bfebf0103d
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/letter-frequency-3.py
890
4.125
4
import string if hasattr(string, 'ascii_lowercase'): letters = string.ascii_lowercase # Python 2.2 and later else: letters = string.lowercase # Earlier versions offset = ord('a') def countletters(file_handle): """Traverse a file and compute the number of occurences of each letter return results as a simple 26 element list of integers.""" results = [0] * len(letters) for line in file_handle: for char in line: char = char.lower() if char in letters: results[ord(char) - offset] += 1 # Ordinal minus ordinal of 'a' of any lowercase ASCII letter -> 0..25 return results if __name__ == "__main__": sourcedata = open(sys.argv[1]) lettercounts = countletters(sourcedata) for i in xrange(len(lettercounts)): print "%s=%d" % (chr(i + ord('a')), lettercounts[i]),
3e5d74e7a18e7ff52ec1425c5cac78316ce2ce85
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/averages-arithmetic-mean-3.py
154
3.6875
4
def average(x): return sum(x)/float(len(x)) if x else 0 print (average([0,0,3,1,4,1,5,9,0,0])) print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))
0fa2f0f4c3a80658c2f69900cc6314e0093b63cf
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/empty-string.py
88
3.828125
4
s = '' if len(s) == 0: print("String is empty") else: print("String not empty")
87b7b74d149b8cddccd58eb80405bb5e43143ec5
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/runtime-evaluation-in-an-environment-2.py
248
3.59375
4
>>> def eval_with_args(code, **kwordargs): return eval(code, kwordargs) >>> code = '2 ** x' >>> eval_with_args(code, x=5) - eval_with_args(code, x=3) 24 >>> code = '3 * x + y' >>> eval_with_args(code, x=5, y=2) - eval_with_args(code, x=3, y=1) 7
c0c8f3361426d86dd5114d0f273a1d8a918b32b7
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/averages-simple-moving-average-2.py
619
3.734375
4
from collections import deque class Simplemovingaverage(): def __init__(self, period): assert period == int(period) and period > 0, "Period must be an integer >0" self.period = period self.stream = deque() def __call__(self, n): stream = self.stream stream.append(n) # appends on the right streamlength = len(stream) if streamlength > self.period: stream.popleft() streamlength -= 1 if streamlength == 0: average = 0 else: average = sum( stream ) / streamlength return average
a158e94229bef8fe5d6d009c4f748f192b4efcdb
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/named-parameters-2.py
3,392
3.65625
4
>>> from __future__ import print_function >>> >>> def show_args(defparam1, defparam2 = 'default value', *posparam, **keyparam): "Straight-forward function to show its arguments" print (" Default Parameters:") print (" defparam1 value is:", defparam1) print (" defparam2 value is:", defparam2) print (" Positional Arguments:") if posparam: n = 0 for p in posparam: print (" positional argument:", n, "is:", p) n += 1 else: print (" <None>") print (" Keyword Arguments (by sorted key name):") if keyparam: for k,v in sorted(keyparam.items()): print (" keyword argument:", k, "is:", v) else: print (" <None>") >>> show_args('POSITIONAL', 'ARGUMENTS') Default Parameters: defparam1 value is: POSITIONAL defparam2 value is: ARGUMENTS Positional Arguments: <None> Keyword Arguments (by sorted key name): <None> >>> show_args(defparam2='ARGUMENT', defparam1='KEYWORD') Default Parameters: defparam1 value is: KEYWORD defparam2 value is: ARGUMENT Positional Arguments: <None> Keyword Arguments (by sorted key name): <None> >>> show_args( *('SEQUENCE', 'ARGUMENTS') ) Default Parameters: defparam1 value is: SEQUENCE defparam2 value is: ARGUMENTS Positional Arguments: <None> Keyword Arguments (by sorted key name): <None> >>> show_args( **{'defparam2':'ARGUMENTS', 'defparam1':'MAPPING'} ) Default Parameters: defparam1 value is: MAPPING defparam2 value is: ARGUMENTS Positional Arguments: <None> Keyword Arguments (by sorted key name): <None> >>> show_args('ONLY DEFINE defparam1 ARGUMENT') Default Parameters: defparam1 value is: ONLY DEFINE defparam1 ARGUMENT defparam2 value is: default value Positional Arguments: <None> Keyword Arguments (by sorted key name): <None> >>> show_args('POSITIONAL', 'ARGUMENTS', 'EXTRA', 'POSITIONAL', 'ARGUMENTS') Default Parameters: defparam1 value is: POSITIONAL defparam2 value is: ARGUMENTS Positional Arguments: positional argument: 0 is: EXTRA positional argument: 1 is: POSITIONAL positional argument: 2 is: ARGUMENTS Keyword Arguments (by sorted key name): <None> >>> show_args('POSITIONAL', 'ARGUMENTS', kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS') Default Parameters: defparam1 value is: POSITIONAL defparam2 value is: ARGUMENTS Positional Arguments: <None> Keyword Arguments (by sorted key name): keyword argument: kwa1 is: EXTRA keyword argument: kwa2 is: KEYWORD keyword argument: kwa3 is: ARGUMENTS >>> show_args('POSITIONAL', 'ARGUMENTS', 'EXTRA', 'POSITIONAL', 'ARGUMENTS', kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS') Default Parameters: defparam1 value is: POSITIONAL defparam2 value is: ARGUMENTS Positional Arguments: positional argument: 0 is: EXTRA positional argument: 1 is: POSITIONAL positional argument: 2 is: ARGUMENTS Keyword Arguments (by sorted key name): keyword argument: kwa1 is: EXTRA keyword argument: kwa2 is: KEYWORD keyword argument: kwa3 is: ARGUMENTS >>> # But note: >>> show_args('POSITIONAL', 'ARGUMENTS', kwa1='EXTRA', kwa2='KEYWORD', kwa3='ARGUMENTS', 'EXTRA', 'POSITIONAL', 'ARGUMENTS') SyntaxError: non-keyword arg after keyword arg >>>
59c1aa53041954828dec498b8c91c262906ec85f
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/strip-comments-from-a-string-3.py
687
3.796875
4
'''Comments stripped with itertools.takewhile''' from itertools import takewhile # stripComments :: [Char] -> String -> String def stripComments(cs): '''The lines of the input text, with any comments (defined as starting with one of the characters in cs) stripped out. ''' def go(cs): return lambda s: ''.join( takewhile(lambda c: c not in cs, s) ).strip() return lambda txt: '\n'.join(map( go(cs), txt.splitlines() )) if __name__ == '__main__': print( stripComments(';#')( '''apples, pears # and bananas apples, pears ; and bananas ''' ) )
47a6664929d3bd1684270fe9aaa355f78f1d3f04
dlaststark/machine-learning-projects
/Programming Language Detection/Experiment-2/Dataset/Train/Python/string-matching.py
246
4
4
"abcd".startswith("ab") #returns True "abcd".endswith("zn") #returns False "bb" in "abab" #returns False "ab" in "abab" #returns True loc = "abab".find("bb") #returns -1 loc = "abab".find("ab") #returns 0 loc = "abab".find("ab",loc+1) #returns 2
76bb0f0ed3cc16e9e8d073c2159b73af2b237de7
ediz12/project_euler_answers
/Power digit sum.py
149
3.53125
4
import time start = time.time() number = 2**1000 total = 0 for i in str(number): total += int(i) print str(total) print str(time.time() - start)
891bc3164a9c63cb5373afa9bb40886897a7ed1b
VisionistInc/advent-of-code-2018
/ct-00/11/AoC11.py
726
3.671875
4
import numpy as np def calculatePowerLevel(x, y, serialNum): rackId = x + 10 powerLevel = int(str((rackId * y + serialNum) * rackId)[-3:-2]) - 5 return powerLevel def findMax(array): max = 0 maxX = -1 maxY = -1 maxLength = None for x in range(298): for y in range(298): power = np.sum(array[x:x+3,y:y+3]) if power > max: max = power maxX = x maxY = y return maxX + 1, maxY + 1 array = np.ndarray(shape=(300, 300), dtype=int, order='C') for x in range(300): for y in range(300): array[x][y] = calculatePowerLevel(x + 1, y + 1, 1308) xMax, yMax = findMax(array) print("%i,%i" % (xMax, yMax))
1e70e37292ee93c319c3e1f42842b9982acc4427
Jusawi/Interview-practice
/validParanthesis.py
930
3.875
4
class Solution: # @param {string} s # @return {boolean} def isValid(self, s): stack=[] for i in s: if i in ['(','[','{']: stack.append(i) else: if not stack or {')':'(',']':'[','}':'{'}[i]!=stack[-1]: return False stack.pop() return not stack #Intuitive method to impress others class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ n = len(s) if n == 0: return True if n % 2 != 0: return False while '()' in s or '{}' in s or '[]' in s: s = s.replace('{}','').replace('()','').replace('[]','') if s == '': return True else: return False
1215bc74ec9edc0701ce6004ccd9031ad6c079ff
The-SIVA/python
/average length of the word in the sentence.py
343
4.15625
4
sentenct_list = input().split() length_of_sentence_list = len(sentenct_list) sum_of_all_words_lengths = 0 for word in sentenct_list: length_of_word = len(word) sum_of_all_words_lengths += length_of_word average_length_of_words_in_sentence = (sum_of_all_words_lengths/length_of_sentence_list) print(average_length_of_words_in_sentence)
9ece6892236fcc2379136ef487ef410b74ba21ad
Elias-gg/205-proj1
/p1t.py
1,177
3.640625
4
from PIL import Image from os import listdir import numpy #source link: http://www.scipy-lectures.org/advanced/image_processing/ #source link: http://cs231n.github.io/python-numpy-tutorial/ #Much of the code was completed on the 31st of august in class with the team #dylan was a major contributor in helping me with this code #I beleive that I hold a major understanding of the project and am very thankful to the rest of my team for all the help they provided def main(): # Create an array to hold all of our images images = []; # For every file inside our working directory... for fileName in (listdir("images\\")): # Open the image and create an array from it, then append that image array into our image list images.append(numpy.array(Image.open("images\\" + fileName))); # Use the built-in median function inside numpy to find the median image, and convert all values to uint8 (0 - 255) stacked = numpy.uint8(numpy.median(images, axis = 0)); # Use Pillow to create an image from an array of data output = Image.fromarray(stacked); # Save it as a PNG for max quality output.save("stacked.png", "PNG"); im = Image.open("stacked.png") main();
99a0d2566d8277286ec0caeb02a00cd429556045
Genxgen/test
/123.py
114
3.5625
4
ws= input('input X=') op= input('input +-*/:') ws2=input('input Y=') x='the dog' print(x) print(int(ws)*int(ws2))
863377dc74e6ea86be7ef0449af2683a5fa740b3
aruzhanss/webPython
/pythonHW/informatics3forK.py
131
3.671875
4
n = int(input()) nums = [] s = 0 for i in range (0, n): number = int(input()) nums.append(number) s = s+number print(s)
e0af3fdf240041c125d41a0b8a5948c9b7aa9d77
aruzhanss/webPython
/pythonHW/informatics3forJ.py
113
3.53125
4
values = [] s = 0 for i in range (0, 100): num = int(input()) values.append(num) s = s+num print(s)
78d43e4790268337ad497149d467ee9c340f8958
slamdunk0414/python
/12.系统编程-多线程/3.解决互相占用bug.py
446
3.609375
4
from threading import Thread,Lock g_num = 0; def test(): global g_num for i in range(1000000): mutex.acquire() g_num += 1; mutex.release() print(g_num) def test2(): global g_num for i in range(1000000): mutex.acquire() g_num += 1; mutex.release() print(g_num) #创建互斥锁 mutex = Lock() t1 = Thread(target=test) t2 = Thread(target=test2) t1.start() t2.start()
1b02f0e08bfdb571196e7f2c3c1c24db898b1b47
slamdunk0414/python
/6.文件操作/1.文件的读写.py
497
3.71875
4
''' 文件读取 f = open('123.txt','r') #第一个参数为文件名 第二个参数为模式 # r为读 如果不存在 会崩溃 # w为写 如果文件不存在 会新建 如果文件存在 则会移除源文件的内容 # a为追加 如果文件不存在 会新建 # 在模式后面添加 + 说明可以读写 #read 如果不添加参数 则读完所有文件 #read(1) 每次读一个字符 print(f.read()) f.close() ''' #文件写入 f = open('456.txt','w') f.write('123456') f.close()
9cf26d07d36eca777778afb6ff16de1773dec6c0
slamdunk0414/python
/10.python高级/8.生成器.py
485
3.953125
4
#列表生成式 a = [x for x in range(10)] print(a) #生成器 第一种方式 b = (x for x in range(10)) #是用next查看生成器里面的元素 print(next(b)) #生成器 第二种方式 def creatNum(): a,b = 0,1 print('开始生成') for x in range(5): yield b a,b = b,a+b creatNum() #加入yield 会成为生成器 不会直接调用 需要是用next a = creatNum() next(a) next会在yield处停止 再次调用yield会从yield处开始继续
6014e844e33aca9eb6da32e905d32cb590ffeb66
slamdunk0414/python
/3.字符串列表数组/8.字典的增删改查.py
335
3.703125
4
info = {'name':'zp'} print(info) #写入没有的 即为增加 info['age'] = 18 print(info) #删除 del del info['age'] print(info) #改 直接改 info['name'] = '123' print(info) info['xxx'] = '1234' #查询 在不缺人是否有key的情况下 不要直接查询 如果不存在key会崩溃 str = info.get('xx') print(str)
6cdf945cb541f5fd8370368dbae3a762e6650858
slamdunk0414/python
/8.面向对象应用/3.单例.py
469
3.640625
4
class Dog: __instance = None __init_flag = False def __new__(cls, name): if cls.__instance: return cls.__instance else: cls.__instance = super().__new__(cls) print('真正的创建') return cls.__instance def __init__(self,new_name): if Dog.__init_flag == False: self.name = new_name Dog.__init_flag = True d = Dog('dd') d2 = Dog('d2') print(d.name)