text
stringlengths
37
1.41M
import math import numpy as np from .uniform.uni_gen import Uni_generator class Binom_gen(): """ Generate binomial distribution """ def __init__(self, m, p): """ Inputs: - m: Integer count of experiments - p: Float probability of success """ self.m = m self.p = p def _combination_(self, n, k): """ Calculate combination from 'n' by 'k' """ res = 1 for i in range(n - k + 1, n + 1): res *= i res /= math.factorial(k) return res def _prob(self, k): """ Calculate probability for appropriate k """ C = self._combination_(self.m, k) res = C * self.p**k * (1-self.p)**(self.m-k) return res def generate(self, N): """ Generate binomial sequence """ # create probability row self._prob_row = np.array([]) for k in range(self.m + 1): self._prob_row = np.append(self._prob_row, self._prob(k)) self._prob_cumsum = np.cumsum(self._prob_row) # create seq belong to uni(0, 1) uni = Uni_generator(1, 2) uni_seq = uni.generate(N, normalized=True) uni_seq = np.array(uni_seq) # calculation elements belong to binomial destribution # fast calculation via numpy: # # sub = uni_seq - self._prob_cumsum.reshape((self._prob_cumsum.shape[0], -1)) # sub[sub >= 0] = -2 # res = np.argmax(sub, axis=0) # vanila algorithm steps = 0 res = [] for i in range(len(uni_seq) - 1, -1, -1): j = 0 el = uni_seq[i] while el - self._prob_cumsum[j] > 0: j += 1 steps += 1 res.append(j) return np.array(res), steps
from it import it def test_equals(): eq = it == 5 assert eq(5), "5 equals 5" assert not eq(4), "4 does not equal 5" def test_it_less_than(): lt = it < 5 assert lt(4), "4 is less than 5" assert not lt(6), "6 is not less than 5" assert not lt(5), "5 is not less than 5" def test_it_less_than_left(): lt = 5 < it assert lt(6), "5 is less than 6" assert not lt(4), "5 is not less than 4" assert not lt(5), "5 is not less than 5" def test_greater_than(): gt = it > 5 assert gt(6), "6 is greater than 5" assert not gt(4), "4 is not greater than 5" assert not gt(5), "5 is not greater than 5" def test_greater_than_left(): gt = 5 > it assert gt(4), "5 is greater than 4" assert not gt(6), "5 is not greater than 6" assert not gt(5), "5 is not greater than 5" def test_less_than_or_equal(): lte = it <= 5 assert lte(4), "4 is less than 5" assert not lte(6), "6 is not less than 5" assert lte(5), "5 is equal to 5" def test_less_than_or_equal_left(): lte = 5 <= it assert lte(6), "5 is less than 5" assert not lte(4), "5 is not less than 4" assert lte(5), "5 is equal to 5" def test_greater_than_or_equal(): gte = it >= 5 assert gte(6), "6 is greater than 5" assert not gte(4), "4 is not greater than 5" assert gte(5), "5 is equal to 5" def test_greater_than_or_equal_left(): gte = 5 >= it assert gte(4), "5 is greater than 4" assert not gte(6), "5 is not greater than 6" assert gte(5), "5 is equal to 5" def test_attribute_access(): class Foo: foo = 12 f = Foo() get_foo = it.foo assert get_foo(f) == 12, "foo is 12" def test_call(): def pair(x, y): return (x, y) call = it(2, 3) ret = call(pair) assert ret == (2, 3) def test_call_kwargs(): def pair(x, y): return (x, y) call = it(y=2, x=3) ret = call(pair) assert ret == (3, 2) def test_key(): d = { 'foo': 'bar' } get_foo = it['foo'] assert get_foo(d) == 'bar' def test_index(): a = [1, 2, 3, 4] get_2 = it[2] assert get_2(a) == 3 def test_slice(): a = [1, 2, 3, 4] get_first_2 = it[:2] assert get_first_2(a) == [1, 2] def test_add_number(): inc = it + 1 assert inc(1) == 2 assert inc(2) == 3 def test_add_string(): suffix = it + '-suffixed' assert suffix('foo') == 'foo-suffixed' def test_add_number_left(): inc = 1 + it assert inc(1) == 2 assert inc(2) == 3 def test_add_string_left(): prefix = 'prefixed-' + it assert prefix('foo') == 'prefixed-foo' def test_subtract(): dec = it - 1 assert dec(1) == 0 assert dec(2) == 1 def test_subtract_left(): diff_12 = 12 - it assert diff_12(6) == 6 assert diff_12(12) == 0 def test_multiplication(): double = it * 2 assert double(1) == 2 assert double(2) == 4 def test_multiplication_left(): double = 2 * it assert double(1) == 2 assert double(2) == 4 def test_division(): halve = it / 2 assert halve(4) == 2 assert halve(8) == 4 def test_division_left(): factor_of_8 = 8 / it assert factor_of_8(2) == 4 assert factor_of_8(4) == 2 def test_floordiv(): halve = it // 2 assert halve(4) == 2 assert halve(5) == 2 def test_floordiv_left(): factor_of_8 = 8 // it assert factor_of_8(2) == 4 assert factor_of_8(3) == 2 def test_modulo(): mod2 = it % 2 assert mod2(4) == 0 assert mod2(5) == 1 def test_modulo_left(): mod_of_8 = 8 % it assert mod_of_8(2) == 0 assert mod_of_8(3) == 2 def test_divmod(): divmod2 = divmod(it, 2) assert divmod2(8) == (4, 0) assert divmod2(5) == (2, 1) def test_divmod_left(): divmod_of_8 = divmod(8, it) assert divmod_of_8(2) == (4, 0) assert divmod_of_8(3) == (2, 2) def test_power(): square = pow(it, 2) assert square(2) == 4 assert square(11) == 121 def test_power_modulo(): square_mod2 = pow(it, 2, 2) assert square_mod2(4) == 0 assert square_mod2(3) == 1 def test_power_left(): power_of_2 = pow(2, it) assert power_of_2(2) == 4 assert power_of_2(3) == 8 def test_lshift(): shift_by_3 = it << 3 assert shift_by_3(4) == 32 assert shift_by_3(10) == 80 def test_lshift_left(): shift_3_by = 3 << it assert shift_3_by(3) == 24 assert shift_3_by(6) == 192 def test_rshift(): shift_by_3 = it >> 3 assert shift_by_3(128) == 16 assert shift_by_3(510) == 63 def test_rshift_left(): shift_128_by = 128 >> it assert shift_128_by(3) == 16 assert shift_128_by(2) == 32 def test_and(): and4 = it & 4 assert and4(4) == 4 assert and4(2) == 0 def test_and_left(): four_and = 4 & it assert four_and(4) == 4 assert four_and(2) == 0 def test_xor(): xor3 = it ^ 3 assert xor3(5) == 6 assert xor3(12) == 15 def test_xor_left(): twelve_xor = 12 ^ it assert twelve_xor(3) == 15 assert twelve_xor(12) == 0 def test_or(): or4 = it | 4 assert or4(8) == 12 assert or4(16) == 20 def test_or_left(): four_or = 4 | it assert four_or(8) == 12 assert four_or(16) == 20 def test_neg(): neg = -it assert neg(12) == -12 assert neg(-4) == 4 def test_pos(): pos = +it assert pos(12) == 12 assert pos(-4) == -4 def test_invert(): inv = ~it assert inv(12) == -13 assert inv(-12) == 11
numbers = [2, 3, 4, 6, 3, 4, 6, 1] # append adds to the end of the list # numbers.append(20) # insert allows us to insert new items at the index we set # second value is the value we wish to add to the list # numbers.insert(0, 10) # .remove will remove the value we want which we pass through # numbers.remove(5) # to remove all items in the list # numbers.clear() # pop remove last item in a list # numbers.pop() # print(numbers.index(5)) # print(50 in numbers) # will return a boolean # count will give you how many times a value is within a list # print(numbers.count(5)) # sort will sort our list # numbers.sort() # numbers.reverse() # copies list # numbers2 = numbers.copy() # print(numbers) for number in numbers: if numbers.count(number) > 1: numbers.remove(number) print(numbers) uniques = list() for number in numbers: if number not in uniques: uniques.append(number) print(uniques)
def emoji_convertor(sentence): emojis = { ":)": "😀", ":(": "☹️", ":'(": "😢", ":|": "😐", ":p": "😜" } output = "" words = sentence.split(" ") for word in words: output += emojis.get(word, word) + " " return output sentence = input('>') print(emoji_convertor(sentence))
# -*- coding: utf-8 -*- """ Created on Fri Mar 26 09:50:10 2021 @author: Carl-Michael """ def prime_factors(number): #print('works') factors = list() divisor = 2 while divisor <= number: if number % divisor == 0: factors.append(divisor) number = number / divisor else: divisor += 1 print(factors) prime_factors(120)
import nltk f = open('output.txt').read() wtokens = nltk.word_tokenize(f) wtokens = [word.lower() for word in wtokens if word.isalpha()] # Word Tokenization. Words are separated from each other. for t in wtokens: print(t)
#!/usr/bin/env python # coding: utf-8 # In[ ]: # collections--- in python # deque ---is double ended queue # append, appendleft, extend, extendleft, pop , popleft, # FIFO : First in First out(queue) # LIFO : drque # Counter - Gives you a count of each items in the container with key value structure # OrderedDict # ChainMap # datetime # In[ ]: import collections dq = collections.deque([4,5,6]) print(dq) dq.append(7) print(dq) dq.appendleft(3) print(dq) dq.extend([8,9]) print(dq) dq.extendleft([2,1,0]) #[1,0] print(dq) dq.insert(4,-10000) print(dq) dq.pop() print(dq) dq.popleft() print(dq) # In[ ]: a = [1,2,3,4] a = collections.deque(a) a.extendleft(['A','B']) print(a) # In[ ]: L1 = ['x','y','z','z','z','z','x','z'] print(collections.Counter(L1)) S1 = @ print(collections.Counter(S1)) # most common #print(collections.Counter(L1).most_common(1)) #elements---iterable object E = collections.Counter(L1) for i in E.elements(): print(i) # In[ ]: # OrderDict ----order of insertion in Dict Py 2.7 was not taken care of # but in 3 and above it there. a = {'apple':3,'mango':4} OD = OrderedDict(a) OD # In[ ]: OD.keys() OD.values() # In[ ]: from collections import OrderedDict OD = OrderedDict({ 'Randy Orton': 'Red', 'Dwayne Johnson' : 'Blue', 'Jhon Cena':'Red' }) print(OD) OD.move_to_end('Dwayne Johnson') print(OD) # In[ ]: from collections import ChainMap d1 = {'a':1,'b':2} d2 = {'c':1,'d':2} d3 = {'e':1,'f':2} C = ChainMap(d1,d2,d3) C # In[ ]: FMCG = {'soap':3,'shampoo':4} PANTRY = {'floor':5,'lentils':6} OI = {'TV':1,'Batteries':2} C = collections.ChainMap(OI,FMCG,PANTRY) print(C) print(list(C.keys())) print(list(C.values())) # new_child c= {'zshoe':2,'socks':3} C = C.new_child(c) print(C) # In[ ]: # substring and string String = 'my name is bikash s' String.count('s') # In[ ]: # datetime HH:MM:SS hh:mm:ss DD/MM/YY # inside datetime i have few important classes # time # date # datetime # In[ ]: import datetime as dt x = dt.datetime.now() x print(x.month) print(x.day) y = dt.date.today() print(y) from datetime import time z = time(hour = 8, minute = 51, second = 30) print(z) from datetime import datetime z1 = datetime(2021,7,24,8,54,30) print(z1) # date(y,m,d) # time(h,m,s,microseconds) # datetime(y,m,d,h,minute,s,microseconds) import datetime as dt # In[ ]: import datetime as dt # Write a Python script to display the various Date Time formats. # a) Current date and time # strftime is used to format our time into string format print(dt.datetime.now()) # b) Current year D = dt.date.today() D.strftime("%Y") #string format time # c) Month of year D.strftime("%m") # d) Week number of the year D.strftime("%W") # e) Weekday of the week print(D.strftime("%A")) # f) Day of year D.strftime("%j") # g) Day of the month D.strftime("%d") # h) Day of week D.strftime("%w") # In[ ]: from collections import ChainMap x = {'Age': 10, 'Name': 'Vinii'} y = {'Gender': 'Female'} X = ChainMap(x, y) print ("Values associated with the keys of Chainmap: ") print (list(X.maps)) X # In[ ]: contestants = { 'Randy Orton': 'Red', 'Dwayne Johnson' : 'Blue' } contestants['Jhon Cena'] = 'Red' contestants # In[ ]: from collections import OrderedDict OD = OrderedDict({ 'Randy Orton': 'Red', 'Dwayne Johnson' : 'Blue', 'Jhon Cena':'Red' }) print(OD) OD.move_to_end('Dwayne Johnson') print(OD) OrderedDict(reversed(list(OD.items()))) # In[ ]: Write a Python script to display the various Date Time formats. a) Current date and time b) Current year c) Month of year d) Week number of the year e) Weekday of the week f) Day of year g) Day of the month h) Day of week # In[ ]: #There is a difference between datetime.strp[arse]time() and datetime.strf[ormat]time(). #The first one, strptime() allows you to create a date object from a string source, #provided you can tell it what format to expect: strDate = "11-Apr-2019_09:15:42" dateObj = datetime.strptime(strDate, "%d-%b-%Y_%H:%M%S") print(dateObj) #The second one, strftime() allows you to export your date object to a string in the format #of your choosing: dateObj = datetime(2019, 4, 11, 9, 19, 25) strDate = dateObj.strftime("%m/%d/%y %H:%M:%S") print(strDate) # In[ ]: from datetime import datetime date_object = datetime.strptime('July 1 2014 2:43PM', '%B %d %Y %I:%M%p') print(date_object) # In[ ]: OI = {'TV':1,'Batteries':2} FMCG = {'soap':3,'shampoo':4} PANTRY = {'floor':5,'lentils':6} C = collections.ChainMap(OI,FMCG,PANTRY) print(C) print(list(C.keys())) list(C.values())
class RingBuffer: def __init__(self, capacity): self.capacity = capacity self.current = 0 self.storage = [None]*capacity def append(self, item): # Set the passed in item to evaluate to the current item in storage. self.storage[self.current] = item # If the current value is less than the overall capacity. if self.current < self.capacity - 1: # Add it to the list self.current += 1 else: # Otherwise set current value to 0 self.current = 0 def get(self): list = [] for value in self.storage: if value is not None: list.append(value) return list
def nombreDivisibles (liste1, n): listeDivisible = [] for each in liste1 : if (each % n == 1): listeDivisible.append(each) return listeDivisible; liste1 = [1,2,3,4,5] n = 2 resultat = nombreDivisibles(liste1,n) print (resultat)
class Poly : def __init__(self, x,y,z): self.x = x self.y = y self.z = z def coeff(self): coeff = [self.x,self.y,self.z] return coeff def evalue(self,x): resultat = self.x+self.y*x+self.z*(x*x) return resultat p = Poly(3,4,-2) print(p.coeff()) print(str(p.evalue(2))) print(list(enumerate(p.coeff())))
def toutEnMajuscule(L): resultat = [] for each in L: resultat.append(each.upper()) return resultat L = ["Python", "est", "un", "langage", "de", "programmation"] print(toutEnMajuscule(L))
class CompteBancaire : def __init__(self, nom, solde=0): self.nom = nom self.solde = solde def __repr__(self): return {"compte de ":self.nom,"solde ":self.solde} def retrait(self,nb): self.solde = self.solde - nb def depot(self,nb): self.solde = self.solde + nb compte1 = CompteBancaire('jean',1000) compte2 = CompteBancaire('Marc') compte1.retrait(200) print(compte1.__repr__()) compte2.depot(500) print(compte2.__repr__())
s = input("Saisir une phrase: ") if (s == ""): print ("la chaine de caractere est vide ") s = list(s) if (not s): print("la liste est vide")
#!/usr/bin/env python import math import numpy as np from PIL import Image import tifffile # ************************************************************* # * From Photography Notebook * # ************************************************************* # ======================= white_balance ======================= # Input: # I: an RGB image -- a numpy array of shape (height, width, 3) # black_level: an RGB offset to be subtracted from all the pixels # gray: the RGB color of a gray object (includes the black level) # Output: # The corrected image: black level subtracted, then color channels scale to make gray come out gray def white_balance(I, black_level, gray): # A3TODO: Complete this function new_gray = gray - black_level balance = (I - [[black_level]]) * [[new_gray[1] / new_gray]] return (balance / (2**16 - 1)).astype(np.float32) # Replace this with your implementation # ======================= color_transform ======================= # Input: # I: an RGB image -- a numpy array of shape (height, width, 3) # M: a 3x3 matrix, to be multiplied with each RGB triple in I # Output: # The image with each RGB triple multiplied by M def color_transform(I, M): # A3TODO: Complete this function transformed = np.tensordot(I, M, axes=(2, 1)) return I # Replace this with your implementation # ************************************************************* # * From Distortion Notebook * # ************************************************************* # ======================= shift_image_to_left ======================= # Input: # img: 2D numpy array of a grayscale image # k: The number of units/pixels to be shifted to the left (you can assume k < width of image) # Output: # A 2D array of img shifted to the left by k pixels # For points that fall out of range on the right side, repeat the rightmost pixel. def shift_image_to_left(img, k): new_img = np.zeros(img.shape, np.uint8) length = img.shape[1] height = img.shape[0] for i in range(0, height): for j in range(0, length): if (j+k < length): new_img[i][j] = img[i][j+k] else: new_img[i][j] = img[i][length-1] return new_img # ======================= rotate_image ======================= # Input: # img: 2D numpy array of a grayscale image # k: The angle (in degrees) to be rotated counter-clockwise around the image center # interp_mode: 0 for nearest neighbor, 1 for bilinear # Output: # A 2D array of img rotated around the original image's center by k degrees def rotate_image(img, k, interp_mode): new_img = np.zeros(img.shape, np.uint8) # A3TODO: Complete this function center_x = img.shape[1] // 2 center_y = img.shape[0] // 2 length = img.shape[1] height = img.shape[0] rad = np.radians(k) if (interp_mode == 0): #nearest neighbor for i in range(0, height): for j in range(0, length): row = round(((j - center_x) * np.cos(rad)) - ((i - center_y) * np.sin(rad)) + center_x) col = round(((j - center_x) * np.sin(rad)) + ((i - center_y) * np.cos(rad)) + center_y) if (row < length and row >= 0 and col < height and col >= 0): new_img[i][j] = img[col][row] return new_img else: #bilinear interpolation for i in range(0, height): for j in range(0, length): row = ((j - center_x) * np.cos(rad)) - ((i - center_y) * np.sin(rad)) + center_x col = ((j - center_x) * np.sin(rad)) + ((i - center_y) * np.cos(rad)) + center_y a = col - np.floor(col) b = row - np.floor(row) col0 = np.floor(col).astype(np.int) row0 = np.floor(row).astype(np.int) col1 = np.ceil(col).astype(np.int) row1 = np.ceil(row).astype(np.int) #q00 if (col0 >= 0 and col0 <= height - 1 and row0 >= 0 and row0 <= length - 1): q00 = img[col0][row0] else: q00 = 0 #q01 if(col1 >= 0 and col1 <= height - 1 and row0 >= 0 and row0 <= length - 1): q01 = img[col1][row0] else: q01 = 0 #q10 if(col0 >= 0 and col0 <= height - 1 and row1 >= 0 and row1 <= length - 1): q10 = img[col0][row1] else: q10 = 0 #q11 if(col1 >= 0 and col1 <= height - 1 and row1 >= 0 and row1 <= length - 1): q11 = img[col1][row1] else: q11 = 0 new_img[i][j] = ((1 - a) * (1 - b) * q00) + ((1 - a) * b * q10) + (a * (1 - b) * q01) + (a * b * q11) return new_img # ======================= undistort_image ======================= # Input: # img: A distorted image, with coordinates in the distorted space # k1, k2: distortion model coefficients (see explanation above) # M: affine transformation from pixel coordinates to distortion-model coordinates # interp_mode: 0 for nearest neighbor, 1 for bilinear # Output: # An undistorted image, with pixels in the image coordinates # Write down the formula for calculating the distortion model first (see exercise above) # Put black in for points that fall out of bounds def undistort_image(img, k1, k2, M, interp_mode): Mi = np.linalg.inv(M) output = np.zeros_like(img) # A3TODO: Complete this function length = output.shape[1] height = output.shape[0] for i in range(0, height): for j in range(0, length): dist_coord = Mi @ np.array([j, i, 1]) dist_i = dist_coord[1] dist_j = dist_coord[0] r = np.sqrt(dist_i ** 2 + dist_j ** 2) sr = 1 + k1 * (r ** 2) + k2 * (r ** 4) dist_x_coord = sr * dist_j dist_y_coord = sr * dist_i new_img_xy = M @ np.array([dist_x_coord, dist_y_coord, 1]) if(interp_mode == 0): #nearest_neighbor new_img_x = round(new_img_xy[0]) new_img_y = round(new_img_xy[1]) if (new_img_x < length and new_img_x >= 0 and new_img_y < height and new_img_y >= 0): output[i][j] = img[new_img_y][new_img_x] else: #binary interpolation version of undistort_image row = new_img_xy[0] col = new_img_xy[1] a = col - np.floor(col) b = row - np.floor(row) col0 = np.floor(col).astype(np.int) row0 = np.floor(row).astype(np.int) col1 = np.ceil(col).astype(np.int) row1 = np.ceil(row).astype(np.int) #q00 if (col0 >= 0 and col0 <= height - 1 and row0 >= 0 and row0 <= length - 1): q00 = img[col0][row0] else: q00 = 0 #q01 if(col1 >= 0 and col1 <= height - 1 and row0 >= 0 and row0 <= length - 1): q01 = img[col1][row0] else: q01 = 0 #q10 if(col0 >= 0 and col0 <= height - 1 and row1 >= 0 and row1 <= length - 1): q10 = img[col0][row1] else: q10 = 0 #q11 if(col1 >= 0 and col1 <= height - 1 and row1 >= 0 and row1 <= length - 1): q11 = img[col1][row1] else: q11 = 0 output[i][j] = ((a - 1) * (b - 1) * q00) + ((1 - a) * b * q10) + (a * (1 - b) * q01) + (a * b * q11) return output # ************************************************************* # * From Convolution Notebook * # ************************************************************* # ======================= gen_gaussian_filter ======================= # Input: # dim: size of the filter in both x and y direction # sigma: standard deviation of the gaussian filter # Output: # A 2-dimensional numpy array of size dim*dim # (Note that the array should be normalized) # Hint: Use linspace or mgrid from numpy def gen_gaussian_filter(dim, sigma): # A3TODO: Complete this function center = dim // 2 f = np.zeros([dim, dim]) for i in range(0, dim): for j in range(0, dim): f[i,j] = np.exp(-((i-center)**2 + (j-center)**2)/(2* sigma**2)) / (2 * np.pi * sigma**2) return f # ======================= convolve ======================= # Input: # I: A 2D numpy array containing pixels of an image # f: A squared/non-squared filter of odd/even-numbered dimensions # Output: # A 2D numpy array resulting from applying the convolution filter f to I # All the entries of the array should be of type uint8, and restricted to [0,255] # You may use clip and astype in numpy to enforce this # Note: When convolving, do not operate on the entries outside of the image bound, # i.e. clamp the ranges to the width and height of the image # Tie-breaking: If f has an even number of dimensions in some direction (assume the dimension is 2r), # sweep through [i-r+1, i+r] (i.e. length of left half = length of right half - 1) # With odd # of dimensions (2r+1), you would sweep through [i-r, i+r]. def convolve(I, f): output = np.zeros_like(I).astype(np.float64) image_height = I.shape[0] image_length = I.shape[1] f_height = f.shape[0] f_length = f.shape[1] for p in range(0, image_length): for q in range(0, image_height): s = 0.0 for i in range(0, f_height): for j in range(0, f_length): if ((q - f_height // 2 + i) < image_height and (q - f_height // 2 + i) >= 0 and (p - f_length // 2 + j) >= 0 and (p - f_length // 2 + j) < image_length): s = s + f[i][j] * I[q - f_height // 2 + i][p - f_length // 2 + j] output[q][p] = s return np.clip(output, 0, 255).astype(np.uint8) # ======================= convolve_sep ======================= # Input: # I: A 2D numpy array containing pixels of an image # f: A squared/non-squared filter of odd/even-numbered dimensions # Output: # A 2D numpy array resulting from applying the convolution filter f to I # All the entries of the array should be of type uint8, and restricted to [0,255] # You may use clip and astype in numpy to enforce this # Note: When convolving, do not operate on the entries outside of the image bound, # i.e. clamp the ranges to the width and height of the image in the for loop # Tie-breaking: If f has an even number of dimensions in some direction (assume the dimension is 2r), # sweep through [i-r+1, i+r] (i.e. length of left half = length of right half - 1) # With odd # of dimensions (2r+1), you would sweep through [i-r, i+r]. # You will convolve with respect to the direction corresponding to I.shape[0] first, then I.shape[1] def convolve_sep(I, f): output = np.zeros_like(I) image_height = I.shape[0] image_length = I.shape[1] f_height = f.shape[0] f_length = f.shape[1] ctr_row = f.shape[0] // 2 ctr_col = f.shape[1] // 2 f_along_row = f[:][ctr_row-1] / np.sum(f[:][ctr_row-1]) f_along_col = f[ctr_col-1][:] / np.sum(f[ctr_col-1][:]) temp = np.zeros_like(I) for p in range(0, image_length): for q in range(0, image_height): s = 0.0 for i in range(0, f_height): if ((q - f_height // 2 + i) < image_height and (q - f_height // 2 + i) >= 0): s = s + f_along_row[i] * I[q - f_height // 2 + i][p] temp[q][p] = np.clip(s, 0, 255).astype(np.uint8) for x in range(0, image_length): for y in range(0, image_height): t = 0.0 for j in range(0, f_length): if ((x - f_length // 2 + j) >= 0 and (x - f_length // 2 + j) < image_length): t = t + f_along_col[j] * temp[y][x - f_length // 2 + j] output[y][x] = np.clip(t, 0, 255).astype(np.uint8) return np.clip(output, 0, 255).astype(np.uint8) # ======================= unsharp_mask ======================= # This function essentially subtracts a (scaled) blurred version of an image from (scaled version of) itself # Input: # I: A 2D numpy array containing pixels of an image # sigma: Gassian std.dev. for blurring # w: Sharpening weight # Output: # A sharpened version of I def unsharp_mask(I, sigma, w): # A3TODO: Complete this function output = np.zeros_like(I) r = np.ceil(3 * sigma).astype(np.int) gaussian_blur = gen_gaussian_filter(2*r, sigma) blurred = convolve_sep(I, gaussian_blur) output = np.clip((1 + w) * I - w * blurred, 0, 255) return output.astype(np.uint8)
''' Shreyash Shrivastava 1001397477 CSE 6363 ''' import math # Height Weight Age Class D = [ ((170, 57, 32),'W'), ((192, 95, 28),'M'), ((150, 45, 30), 'W'), ((170, 65, 29), 'M'), ((175, 78, 35), 'M'), ((185, 90, 32), 'M'), ((170, 65, 28), 'W'), ((155, 48, 31), 'W'), ((160, 55, 30), 'W'), ((182, 80, 30), 'M'), ((175, 69, 28), 'W'), ((180, 80, 27), 'M'), ((160, 50, 31), 'W'), ((175, 72, 30), 'M'), ] # Taking input from user data_point = input('Enter the data point, separeted with a comma: Height, Weight\n') data_point = list(data_point) X =[] for x in data_point: X.append(x) # Probability of class W no_of_w = 0 for x in D: if x[1] == 'W': no_of_w +=1 prob_of_w = (float(no_of_w)/float(len(D))) # Probability of class M no_of_m = 0 for x in D: if x[1] == 'M': no_of_m +=1 prob_of_m = (float(no_of_w)/float(len(D))) # Creating a classifier from the training data # male -> mean(height), sigma(height) .. # female -> mean(height), sigma(height) .. # @mean takes three arguments # arg1 = Data set # arg2 = gender as M or W # arg3 = classifier as height, weight or age def mean(D,gender,classifier): fetch = 0 if classifier == 'height': fetch = 0 if classifier == 'weight': fetch = 1 if classifier == 'age': fetch = 2 total_sum = 0 data_sum = 0 # data sum for x in D: if x[1] == gender: data_sum += x[0][fetch] # number of data points dp= 0 for x in D: if x[1] == gender: dp +=1 # total sum for x in D: total_sum += x[0][fetch] return float(float(data_sum)/float(dp)) # @variance takes three arguments # arg1 = Data set # arg2 = gender as M or W # arg3 = classifier as height, weight or age def variance(D,gender,classifier): fetch = 0 if classifier == 'height': fetch = 0 if classifier == 'weight': fetch = 1 if classifier == 'age': fetch = 2 mu = float(mean(D,gender,classifier)) var = 0 var = float(var) for x in D: if x[1] == gender: var += math.pow((float(x[0][fetch] - mu)),2) dp= 0 for x in D: if x[1] == gender: dp +=1 #return var var = float(float(var)/float(dp)) return float(math.sqrt(var)) # male variable holds the gaussian distribution assumption for male and calculates mean and variance male = [mean(D,'M','height'),variance(D,'M','height'),mean(D,'M','weight'),variance(D,'M','weight'), mean(D,'M','age'), variance(D,'M','age'),] # female variable holds the gaussian distribution assumption for male and calculates mean and variance female = [mean(D,'W','height'),variance(D,'W','height'),mean(D,'W','weight'),variance(D,'W','weight'), mean(D,'W','age'), variance(D,'W','age'),] def calculateProbability(x, mean, stdev): exponent = float(math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))) return (1 / (float(math.sqrt(2*math.pi) * stdev))) * exponent # p(height|male)* p(wight|male) * p(age|male) from calculateProbability print('P(height|M)', calculateProbability(X[0],male[0],male[1])) print('P(Weight|M)', calculateProbability(X[1],male[2],male[3])) print('P(Age|M)', calculateProbability(X[2],male[4],male[5])) print('\n') print('P(height|W)', calculateProbability(X[0],female[0],female[1])) print('P(Weight|W)', calculateProbability(X[1],female[2],female[3])) print('P(Age|W)', calculateProbability(X[2],female[4],female[5])) p_m_x = calculateProbability(X[0],male[0],male[1]) * calculateProbability(X[1],male[2],male[3]) * calculateProbability(X[2],male[4],male[5]) * prob_of_m p_w_x = calculateProbability(X[0],female[0],female[1]) * calculateProbability(X[1],female[2],female[3]) * calculateProbability(X[2],female[4],female[5]) * prob_of_w print('\n') print('P(M|X) ',p_m_x) print('P(W|X) ',p_w_x) print('\n') if p_m_x > p_w_x: print('Predicted as : Male') else: print('Predicted as : Female')
#!/usr/bin/python number = 20 guess = int(input('Enter an integer: ')) if guess == number: print ('you guessed it.') elif guess < number: print('No, it is higher than that') else: print('No, it is lower than that')
# Подключение библиотек import tkinter as tk from tkinter import ttk from tkinter import messagebox #Создание основного фрейма root = tk.Tk() root.title('Список дел') root.geometry("500x400") #Инициализация массива для добавления заданий tasks = [] #Функция добавления задания def addTask(): word = input_entry.get() if len(word)==0: messagebox.showinfo('Отсутствуют данные', 'Введите задачу') else: tasks.append(word) listUpdate() input_entry.delete(0,'end') #Функция удаления задания def delOne(): try: val = list_box.get(list_box.curselection()) if val in tasks: tasks.remove(val) listUpdate() except: messagebox.showinfo('Невозможно удалить', 'Не выбрана задача') #Фукция обновления листа с заданиями def listUpdate(): clearList() for i in tasks: list_box.insert('end', i) #Функция очистки списка def clearList(): list_box.delete(0,'end') #Функция выхода из приложения def bye(): answer = messagebox.askyesno(title="Выход", message="Вы действительно хотите выйти?") if answer: root.destroy() #Инициализация UI компонентов title = ttk.Label(root, text = 'Список дел') input_label = ttk.Label(root, text='Введите задачу: ') input_entry = ttk.Entry(root, width=20) list_box = tk.Listbox(root, height=15, selectmode='SINGLE') add_btn = ttk.Button(root, text='Добавить', width=20, command=addTask) del_btn = ttk.Button(root, text='Удалить', width=20, command=delOne) exit_btn = ttk.Button(root, text='Выход', width=20, command=bye) input_label.place(x=20, y=40) input_entry.place(x=20, y=60) add_btn.place(x=20, y=90) del_btn.place(x=20, y=120) exit_btn.place(x=20, y =305) title.place(x=20, y=10) list_box.place(x=260, y=60) #Главный цикл обработки событий root.mainloop()
# coding: UTF-8 # No.? Python Study 2015/07/? # タプル (変更できない) a = (2, 5, 8) # len + * [] print len(a) # 3 print a * 3 # a[2] = 10 変更できない # タプル <> リスト b = list(a) print b c = tuple(b) print c
import numpy as np x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; print(x) # 2차원 배열 생성 후 출력 arr_x = np.array(x); print(arr_x) # Numpy의 ndarray로 변환 후 출력 arr_y = np.eye(3); print(arr_y) # 주 대각 성분이 1 나머지가 0인 단위 행렬 생성 후 출력 dot_xy = np.add(arr_x, arr_y); print(dot_xy) # 행렬 덧셈
class Country(): """A model for a country """ def __init__(self, name, factor_endowments, technologies): """Initialize instance variables. :param name: country name :type name: str :param factor_endowments: country's factor endowments :type factor_endowments: dict :param technologies: country's unit labor requirements for trade goods :type technologies: dict :return None: """ self.name = name self.factor_endowments = factor_endowments self.technologies = technologies
nums = [10, 20, 30, 40] for i in range(len(nums)): nums[i] = nums[i] * 10 print(nums)
# def check(n): # # for i in range(len(n)): # if n[i]%2==0: # print("this even number:",n[i]) # else: # print("this number is odd:",n[i]) # n=[10,20,30,50,60,77] # check(n) # def count1(string,string2="a"): # count=0 # for i in string: # if i in string2: # count+=1 # return count # string="aaavenkatesh" # print(count1(string,string2="e")) def fib(n): list1 = [0, 1] a = 0 b = 1 for i in range(0, n): b = a + b a = b - a list1.append(b) return list1 print(fib(10))
# str1="venkayesh" # count=0 # for i in str1: # count=count+1 # new=str1[0:2]+str1[-2:] # print(new) str1=["venkatesh","sai","reddy","manoj","venkatesh"] str2="venkatesh" count=0 for i in range(len(str1)): if str2==str1[i]: count+=1 print(count)
class rectangle: def __init__(self,breadth,height): self.breadth=breadth self.height=height def area(self): return self.breadth*self.height obj=rectangle(10,20) print(obj.breadth) print(obj.height) print(obj.area())
from tkinter import * from PIL import ImageTk , Image root=Tk() root.title("ESCAPE ROOM GAME") books= ImageTk.PhotoImage(Image.open("book1.jpg")) clocks2= ImageTk.PhotoImage(Image.open("clocks1.jpg")) key1= ImageTk.PhotoImage(Image.open("key1.jpg")) key2= ImageTk.PhotoImage(Image.open("key2.jpg")) key3= ImageTk.PhotoImage(Image.open("key3.jpg")) mainroom= ImageTk.PhotoImage(Image.open("mainroom.jpg")) maze1= ImageTk.PhotoImage(Image.open("maze.jpg")) switchoff1= ImageTk.PhotoImage(Image.open("switchoff1.jpg")) switchon1= ImageTk.PhotoImage(Image.open("switchon1.jpg")) txt='''This is the Escape room. Here, in this game you are locked in a room, filled with items you can interact with, and all you have to do is explore all the objects and find the clues and connect the dots to find the key and open the door to escape the room. The rules are simple, there is a broken key on the table near the door, one of three pieces.Find the remaining two, and combine them to get a whole key, and open the door!!''' booktxt="Pages on war of China? Must contain something important" clockstxt1="Is it 12:30??" switchontxt="What happens when I switch it off" emptyboardtxt="Toggle the switches it might help" labelText = StringVar() labelText.set(txt) my_label_image=Label(image=mainroom) my_label_image.grid(row=10,column=10) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) def books_shelf_open(): global my_label_image global my_label_text global bookstxt global books my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=books) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(booktxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) def brokenkey_open(): global my_label_image global my_label_text global bookstxt global key1 my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=key1) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(booktxt) my_label_text=Label() my_label_text.grid(row=10,column=800) def clocks_open(): global my_label_image global my_label_text global clockstxt1 global clocks2 my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=clocks2) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(clockstxt1) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) def back_mainroom(): global my_label_image global my_label_text global mainroom global txt my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=mainroom) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(txt) my_label_text=Label() my_label_text.grid(row=10,column=800) def switchon_open(): global my_label_image global my_label_text global switchontxt global switchon1 my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=switchon1) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(switchontxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) def switchoff_open(): global my_label_image global my_label_text #global switchontxt global switchoff1 my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=switchoff1) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(switchontxt) my_label_text=Label() my_label_text.grid(row=10,column=800) def empty_open(): global my_label_image global my_label_text global emptyboardtxt global switchoff1 my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label() my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(emptyboardtxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) def maze_open(): global my_label_image global my_label_text global maze1 #global switchoff1 my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label(image=maze1) my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(emptyboardtxt) my_label_text=Label() my_label_text.grid(row=10,column=800) u=0 donetxt="Code Accepted!" notdonetxt="INCORRECT CODE" entertxt=" ENTER CODE IN SECRET TEXT BOX BELOW" def take(): global u c=b.get() if c=="123055": u=1 def enter(): global my_label_image global my_label_text my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label() my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(entertxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) def check(): global my_label_image global my_label_text global donetxt global notdonetxt global u if u ==0: my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label() my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(notdonetxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) else: my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label() my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(donetxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) unlocktxt='''Congratualtions You have completed all the puzzles and unlocked the main door ! Well played!!!''' locktxt='''Not yet! You have not completed all the puzzles! ''' def done(): global my_label_image global my_label_text global unlocktxt global locktxt if u ==0: my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label() my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(locktxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) else: my_label_image.grid_forget() my_label_text.grid_forget() my_label_image=Label() my_label_image.grid(row=10,column=10) labelText = StringVar() labelText.set(unlocktxt) my_label_text=Label(textvariable=labelText) my_label_text.grid(row=10,column=800) #Category Buttons bookshelf = Button(root, text = 'BOOK SHELF', bd = '5' , command=books_shelf_open) bookshelf.place(x=0,y=405) clocks = Button(root, text = 'CLOCKS', bd = '5',command=clocks_open) clocks.place(x=130,y=405) emptyswitch = Button(root, text = 'EMPTY BOARD ', bd = '5',command=empty_open ) emptyswitch.place(x=250,y=405) emptyswitch = Button(root, text = 'SWITCH ON', bd = '5',command=switchon_open) emptyswitch.place(x=250,y=455) emptyswitch = Button(root, text = 'SWITCH OFF', bd = '5',command=switchoff_open) emptyswitch.place(x=250,y=505) maze = Button(root, text = 'MAZE', bd = '5',command=maze_open) maze.place(x=380,y=405) locker = Button(root, text = 'LOCKER', bd = '5', command=enter) locker.place(x=450,y=405) checkval=Button(root,text='CHECK',bd='5',command=check) checkval.place(x=450,y=450) brokenkey = Button(root, text = 'BROKEN KEY', bd = '5',command=brokenkey_open) brokenkey.place(x=550,y=405) maindoor = Button(root, text = 'MAIN DOOR', bd = '5',command=done) maindoor.place(x=650,y=405) back = Button(root, text = 'BACK TO MAIN ROOM', bd = '5' , command=back_mainroom) back.place(x=1000,y=405) secret=Label(text="Secret TEXTBOX") secret.place(x=900,y=505) b=StringVar() text=Entry(textvariable=b) text.place(x=1000, y=505) unlock=Button(root, text="UNLOCK",bd='5',command=take) unlock.place(x=1150,y=505) root.mainloop()
import openpyxl def make_invoice(invoice_id): """ Receives an invoice id as parameter, obtains invoice data from spreadsheet 'sales_data.xlsx', and appends an invoice with the following format to 'invoice.txt': Andrew Wang (client ID: 124) Invoice # 266 Invoice date 2019-04-30 Quantity Item Unit price Line total -------- ---- ---------- ---------- 9 Pen 70.00 $ 630.00 2 Stapler 40.00 $ 80.00 1 Binder 10.00 $ 10.00 ---------- TOTAL $ 720.00 ============================================================ """ # - Open 'sales_data.xlsx', obtain iterators for worksheets of interest # - Use 'invoice_id' to obtain customer id and invoice date # - Use customer id to obtain customer's name # # Create invoice: # - add header showing customer name, id and invoice id, date # - initialise invoice total to 0 # - loop through line items for the invoice with id 'invoice_id' # * determine product id, units sold from the line item # * use product id to obtain product name, unit price # * calculate line total (units sold * unit price) # * add line total to invoice total # * add a line to invoice showing units sold, product name, # unit price, and line total # - add footer showing invoice total wb = openpyxl.load_workbook('sales_data.xlsx') customers_ws = wb['customers'] invoices_ws = wb['invoices'] line_items_ws = wb['invoice line items'] products_ws = wb['products'] invoice_txt = '' # stores text of the entire invoice customer_name = None customer_id = None invoice_date = None invoice_total = 0 products = {} # dictionary of products line_items = {} # dictionary of invoice line items # Obtain customer id and invoice date from 'invoices' worksheet for i in range(2, invoices_ws.max_row + 1): if not (invoices_ws.cell(i, 1).value is None): if (invoice_id == invoices_ws.cell(i, 1).value): customer_id = invoices_ws.cell(i, 3).value invoice_date = invoices_ws.cell(i, 2).value\ .strftime('%Y-%m-%d') if customer_id is None: return # Obtain customer name from 'customers' worksheet for i in range(2, customers_ws.max_row + 1): if not (customers_ws.cell(i, 1).value is None): if (customer_id == customers_ws.cell(i, 1).value): customer_name = customers_ws.cell(i, 2).value + \ ' ' + customers_ws.cell(i, 3).value # Iterate over rows in 'products' worksheet, build dictionary of # product name and unit price, with product ID as key for i in range(2, products_ws.max_row + 1): if not (products_ws.cell(i, 1).value is None): products[products_ws.cell(i, 1).value] = \ {'name': products_ws.cell(i, 2).value, 'price': products_ws.cell(i, 3).value} # Iterate over rows in 'invoice line items' worksheet, build dictionary of # units sold, with product ID as key for i in range(2, line_items_ws.max_row + 1): if not (line_items_ws.cell(i, 1).value is None): if (invoice_id == line_items_ws.cell(i, 2).value): line_items[line_items_ws.cell(i, 3).value] = \ line_items_ws.cell(i, 4).value invoice_txt += f'\ {customer_name} (client ID: {customer_id})\n\ {format("Invoice # ", ">50")}\ {format(invoice_id, "<10")}\n\ {format("Invoice date ", ">50")}\ {invoice_date}\n' """ Invoice is 60 columns wide: 12 cols: Quantity, centered 20 cols: Item name, left-aligned 11 cols: Unit price, right-aligned 17 cols: Line total, right-aligned """ invoice_txt += f'\n\n\ {format("Quantity", "^12")}\ {format("Item", "<20")}\ {format("Unit price", ">11")}\ {format("Line total", ">17")}\n\ {format("--------", "^12")}\ {format("----", "<20")}\ {format("----------", ">11")}\ {format("----------", ">17")}\n' for prod_id, units_sold in line_items.items(): line_total = units_sold * products[prod_id]['price'] invoice_total += line_total invoice_txt += f'\ {format(units_sold, "^12")}\ {format(products[prod_id]["name"], "20")}\ {format(products[prod_id]["price"], ">11,.2f")}\ {format("$", ">8")}\ {format(line_total, ">9,.2f")}\n' invoice_txt += f'\n\n\ {format(" ", ">49")}\ {format("----------", ">11")}\n\ {format("TOTAL", ">43")}\ {format("$", ">8")}\ {format(invoice_total, "9,.2f")}\n\ {"=" * 60}\n\n' with open('invoice.txt', 'a+') as invoice: invoice.write(invoice_txt) def main(): # print(f'\n---------- {__file__} ----------') for i in range(222, 268): make_invoice(i) if __name__ == '__main__': main()
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' This is a simple python program to help manage email address that are set up using mysql. This program allows you to add/delete email addresses, add new domains, and add new aliases. ''' import MySQLdb as mdb import os def db(): data = open('/path/to/mysqlinfo', 'r') # this grabs mysql info login = data.read().split(',') # from a text document return mdb.connect(login[0], login[1], login[2], login[3]) def listDomains(): con = db() with con: cur = con.cursor() cur.execute("SELECT id, name FROM virtual_domains") domains = cur.fetchall() print 'id : domain' for d in domains: print d[0], ' : ', d[1] cur.close() def createEmail(): os.system('clear') # clear terminal listDomains() id = raw_input('Select id of domain: ') email = raw_input('User Email (include the proper domain): ') pw = raw_input('User Pw: ') if id and email and pw: con = db() with con: cur = con.cursor() #make sure email address doesnt exists cur.execute("SELECT * FROM virtual_users WHERE email = '%s';" % (email)) found = cur.fetchall() if found: # if email address exists print 'Email already exists' else: # if not, then add it cur.execute("INSERT INTO `virtual_users`(`domain_id`, `password` , `email`)" \ " VALUES('%s', ENCRYPT('%s', CONCAT('$6$', SUBSTRING(SHA(RAND()), -16))) , '%s');" % (id, pw, email)) cur.execute("SELECT * FROM virtual_users WHERE email='%s';" % (email)) rows = cur.fetchall() if rows: #display web client info print 'Email added!' else: print 'Error adding email.' con.close() def delEmail(): os.system('clear') email = raw_input('User Email to delete: ') if email: con = db() with con: cur = con.cursor() # dels email address - WARNING: anyone has the power to del account. Don't abuse. cur.execute("DELETE FROM virtual_users WHERE email='%s';" % (email)) cur.execute("SELECT * FROM virtual_users WHERE email='%s';" % (email)) rows = cur.fetchall() if not rows: print 'Email deleted!' else: print 'Error deleting email' con.close() def newDomains(): os.system('clear') domain = raw_input('Enter new domain: ') if domain: con = db() with con: cur = con.cursor() cur.execute("INSERT INTO virtual_domains(`name`) VALUES('%s');" % (domain)) cur.execute("SELECT * FROM virtual_domains WHERE name='%s';" %(domain)) # verify its been added rows = cur.fetchall() if rows: print 'Domain added!' else: print 'Error adding domain!' def aliases(): os.system('clear') listDomains() id = raw_input('Select the id of domain: ') alias = raw_input('Alias address: ') orig = raw_input('Current email: ') con = db() with con: cur = con.cursor() cur.execute("SELECT * FROM virtual_users WHERE email='%s';" % (orig)) rows = cur.fetchall() if rows: cur.execute("INSERT INTO virtual_aliases(`domain_id`, `source`, `destination`)" \ " VALUES('%s', '%s', '%s');" % (id, alias, orig)) cur.execute("SELECT * FROM virtual_aliases WHERE source='%s';" %(alias)) row = cur.fetchall() if row: print 'Aliases added!' else: print 'Error adding alias' else: print 'That email address does not exists' def menu(): print '\nEmail Admin Tool' print 'Choose 1 to create an email' print 'Choose 2 to delete an email' print 'Choose 3 to add a new domain' print 'Choose 4 to add an alias' print 'Or type q to exit\n' def main(): menu() while True: print 'Press "m" to see the menu again' choice = raw_input('Choice: ') if choice == 'q': break if choice == 'm': menu() elif choice == '1': createEmail() elif choice == '2': delEmail() elif choice == '3': newDomains() elif choice == '4': aliases() else: print 'Invalid option. Please choose again.' if __name__ == "__main__": main()
import random def shuffle(mylist): new_list = [] while len(mylist) > 0: change = random.randrange(len(mylist)) new_list.append(mylist[change]) mylist.remove(mylist[change]) return new_list mylist = [5,3,8,6,1,9,2,7] print(mylist) x = shuffle(mylist) print(x)
class Solution: def mySqrt(self, x): if x == 0 or x == 1: return x mid = int(x/2) while mid > 0: if mid * mid == x: return mid elif mid * mid > x: mid = int(mid/2) else: break while x >= mid * mid: mid += 1 return mid - 1 solution = Solution() print(solution.mySqrt(2))
class Solution: def strStr(self, haystack, needle): lenNeedle = len(needle) lenHaystack = len(haystack) if lenNeedle == 0: return 0 if lenHaystack == 0 or lenHaystack < lenNeedle: return -1 for i in range(len(haystack)): if i + lenNeedle >= lenHaystack and haystack == needle: return 0 elif haystack[i:i+lenNeedle:1] == needle: return i else: i +=i return -1 solution = Solution() # print(solution.strStr("hello","ll")) # print(solution.strStr("aaaaa","bba")) # print(solution.strStr("","")) # print(solution.strStr("mwscxsd","d")) print(solution.strStr("x","dwdkwdn"))
from karel.stanfordkarel import * """ File: EndpointCounter.py ------------------------ In this problem, Karel is in the top left corner of a square world. Karel needs to make his way down to a staircase at the bottom left corner, and from there, he needs to place the same number of beepers on each step as there are blank spaces above Karel. For example, in a 10x10 world, karel must place 9 beepers on the first step (due to 1 being blocked by a wall), then 8 in the next, and so on, until Karel reaches the top of the staircase. """ def main(): """ You should write your code to make Karel do its task in this function. Make sure to delete the 'pass' line before starting to write your own code. You should also delete this comment and replace it with a better, more descriptive one. """ a =gocheck() for i in range(0, a): put_beeper() reverse() move() turn_left() move() a-=1 while(True): for i in range(0,a): put_beeper() right() if front_is_clear(): move() turn_left() move() else : break; a -= 1 def reverse(): for i in range(0,2): turn_left() def gocheck(): a=1 while(front_is_clear()): move() a +=1 return a def rightsidecheck(): turn_left() while(front_is_blocked()): if beepers_present(): return 1 def right(): for i in range(0,3): turn_left() # There is no need to edit code beyond this point if __name__ == "__main__": run_karel_program()
while True: a = int(input("lotfa adadi ra vared konid:")) b = '*' print(b * a)
""" Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2 """ def countBob(s): ''' This function counts the number of times the term 'bob' appears in a string s s is a string of lower case characters ''' count = 0 #Initializing count of 'bob's to zero for i in range(len(s)-1): #i goes from 0 to one less than length of string s if s[i:i+3] == 'bob': #Checking three characters starting from i if they equal 'bob' count += 1 return count print('Number of times bob occurs is: ' + str(countBob(s))) #Printing the desired output by converting count to a string
x = 1 y = 0 while x <= end: y = y + x x += 1 print y
def fib(n): i = 1 x = [0,1] while len(x) < n: x.append(x[i] + x[i-1]) i += 1 return(x) # alternatively def fibon(n): a = b = 1 result = [] for i in range(n): result.append(a) a, b = b, a + b return result # generator version, does not block as much memory def fibGen(n): a = b = 1 for i in range(n): yield a a, b = b, a + b fibGen(100) def fibRatio(s): # if called on fib(min(n,3)) == golden ratio if len(s) < 3: raise ValueError("Need at least 2, non-zero elements to calculate Fibbonacci ratios.") else: i = 3 l = [0,(s[2]/s[1])] while len(l) < len(s)-1: l.append(float(s[i])/s[i-1]) i += 1 return(l) even_fibSequence = filter(lambda x: x % 2 == 0 fibRatio(even_fibSequence, fib(100))) # around 1 + golden ratio def multiply(x): return (x*x) def add(x): return (x+x) from collections import OrderedDict funcs = [multiply, add] names = ['a', 'b', 'c'] vals = [1,2,3] d = OrderedDict(zip(names,vals)) for i in d.values(): value = list(map(lambda x: x(i), funcs)) print(value) some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] unqs = set([x for x in some_list]) dupelicates = set([x for x in some_list if some_list.count(x) > 1]) valid = set(['yellow', 'red', 'blue', 'green', 'black']) input_set = set(['red', 'brown']) # valid print(input_set.intersection(valid)) # invalid print(input_set.difference(valid))
from abc import ABC, abstractmethod class AbstractClassExample(ABC): def __init__(self, value): self.value = value super().__init__() @abstractmethod def do_something(self): pass class DoAdd42(AbstractClassExample): def do_something(self): return self.value + 42 class DoMul42(AbstractClassExample): def do_something(self): return self.value * 42 x = DoAdd42(value = 10, string_thing = 'thing') y = DoMul42(10) print(x.do_something()) print(y.do_something())
def displayTitle(title): separator = "=" * 50 print(separator + " " + title + " " + separator) """ 나무를 1 찍음 나무를 2 찍음 나무를 3 찍음 나무를 4 찍음 나무를 5 찍음 나무가 넘어감 while문 밖 """ treeHit = 0 while treeHit < 5: treeHit = treeHit + 1 print("나무를 %d 찍음" % treeHit) if treeHit == 5: print("나무가 넘어감") print("while문 밖") displayTitle("while문 직접 만들기") prompt = """ 1. Add 2. Del 3. List 4. Quit Enter number : """ # number = 0 # while number != 4: # print(prompt) # number = int(input()) # print("Your choice is %d" % number) displayTitle("while문 강제로 빠져나가기") coffee = 5 money = 300 while money: coffee = coffee - 1 print("커피 1개 판매. 남은 coffee %d개" % coffee) if not coffee: print("coffee : 0 개이므로 종료") break displayTitle("조건에 맞지 않는 경우 맨 처음으로 돌아가기") a = 0 while a < 10: a = a + 1 if a % 2 == 0: continue print(a) displayTitle("무한루프") #while True: # print("Press Ctrl+C")
try: print(4 / 0) except: print("Exception occur..") try: 4 / 0 except ZeroDivisionError as e: print(e) try: f = open("foo.txt", "r") except FileNotFoundError as e: print(str(e)) else: data = f.read() f.close() finally: print("finally is called..") try: f = open("foo.txt", "r") except FileNotFoundError as e: pass class Bird: def fly(self): raise NotImplementedError("must implement fly methods") class Eagle(Bird): pass try: eagle = Eagle() eagle.fly() except NotImplementedError as e: print("Raised exception", e) print("End..")
""" 문자열 자료형 """ lineSeparator = "=" * 50 # == 문자열 생성 str1 = "Hello World" str2 = 'Python is fun' str3 = """Life is too short, You need python""" str4 = '''zaccoding''' print(str1) print(str2) print(str3) print(str4) # == 문자열에 ' 포함 food = "Python's favorite food is perl" # Python's favorite food is perl print(food) say = '"Python is very easy." he says' # "Python is very easy." he says print(say) food = 'Python\'s favorite food is perl' say = "\"Python is very easy.\" he says" print(food) print(say) # new line multiline = "Life is too short\nYou need python" print(multiline) print("--") multiline = '''Life is too short You need python ''' print(multiline) print("--") multiline = """Life is too short You need python""" print(multiline) print("--") # == 문자열 연산 print("================= 문자열 연산 =================") print("1. 더해서 연결") head = "Python" tail = " is fun" # Python is fun print(head + tail) print("2. 문자열 곱하기") a = "python" # pythonpython print(a * 2) print("=" * 50) print("My Program") print("=" * 50) # == 문자열 인덱싱과 슬라이싱 a = "Life is too short, You need Python" # e print(a[3]) # n print(a[-1]) # True print(a[0] == a[-0]) # Life 0 <= i < 4 print(a[0:4]) # You need Python , 19 <= i <length-1 print(a[19:]) # Life is too short, 0 <= i <19 print(a[:19]) a = "Pithon" # Python print(a[:1] + 'y' + a[2:]) # == 문자열 포매팅 """ %s : 문자열 // %c : 문자1개 // %d : 정수 // %f 부동 소수 %o : 8진수 // %x : 16진수 // %% : Literal % (문자 '%' 자체) """ print("=" * 50) # I eat 3 apples print("I eat %d apples" % 3) # I eat five apples print("I eat %s apples" % "five") number = 3 # I eat 3 apples print("I eat %d apples" % number) day = "three" # I ate 3 apples. so I was sick for three days print("I ate %d apples. so I was sick for %s days" % (number, day)) # I have 3 apples print("I have %s apples" % 3) # Error is 98% print("Error is %d%%" % 98) # == 포맷 코드와 숫자 함께 사용하기 # 1. 정렬과 공백 # hi (전체 length 10중 0:7 공백, 8,9 'h', 'i' print("%10s" % "hi") # hi jane print("%-10sjane" % "hi") print(lineSeparator) print("2. 소수점 표현") # 3.1416 print("%0.4f" % 3.141592) # 3.1416 (전체 길이 10 중 소수점4개 표현, 공백 4개) print("%10.4f" % 3.141592) print(lineSeparator + " 문자열 관련 함수 " + lineSeparator) a = "hobby" # 2 print(a.count('b')) # 위치알려주기1 (find) a = "Python is best choice" # 10 print(a.find('b')) # -1 print(a.find('k')) # 위치 알려주기2 (index) a = "Life is too short" # 8 print(a.index('t')) # error # Traceback (most recent call last): # print(a.index('k')) # ValueError: substring not found # print(a.index('k')) # 문자열 삽입 (join) a = "," # a,b,c,d print(a.join("abcd")) # upper a = 'hi' # HI print(a.upper()) # hi print(a.upper().lower()) # 왼쪽 공백 지우기 (lstrip) a = " hi" print(a.lstrip()) # 오른쪽 공백 지우기 (rstrip) a = "hi " print(a.rstrip()) # 양쪽 공백 지우기 a = " hi " print(a.strip()) # 문자열 바꾸기 (replace) a = "Life is too short" # Your leg is too short print(a.replace("Life", "Your leg")) # 문자열 나누기 (split) a = "Life is too short" # 공백을 기준으로 문자열 나눔 # ['Life', 'is', 'too', 'short'] print(a.split()) a = "a:b:c:d" # ['a', 'b', 'c', 'd'] print(a.split(':')) # 고급 문자열 포매팅 print(lineSeparator + " 고급 문자열 포매팅 " + lineSeparator) # I eat 3 apples print("I eat {0} apples".format(3)) # I eat five apples print("I eat {0} apples".format("five")) number = 3 # I eat 3 apples print("I eat {0} apples".format(number)) number = 10 day = "three" # I ate 10 apples. so I was sick for three days. print("I ate {0} apples. so I was sick for {1} days.".format(number, day)) # I ate three apples. so I was sick for 10 days. print("I ate {1} apples. so I was sick for {0} days.".format(number, day)) # 이름으로 넣기 # I ate 10 apples. so I was sick for 3 days. print("I ate {number} apples. so I was sick for {day} days.".format(number=10, day=3)) # 인덱스와 혼용해서 넣기 # I ate 10 apples. so I was sick for 3 days. print("I ate {0} apples. so I was sick for {day} days.".format(10, day=3)) # 왼쪽 정렬 # hi k print("{0:<10}".format("hi") + "k") # 오른쪽 정렬 # hik print("{0:>10}".format("hi") + "k") # 가운데 정렬 # hi k print("{0:^10}".format("hi") + "k") # 공백 채우기 # ====hi====k print("{0:=^10}".format("hi") + "k") # hi!!!!!!!!k print("{0:!<10}".format("hi") + "k") # 소수점 표현하기 y = 3.42134234 # 3.4213 print("{0:0.4f}".format(y)) # 3.4213 print("{0:10.4f}".format(y)) # '{' or '}' 문자 표현하기 # { and } print("{{ and }}".format())
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from triangle_classify import classify_triangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html has a nice description of the framework class TestTriangles(unittest.TestCase): # define multiple sets of tests as functions with names that begin def testxRightTriangleA(self): self.assertEqual(classify_triangle(3,4,5), "Right") def testRightTriangleB(self): self.assertEqual(classify_triangle(5,3,4), 'Right') def testEquilateralTriangles(self): self.assertEqual(classify_triangle(1,1,1), 'Equilateral') def testEquilateralTriangles1(self): self.assertEqual(classify_triangle(2,2,2), 'Equilateral') def testIsocelesTriangles2(self): self.assertEqual(classify_triangle(1,1,2), 'NotATriangle') def testIsocelesTriangles3(self): self.assertEqual(classify_triangle(3,4,3), 'Isoceles') def testIsocelesTriangles4(self): self.assertEqual(classify_triangle(4,10,10), 'Isoceles') def testScaleneTriangles5(self): self.assertEqual(classify_triangle(10,11,12),'Scalene') def testInvalidInputTriangles7(self): self.assertEqual(classify_triangle(300,1,1), 'InvalidInput') def testInvalidInputTriangles8(self): self.assertEqual(classify_triangle(300.05,1,1), 'InvalidInput') if __name__ == '__main__': print('Running unit tests') unittest.main()
import random def randomFig(): figure = random.randint(1, 20) return figure def welcome(): print ("Welcome to guess the number game! Guess the number between 1 and 20! You have 7 guesses! Take a Guess:") def events(figure): while(guesses<=10): if guesses==10 : print("Gameover") break guess = int(input()) if guess>figure: print("Opps thats incorrect\n please try a Smaller no. then it\nNo of gusses left =",9-guesses) guesses=guesses+1 continue elif guess< figure: print("Opps thats incorrect\n please try a Bigger no. then it\nNo of gusses left =", 9 - guesses) guesses = guesses + 1 continue elif guess == figure: print(" 'Marvelous'\n You won the game \nYou took ", guesses, "gusses") break figure = randomFig() welcome() events(figure)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Oct 27 20:19:08 2017 @author: chao_lu """ # Dependencies import csv #input and output files file_to_load = "election_data_2.csv" file_to_output = "election_data_2.txt" # Read the csv and convert it into a list of dictionaries Candidates=[] with open(file_to_load, newline="") as election_data: csv_reader = csv.reader(election_data, delimiter=",") # Skip Headers next(csv_reader, None) # Loop for row in csv_reader: Candidates.append(row[2]) # Update candidate list # Vote Summary total_votes=len(Candidates) c_list=set(Candidates) c_list=[i for i in c_list] vote_counts=[Candidates.count(i) for i in c_list] vote_percent= [((Candidates.count(i)/total_votes)*100) for i in c_list] vote_percent= [round(i,3) for i in vote_percent] max_vote=max(vote_counts) mx, vid = max( (vote_counts[i],i) for i in range(len(vote_counts)) ) win=c_list[vid] # printing vote summary print('Election Results') print('-------------------------') print('Total Votes: ' + str(total_votes) ) print('-------------------------') c_num=0 for i in c_list: print(i + ': ' + str(vote_percent[c_num])+'% '+ '(' + str(vote_counts[c_num]) + ')' ) c_num+=1 print('-------------------------') print('Winner: ' + str(win)) print('-------------------------') #export to text file myfile= open(file_to_output,'w') myfile.write('Election Results'+ '\n') myfile.write('-------------------------'+ '\n') myfile.write('Total Votes: ' + str(total_votes)+ '\n') c_num=0 for i in c_list: myfile.write(i + ': ' + str(vote_percent[c_num])+'% '+ '(' + str(vote_counts[c_num]) + ')'+ '\n') c_num+=1 myfile.write('-------------------------'+ '\n') myfile.write('Winner: ' + str(win)+ '\n') myfile.write('-------------------------'+ '\n') myfile.close
"""This module contains Movie class""" import re class Movie(object): """Class to encapsulate Movie data for display in HTML page""" def __init__(self, title, poster_image_url, trailer_youtube_url, release_year, rating): """Initialization method for Movie class""" self.title = title self.poster_image_url = poster_image_url self.trailer_youtube_url = trailer_youtube_url self.release_year = release_year self.set_rating(rating) def set_rating(self, rating): """Method that enforces rating limits (ensures rating is between 0 and 5, and rounds rating (to nearest whole number, then sets adjusted rating to instance variable""" if rating < 0: self.rating = 0 elif rating > 5: self.rating = 5 else: self.rating = int(round(rating)) def get_youtube_id(self): """Method that extracts and returns the youtube ID from the url""" youtube_id_match = re.search(r'(?<=v=)[^&#]+', self.trailer_youtube_url) youtube_id_match = youtube_id_match or re.search(r'(?<=be/)[^&#]+', self.trailer_youtube_url) trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match else None return trailer_youtube_id
def main(): ogrenci_no=input('Ogrenci Numaranızı Giriniz') ogrenci_no=int(ogrenci_no) arkadaslar_dosyasi=open('arkadaslar.txt','w') ogno=ogrenci_no%10 for sayac in range(1,ogno+1): isim=input('İsim Giriniz: ') telefon=input('Telefon giriniz: ') arkadaslar_dosyasi.write('İsim: '+isim+'\n') arkadaslar_dosyasi.write('Telefon: '+telefon+'\n') arkadaslar_dosyasi.close() print("arkadaslar.txt dosyasına yazılan veriler asagıda") arkadaslar_dosyasi=open('arkadaslar.txt','r') while isim !='': isim=arkadaslar_dosyasi.readline() numara=arkadaslar_dosyasi.readline() isim=isim.rstrip('\n') print(isim) numara=numara.rstrip('\n') print(numara) arkadaslar_dosyasi.close() main()
def smallest(a,k): for i in range(0,n): min=i for j in range(i+1,n): if(a[j]<a[min]): min=j temp=a[i] a[i]=a[min] a[min]=temp print("k th smallest is: ",a[k-1]) n=int(input("enter the num of elements in array: ")) k=int(input("enter value of k: ")) a=[] print("enter elements: ") for i in range(0,n): a.append(int(input())) smallest(a,k)
s = input("Do you agree? ") if s.lower() in ["y", "yes"]: print("Agreed.") elif s.lower() in ["no", "n"]: print("Not agreed.")
#*************************** CREATING DECRYPTION SHARES *************************************** def invmodp(a, b): for d in range(1, b): r = (d * a) % b if r == 1: break else: raise ValueError('%d has no inverse mod %d' % (a, b)) return d if (num ==3): u = int(input("\nEnter your user number : ")) if (u == 1): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3) * invmodp(((u2-u1)*(u3-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3) * invmodp(((u1-u2)*(u3-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2) * invmodp(((u2-u3)*(u1-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") elif (u == 2): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3) * invmodp(((u2-u1)*(u3-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3) * invmodp(((u1-u2)*(u3-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2) * invmodp(((u2-u3)*(u1-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") elif (u == 3): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3) * invmodp(((u2-u1)*(u3-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3) * invmodp(((u1-u2)*(u3-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2) * invmodp(((u2-u3)*(u1-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") elif (u == 4) : if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3) * invmodp(((u2-u1)*(u3-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3) * invmodp(((u1-u2)*(u3-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2) * invmodp(((u2-u3)*(u1-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") elif (u == 5) : if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3) * invmodp(((u2-u1)*(u3-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3) * invmodp(((u1-u2)*(u3-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2) * invmodp(((u2-u3)*(u1-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") elif(num ==4): u = int(input("\nEnter your user number :")) if (u == 1): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3*u4) * invmodp(((u2-u1)*(u3-u1)*(u4-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3*u4) * invmodp(((u1-u2)*(u3-u2)*(u4-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2*u4) * invmodp(((u1-u3)*(u2-u3)*(u4-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u4): t = int(input("Enter your share :")) s = (t * ((u1*u2*u3) * invmodp(((u1-u4)*(u2-u4)*(u3-u4)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") if (u == 2): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3*u4) * invmodp(((u2-u1)*(u3-u1)*(u4-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3*u4) * invmodp(((u1-u2)*(u3-u2)*(u4-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2*u4) * invmodp(((u1-u3)*(u2-u3)*(u4-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u4): t = int(input("Enter your share :")) s = (t * ((u1*u2*u3) * invmodp(((u1-u4)*(u2-u4)*(u3-u4)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") if (u == 3): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3*u4) * invmodp(((u2-u1)*(u3-u1)*(u4-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3*u4) * invmodp(((u1-u2)*(u3-u2)*(u4-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2*u4) * invmodp(((u1-u3)*(u2-u3)*(u4-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u4): t = int(input("Enter your share :")) s = (t * ((u1*u2*u3) * invmodp(((u1-u4)*(u2-u4)*(u3-u4)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") if (u == 4): if(u == u1): t = int(input("Enter your share :")) s = (t * ((u2*u3*u4) * invmodp(((u2-u1)*(u3-u1)*(u4-u1)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u2): t = int(input("Enter your share :")) s = (t * ((u1*u3*u4) * invmodp(((u1-u2)*(u3-u2)*(u4-u2)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u3): t = int(input("Enter your share :")) s = (t * ((u1*u2*u4) * invmodp(((u1-u3)*(u2-u3)*(u4-u3)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif(u == u4): t = int(input("Enter your share :")) s = (t * ((u1*u2*u3) * invmodp(((u1-u4)*(u2-u4)*(u3-u4)),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present") elif(num ==5): u = int(input("\nEnter your user number :")) if (u == 1): t = int(input("Enter your share :")) s = (t * ((u2*u3*u4*u5) * invmodp(((u2-u1)*(u3-u1))*(u4-u1)*(u5-u1),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif (u == 2): t = int(input("Enter your share :")) s = (t * ((u1*u3*u4*u5) * invmodp(((u1-u2)*(u3-u2))*(u4-u2)*(u5-u2),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif (u == 3): t = int(input("Enter your share :")) s = (t * ((u1*u2*u4*u5) * invmodp(((u1-u3)*(u2-u3))*(u4-u3)*(u5-u3),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif (u == 4): t = int(input("Enter your share :")) s = (t * ((u1*u2*u3*u5) * invmodp(((u1-u4)*(u2-u4))*(u3-u4)*(u5-u4),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) elif (u == 5): t = int(input("Enter your share :")) s = (t * ((u1*u2*u3*u4) * invmodp(((u1-u5)*(u2-u5))*(u3-u5)*(u4-u5),q))) print("Your Decryption Share Is =",(pow(c1,s,p))) else: print("User Not Present")
'''' This is an helper class to the Chilean economic indicator http://mindicador.cl/ using the awesome requests library you can get uf, ivp, dolar, etc. a simple example: >> m = Mindicador() >> m = m.get_uf() >> uf {'fecha': '2017-07-23T04:00:00.000Z', 'nombre': 'Unidad de fomento (UF)', 'codigo': 'uf', 'unidad_medida': 'Pesos', 'valor': 26624.85} The above response is returned as a json ready object; you can use the object the following way: >> for ufs in uf: print(ufs, ':', uf.get(ufs)) fecha : 2017-07-23T04:00:00.000Z nombre : Unidad de fomento (UF) codigo : uf unidad_medida : Pesos valor : 26624.85 Note: Some if not most of the words in the responses are in Spanish(Chilean). ''' import requests class Mindicador(): def __init__(self): if requests.get('http://mindicador.cl/api').status_code == requests.codes.ok: self.api_url = requests.get('http://mindicador.cl/api') else: self.bad_r = requests.get('http://mindicador.cl/api') return self.bad_r.raise_for_status() def get_uf(self): api_url = self.api_url.json() return api_url.get('uf') def get_ivp(self): self.api_url = self.api_url.json() return self.api_url.get('ivp') def get_dolar(self): self.api_url = self.api_url.json() return self.api_url.get('dolar') def get_dolar_intercambio(self): self.api_url = self.api_url.json() return self.api_url.get('dolar_intercambio') def get_euro(self): self.api_url = self.api_url.json() return self.api_url.get('euro') def get_ipc(self): self.api_url = self.api_url.json() return self.api_url.get('ipc') def get_utm(self): self.api_url = self.api_url.json() return self.api_url.get('utm') def get_imacec(self): self.api_url = self.api_url.json() return self.api_url.get('imacec') def get_tpm(self): self.api_url = self.api_url.json() return self.api_url.get('tpm') def get_libra_cobre(self): self.api_url = self.api_url.json() return self.api_url.get('libra_cobre') def get_tasa_desempleo(self): self.api_url = self.api_url.json() return self.api_url.get('tasa_desempleo')
l = input() print(l, type(l)) s = l.split() print(s, type(s)) # for i in range(len(s)): # s[i] = int(s[i]) # print(s) s = list(map(int, s)) print(s) def f(x): return x + 1 # s = [1, 2, 3, 4, 5] for i in range(len(s)): s[i] = f(s[i]) s = list(map(f, s)) print(s) names = ['Zhandos', 'Bekaidar', 'Ildar', 'Dulat'] def f(name): return len(name) len_names = list(map(f, names)) print(len_names) def how_many_vowels(name): def f(ch): return ch in ['a', 'o', 'u', 'i', 'e'] return sum(list(map(f, name.lower()))) vowels = list(map(how_many_vowels, names)) print(vowels)
board = [[' ' for i in range(3)] for j in range(3)] # board[1][2] = 'X' # board[0][1] = 'O' def display(): for i in range(3): print("+---" * 3 + '+') for j in range(3): print(f"| {board[i][j]} ", end='') print('|') print("+---" * 3 + '+') def is_win(player): win1 = True win2 = True for i in range(3): win1 = win1 and board[i][i] == player win2 = win2 and board[i][2 - i] == player win_ij = True win_ji = True # win = board[i][0] == player and board[i][1] == player and board[i][2] == player for j in range(3): win_ij = win_ij and board[i][j] == player win_ji = win_ji and board[j][i] == player if win_ij or win_ji: return True if win1 or win2: return True return False moves = ['X', 'O'] current_move = 0 cnt = 0 while True: display() print(f"{moves[current_move]} is moving") x, y = map(int, input().split()) if x > 2 or x < 0 or y > 2 or y < 0: print("No such coordinate. Try again.") elif board[x][y] != ' ': print("Cell is occupied. Try again.") else: cnt += 1 board[x][y] = moves[current_move] if is_win(moves[current_move]): display() print(f"Player {moves[current_move]} win!") break elif cnt == 9: display() print("Game over. Draw.") break current_move = (current_move + 1) % 2
shop = {} while True: role = input("Please, enter your role\n") if role == 'admin': while True: option = int(input("1 to add items\n2 to change role\n")) if option == 1: name = input("Please, enter item name\n") price = int(input("Please, enter item price\n")) amount = int(input("Please, enter item amount\n")) shop[name] = { 'price': price, 'amount': amount } print(shop) elif option == 2: break elif role == 'customer': cart = {} while True: print("Name\tPrice\tAmount") for name in shop: print(f'{name}\t{shop[name]["price"]}\t{shop[name]["amount"]}') option = int(input("1 to add item\n2 to buy\n3 to change role\n")) if option == 1: name = input("Please, enter item name\n") amount = int(input("Please, enter item amount\n")) if cart.get(name) is None: if amount > shop[name]['amount']: print("Amount exceeded") else: cart[name] = { 'price': shop[name]['price'], 'amount': amount } else: if amount + cart[name]['amount'] > shop[name]['amount']: print("Amount exceeded") else: cart[name]['amount'] += amount elif option == 2: total = 0 for name in cart: total += cart[name]['price'] * cart[name]['amount'] shop[name]['amount'] -= cart[name]['amount'] if shop[name]['amount'] == 0: del shop[name] print(f"Total: {total}") cart.clear() elif option == 3: break
from globals import * class Star(object): def __init__(self, mass, radius, pos, vel, color): self.obj = sphere(pos=pos / DIST_SCALE, radius=radius, color=color) self.mass = mass self.vel = vel self._pos = pos # Externally use scaled version for physics, use normalized version for graphics @property def pos(self): return self._pos @pos.setter def pos(self, value): self.obj.pos = value / DIST_SCALE self._pos = value def __str__(self): return "Mass: " + str(self.mass) + "\nPos: " + str(self.pos) + \ "\nVel: " + str(self.vel)
import pdb class people(object) : def __init__(self,name,age): self.name = name self.__age = age def getName(self): return self.name def getAge(self): return self.__age class man(people): def __init__(self,name,age): pdb.set_trace() super(man,self).__init__(name,age) """ super(man,self) <super: <class 'man'>, <man object>> """
__author__ = "Danilo S. Carvalho <[email protected]>" from abc import ABCMeta from abc import abstractmethod class Annotator(object): __metaclass__ = ABCMeta def __init__(self): """Formatter constructor Constructs an annotator object that includes or modify annotations for objects in the data model. :return: new Annotator instance. """ pass @abstractmethod def annotate(self, annotable): """Annotates a document :param annotable (Annotable): object to be annotated. :return: Annotated Annotable (Document, Sentence, Term, Token, ...) object. """ raise NotImplementedError()
# Pseudocode # # Take input from the user for number of actors # Take input from the user for number of roles and attributes # Create a matrix to store the value of each actor who has roles and attributes # # function weighted score with input as the score # calculate the weight of each score by taking the weight as input # # for rows in the matrix: # for columns in the matrix # Take input from the user for each actor's score # current cell = weighted score of each score entered # # # for each row in the matrix: # print the sum of the weighted score for that actor # Code snippet # # Inputs number_of_actors = int(input("Enter number of actors: ")) number_of_roles_and_attributes = int(input("Enter number of roles and attributes: ")) # initialize the matrix that holds the "table" for each actor and the actor's role/attribute Matrix = [[0 for x in range(number_of_roles_and_attributes)] for y in range(number_of_actors)] # calculate the weighted score def weighted_score(score): weight = 0.0 weight = float(input("Enter the weight = ")) return float(score)*weight # add items to the array for i in range(number_of_actors): for j in range(number_of_roles_and_attributes): Matrix[i][j] = weighted_score(input("Enter score for the role: ")) # Calculate the total weighted score of each actor for i in range(number_of_actors): print("total weighted score of the actor: " + str(sum(Matrix[i]))) # print([i[1] for i in Matrix]) # print(Matrix) # for i in range(number_of_actors): # print("row " + str(i)) # for j in range(number_of_roles): # print(" column value:" + str(Matrix[i][j])) # actor_weight = [-0.7,0.8] # role_weight = [x * 0.5 for x in actor_weight] # print(role_weight) # role_weight = [0.4,0.4] # # # No iterables are passed # result = zip() # # # Converting itertor to list # resultList = list(result) # print(resultList) # for g in range(len(actor_weight)): # actor_weight[g] = actor_weight[g] * role_weight[g] / sum(role_weight) # print(sum(actor_weight)) # Two iterables are passed # result = zip(actor_weight, role_weight) # print(sum(x * y for x, y in zip(actor_weight, role_weight))/sum(role_weight)) # Converting itertor to set # resultSet = set(result) # print(resultSet)
while True: try: number = int(input("enter a number: ")) print(2/number) break except ValueError: print("Please enter a number") except ZeroDivisionError: print("Zero doesn't work") except Exception as e: print("some other error: " + repr(e)) # repr gives u the complete exception + the message string whereas str(e) will give only the message string finally: print("next loop")
# Programmer: James Aniciete # Course No.: CSC 157 # Lab No.: 16 # Date: 5/9/2020 from datetime import datetime as DateTime from datetime import timedelta as TimeDelta from statistics import mean from math import ceil # function to add days to the start date with formatting def addDays(days) : start_date = DateTime.today() # print (start_date.strftime("%m-%d-%Y")) end_date = (start_date + TimeDelta(days)).strftime("%m-%d-%Y") return end_date # List for location/placement placement = [ "Front Store Entrance (Carboard Display)", "CD Racks (Usual Music Collection Aisles)", "Bargain CD Music Bins (Placed at the Front of the Store)", "Extended Edition Released (Cardboard Display)" ] # List for start dates of each period dates = [DateTime.today().strftime("%m-%d-%Y"), addDays(46), addDays(91), addDays(121)] # Anticipated Units Sold List # [ [CD, vinyl], ...] # fourth period uncertain ==> only initialized anticipated = [ [25,32], [15,19], [37,46], [0,0] ] # CD/Vinyl Prices List prices = [ [17,32], [15,36], [9,21], [39,53] ] # function to ensure valid choice selection in a specified range def getIntInRange(message, rangeBottom, rangeTop): msg = message while True: try: x = int(input(msg)) if x >= rangeBottom and x <= rangeTop: break else: # error message for integer out of range + redisplay menu choices # f"" is like str.format() msg = f"Please enter a value between {rangeBottom} and {rangeTop}\n{message}" # error message for wrong data type (non-integer) except ValueError: msg = f"Please enter an integer value \n{message}" return x # function to display info on anticipated CD/vinyl sales # row = period - 1 b/c lists have zero-based indices def printInfo(row): antTotalCD = 0; antTotalVin = 0 # calculate total anticipated sales for CD and Vinyl for x in range(row+1): antTotalCD += anticipated[x][0] antTotalVin += anticipated[x][1] # anticipated values for the given period #antCD = anticipated[row][0] #antVin = anticipated[row][1] # for Period 4, tell user data are only forecasted values if row == 3: if anticipated[row][0] == 0 and anticipated[row][1] == 0: anticipated[row][0] = "Number is dependent on previous sales" anticipated[row][1] = "Number is dependent on previous sales" # \ for line continuation # not indented b/c it would display as indented print(f"\n\ Period: {row +1}\n\ Start Date: {dates[row]}\n\ Location and Placement: {placement[row]}\n\ Anticipated CDs Sold for this Period: {anticipated[row][0]}\n\ Anticipated Vinyl Sold for this Period: {anticipated[row][1]}\n\ Total Anticipated CDs Sold for this Period: {antTotalCD}\n\ Total Anticipated Vinyls Sold for this Period: {antTotalVin}\n\ CD Price: ${prices[row][0]}\n\ Vinyl Price: ${prices[row][1]}\n") # function to calculate Period 4 sales based on {ceil(1.1 * mean of previous periods' sales)} # allows entry of different sales amounts for Periods 1-3 in the range [0, 1,000,000] def calcPeriodFour(): soldCDOne = getIntInRange(f"Please input the number of CDs sold in period 1 ({dates[0]}): ", 0, 1000000) soldCDTwo = getIntInRange(f"Please input the number of CDs sold in period 2 ({dates[1]}): ", 0, 1000000) soldCDThree = getIntInRange(f"Please input the number of CDs sold in period 3 ({dates[2]}): ", 0, 1000000) calcCD = ceil(mean([soldCDOne, soldCDTwo, soldCDThree])*1.1) soldVinOne = getIntInRange(f"Please input the number of vinyl records sold in period 1 ({dates[0]}): ", 0, 1000000) soldVinTwo = getIntInRange(f"Please input the number of vinyl records sold in period 2 ({dates[1]}): ", 0, 1000000) soldVinThree = getIntInRange(f"Please input the number of vinyl records sold in period 3 ({dates[2]}): ", 0, 1000000) calcVin = ceil(mean([soldVinOne, soldVinTwo, soldVinThree])*1.1) print(f"\nAnticipated CDs Sold for Period 4: {calcCD}") print(f"\nAnticipated Vinyls Sold for Period 4: {calcVin}") print("\nNOTE: Anticipated Sales for Perid 4 is 1.1 times the average of sales from Periods 1-3\n") anticipated[3] = [calcCD, calcVin] # menu choices to be used with getIntInRange() menuChoices = "\ Please select an option from the following \n\ 1. View Entire Timeline for the Norwood Notes New CD Placement\n\ 2. See Information for a Specific Period\n\ 3. Calculate Anticipated Units Sold for Period 4\n\ 4. Exit Program\n\ Your Choice: " # period choices for specific period selection if menuChoices != 4: periodChoices = f"\n\ Please select a period:\n\ Period 1: {dates[0]}\n\ Period 2: {dates[1]}\n\ Period 3: {dates[2]}\n\ Period 4: {dates[3]}\n\ Your Choice: " # while loop to execute program until choice 4 (Exit Program) is selected while True: choice = getIntInRange(menuChoices, 1, 4) if choice == 1: for i in range(4): printInfo(i) elif choice == 2: period = getIntInRange(periodChoices, 1, 4) printInfo(period-1) elif choice == 3: calcPeriodFour() elif choice == 4: break; ################################################################################### ## Questions ## 1 #from datetime import datetime #def daysBetween(day1, day2) : # day1 = datetime.strptime(day1, "%m/%d/%Y") # day2 = datetime.strptime(day2, "%m/%d/%Y") # return abs((day2 - day1).days) ## 2 #import datetime #today = datetime.date.today() #targetDay = datetime.date(2019, 12, 25) #diff = abs(today - targetDay) #print (diff.days) ## 3 #import datetime #print ("Today's Date:", datetime.datetime.today()) ## returns the date in "yyyy-mm-dd" format #date_today = datetime.date.today() #print (date_today) #print ("Current Year:", date_today.year) #print ("Current Month:", date_today.month) ## %B returns the name of the month spelled out #print ("Month Name:", date_today.strftime("%B")) #print ("Month\'s Day :", date_today.day) ## %A returns the weekday spelled out #print ("Weekday Name:", date_today.strftime("%A")) ## %x returns the date in "mm/dd/yy" format #date_today.strftime("%x")
def swap(arr,i,j): arr[i],arr[j]=arr[j],arr[i] def selection_sort(arr): for i in range(len(arr)): minimum=i for j in range(i+1,len(arr)): #Select the smallest value if arr[j] < arr[minimum]: minimum=j #Place it the front of the #Sorted end of the array swap(arr,minimum,i) arr= [1,4,5,6,54,6,8,6,5,58934,24,2823] print(arr) selection_sort(arr) print(arr)
#!/usr/bin/env python """A module with the definition of the abstract keystore.""" import abc class Keystore(metaclass=abc.ABCMeta): """A keystore interface.""" @abc.abstractmethod def Crypter(self, name: str) -> "Crypter": """Creates a crypter for the given key to encrypt and decrypt data. Args: name: A name of the key to create the crypter for. Returns: A crypter instance. """ class Crypter(metaclass=abc.ABCMeta): """A crypter interface.""" @abc.abstractmethod def Encrypt(self, data: bytes, assoc_data: bytes) -> bytes: """Encrypts the given data. Args: data: Data to encrypt. assoc_data: Associated data used for authenticating encryption. Returns: An encrypted blob of data. """ @abc.abstractmethod def Decrypt(self, data: bytes, assoc_data: bytes) -> bytes: """Decrypts the given encrypted data. Args: data: Encrypted data to decrypt. assoc_data: Associated data used for authenticating decryption. Returns: A decrypted blob of data. Raises: DecryptionError: If it is not possible to decrypt the given data. """ class UnknownKeyError(Exception): """An error class for situations when a key is not know.""" def __init__(self, key_name: str) -> None: super().__init__(f"Unknown key: '{key_name}'") self.key_name = key_name class DecryptionError(Exception): """An error class for situation when decryption failed."""
#!/usr/bin/env python """Test utilities for working with time.""" import sys import time import dateutil def Step() -> None: """Ensures passage of time. Some tests need to ensure that some amount of time has passed. However, on some platforms (Windows in particular) Python has a terribly low system clock resolution, in which case two consecutive time checks can return the same value. This utility waits (by sleeping the minimum amount of time possible), until the time actually made a step. Which is not perfect, as unit tests in general should not wait, but in this case this time is minimal possible. """ start = time.time() while start == time.time(): time.sleep(sys.float_info.epsilon) _MICROSECOND_MULTIPLIER = 10**6 def HumanReadableToMicrosecondsSinceEpoch(timestamp: str) -> int: """Converts a human readable timestamp into microseconds since epoch. Args: timestamp: A human readable date time string. Returns: Number of microseconds since epoch. Note: this method is intentionally made testing only, as it relies on dateutil.parser guessing the timestamp format. Guessing is expensive and generally non-deterministic and should be avoided in production code. """ return dateutil.parser.parse(timestamp).timestamp() * _MICROSECOND_MULTIPLIER
def print_upper_words(list): '''Accepts a list, and returns it all capitalized. ''' for word in list: if word.startswith("e") or word.startswith("E"): print(word.upper()) print_upper_words(["eggs", "hey", "goodbye", "yo", "yes", "Eeeeeeeh"]) def print_e_words(list): '''Accepts a list, and returns only words that start with the letter 'e'. ''' for word in list: if word.startswith("e"): print(word) print_e_words(["eggs", "hey", "goodbye", "yo", "yes", "Eeeeeeeh"]) def print_msw(words, must_start_with): for word in words: for letter in must_start_with: if word.startswith(letter): print(word.upper()) break print_msw(["hello", "hey", "goodbye", "yo", "yes"], must_start_with={"h", "y"})
"""In a small town the population is p0 = 1000 at the beginning of a year. The population regularly increases by 2 percent per year and moreover 50 new inhabitants per year come to live in the town. How many years does the town need to see its population greater or equal to p = 1200 inhabitants?""" def nb_year(p0, percent, aug, p): counter = 0 while p0 < p: p0 = p0 * (100 + percent) / 100 + aug counter += 1 return counter nb_year(1500, 5, 100, 5000)
class Solution: def lemonadeChange(self, bills: [int]) -> bool: fives, tens, twenties = 0,0,0 print(bills) for bill in bills: if bill == 5: fives+=1 elif bill == 10: tens +=1 if fives>=1: fives -=1 else: return False elif bill == 20: twenties+=1 if fives>=1 and tens>=1: fives -=1 tens -=1 elif fives>=3 and tens ==0: fives -=3 else: return False print(fives, tens, twenties) return True bills1 = [5,5,20,5,5,10,5,10,5,20] sol = Solution() print(sol.lemonadeChange(bills1))
class Solution(): def reverse(self, x: int) -> int: neg = 0 if (x<0): x *= -1 neg = 1 res = 0 while(x>0): temp = x%10 res = res*10+temp x = int(x/10) if(neg): res*= -1 return res t = Solution() print (t.reverse(-123))
from collections import OrderedDict def odd_numbers(): lst = [1, 5, 6, 12, 19, 7, 8, 44, 27] total = 0 for i in lst: if i % 2 == 1: total += i print(total) def sum_elements(): lst = [1, 5, 6, 12, 19, 7, 8, 44, 27] total = sum(lst) print(total) def reverse_string(word): rword = '' index = len(word) while index > 0: rword += word[index - 1] index -= 1 return rword def remove_repeat(word): return "".join(OrderedDict.fromkeys(word)) def fizzbuzz(): numbers = [45, 22, 14, 65, 97, 72] for i in range(len(numbers)): if i % 3 == 0 and i % 5 == 0: numbers[i] = 'fizzbuzz' elif i % 3 == 0: numbers[i] = 'fizz' elif i % 5 == 0: numbers[i] = 'buzz' return numbers def pyramid(height): for i in range(1, height+1, 2): print(' ' * height + i * 'x') height -= 1 if __name__ == '__main__': pyramid(3)
import re # checker with out 'cid' passport_fields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] valid_passport = 0 # file read file_name = "input.txt" f = open(file_name) # get file content file_lines = f.readlines() file_content = "" i = 0 for line in file_lines: if line == '\n': file_content = file_content + '\n' i += 1 elif '\n' in line: file_content = file_content + line.split('\n')[0] + ' ' else: file_content = file_content + line passports = file_content.split('\n') for passport in passports: valid = 1 for passport_field in passport_fields: if passport_field in passport: valid = 1 else: valid = 0 break # break if valid == 1: valid_passport += 1 print("Total Number of valid passports =", valid_passport) # --------Second part ----- for passport in passports: s_valid = True # for birth year birth = passport.split('byr:')[-1].split(' ')[0] bir = re.compile(r'\d\d\d\d') if bir.match(birth): if not (int(birth) >= 1920 and int(birth) <= 2002): print('birth not valid') s_valid = False else: s_valid = False # for issue year iyr = passport.split('iyr:')[-1].split(' ')[0] iss = re.compile(r'\d\d\d\d') if iss.match(iyr): if not (int(iyr) >= 2010 and int(iyr) <= 2020): print('issue year not valid') s_valid = False else: s_valid = False # for expiration year eyr = passport.split('eyr:')[-1].split(' ')[0] exp = re.compile(r'\d\d\d\d') if exp.match(eyr): if not (int(eyr) >= 2010 and int(eyr) <= 2020): print('issue year not valid') s_valid = False else: s_valid = False # for height hgt = passport.split('eyr:')[-1].split(' ')[0] height = re.compile(r'cm|in')
import math import numbers class Vec3(object): def __init__(self, e0, e1, e2): self.e = (e0, e1, e2) @property def x(self): return self.e[0] @property def y(self): return self.e[1] @property def z(self): return self.e[2] @property def r(self): return self.e[0] @property def g(self): return self.e[1] @property def b(self): return self.e[2] def __add__(self, other): return Vec3(*[e1 + e2 for (e1, e2) in zip(self.e, other.e)]) def __radd__(self, other): return Vec3(*[e1 + e2 for (e1, e2) in zip(self.e, other.e)]) def __iadd__(self, other): return Vec3(*[e1 + e2 for (e1, e2) in zip(self.e, other.e)]) def __sub__(self, other): return Vec3(*[e1 - e2 for (e1, e2) in zip(self.e, other.e)]) def __sub__(self, other): return Vec3(*[e1 - e2 for (e1, e2) in zip(self.e, other.e)]) def __neg__(self): return Vec3(*(-self.e[0], -self.e[1], -self.e[2])) def __isub__(self, other): return Vec3(*[e1 - e2 for (e1, e2) in zip(self.e, other.e)]) def __rmul__(self, other): if isinstance(other, Vec3): return Vec3(*[e1 * e2 for (e1, e2) in zip(self.e, other.e)]) if isinstance(other, numbers.Real): return Vec3(*[other * i for i in self.e]) def __mul__(self, other): if isinstance(other, Vec3): return Vec3(*[e1 * e2 for (e1, e2) in zip(self.e, other.e)]) if isinstance(other, numbers.Real): return Vec3(*[other * i for i in self.e]) def __imul__(self, other): if isinstance(other, Vec3): return Vec3(*[e1 * e2 for (e1, e2) in zip(self.e, other.e)]) elif isinstance(other, numbers.Real): return Vec3(*[other * i for i in self.e]) def __truediv__(self, other): if isinstance(other, Vec3): return Vec3(*[e1 / e2 for (e1, e2) in zip(self.e, other.e)]) elif isinstance(other, numbers.Real): return Vec3(*[i / other for i in self.e]) def __itruediv__(self, other): if isinstance(other, Vec3): return Vec3(*[e1 / e2 for (e1, e2) in zip(self.e, other.e)]) elif isinstance(other, numbers.Real): return Vec3(*[i / other for i in self.e]) def length(self): return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) def squared_length(self): return self.x ** 2 + self.y ** 2 + self.z ** 2 def __repr__(self): return '{} {} {}'.format(self.r, self.g, self.b) def unit_vector(vec3): return vec3 / vec3.length() def dot(vec3, other): return sum([e1 * e2 for (e1, e2) in zip(vec3.e, other.e)]) def cross(vec3, other): return Vec3( vec3.y * other.z - vec3.z * other.y, vec3.z * other.x - vec3.x * other.z, vec3.x * other.y - vec3.y * other.x ) def reflect(v: "Vec3", n: "Vec3"): return v - 2 * dot(v, n) * n
def getorder(a): from datetime import date today = date.today() products=[] amounts=[] prices=[] product = input("enter which food u want ") amount = int(input("enter amount of ur product")) money=input("if u pay in GEL write GEL and if you pay with USD write USD") more=input("do you want more products? write yes or no") products.append(product) amounts.append(amount) for i in a: if product==i["product"] and int(i["amount"])>amount and today.strftime("%d/%m/%Y")>=i["validity"]: for c in i["price"]: price=i["price"] if c==money: prices.append(price[c]) if more=="yes": for d in range(len(a)-1): product = input("enter which food u want ") amount = int(input("enter amount of ur product")) money = input("if u pay in GEL write GEL and if you pay with USD write USD") products.append(product) amounts.append(amount) prices.append(money) elif more=="no": print("sooo.....okay") for i in range(len(prices)): pay=int(amounts[i])*int(prices[i]) print("you have to pay {}".format(pay)) user={} for b in range(len(products)): user[products[b]]=amounts[b]
import functools class Query: """Queries python objects for their values. Args: *args: The series of `queryable` functions Typical usage would pass in `queryable` functions in order to enable the class to perform actions on the passed in python object. For example, if three functions are initially passed in (`filter`, `exclude` and `get`), and the object being operated on is `[1, 2, 3, 4]`, usage might look like: >>> q = Query(filter, exclude, get) >>> q = q([1, 2, 3, 4]) >>> result = q.filter(value > 1).exclude(4) >>> assert list(q) == [2, 3] """ def __init__(self, *args, _parent=None): self._result = None self._cached_result = [] self._parent = _parent self._actions = {arg.__name__: arg for arg in args} @property def result(self): result = self._result if result is None and self._parent: result = self._parent.result return result @result.setter def result(self, value): self._result = value def __getattr__(self, name): if name in self._actions: return self._actions[name](self) raise AttributeError() def __call__(self, obj): self._result = obj self._cached_result = [] return self def __iter__(self): if self._cached_result: for r in self._cached_result: yield r return None for r in self.result: self._cached_result.append(r) yield r class Value: """Generate deferred comparison object. Used to generate functions which return `True` or `False` results depending on how the given comparison value compares to the comparison object. Example usage: >>> value = Value() >>> q = Q(filter)([1, 2, 3, 4]) >>> q.filter(value < 3) This would use a compatible filter function to compare each value in the given list to the value 3, where 1 and 2 would return `True` and 3 and 4 would return `False`. """ def __init__(self, _getattr=None): self._getattr = _getattr def _check_attr(self, comp): def check(x): return comp(self._getattr(x)) if self._getattr: return check return comp # TODO: These can probably be created programmatically. def __eq__(self, other): def comp(x): return x == other return self._check_attr(comp) def __lt__(self, other): def comp(x): return x < other return self._check_attr(comp) def __gt__(self, other): def comp(x): return x > other return self._check_attr(comp) def __getattr__(self, name): def _getattr(obj): if self._getattr: obj = self._getattr(obj) return getattr(obj, name) return type(self)(_getattr) def queryable(func): """Mark a function as able to be directly used by a `Query`. A convenience decorator for functions that take the arguments: result(Iterable): the iterable results on which the function operates *args: arbitrary positional args **kwargs: arbitrary positional keyword args and returns the results of that operation. """ @functools.wraps(func) def query_wrapper(self): def func_wrapper(*args, **kwargs): query = type(self)(*self._actions.values(), _parent=self) result = func(self, *args, **kwargs) query.result = result return query return func_wrapper return query_wrapper @queryable def filter(result, *args, **kwargs): """Filter out elements of the `result`. Args: args: filter functions that return a truthy or falsy value depending on if the element should be kept in the result. kwargs: filter functions that return a truthy or falsy value depending on if the named element should be kept in the result. """ for value in args: if callable(value): result = (r for r in result if value(r)) else: raise NotImplementedError() for key, value in kwargs.items(): if callable(value): result = (r for r in result if value(r)) else: raise NotImplementedError() return result @queryable def exclude(result, *args, **kwargs): """Exclude elements of the `result`. Args: args: filter functions that return a truthy or falsy value depending on if the element should be excluded from the result. kwargs: filter functions that return a truthy or falsy value depending on if the named element should be excluded from the result. """ for value in args: result = (r for r in result if r != value) for key, value in kwargs.items(): if callable(value): result = (r for r in result if value(r)) else: raise NotImplementedError() return result # Test Usage value = Value() Q = Query(filter, exclude) woah = [1, 2, 3, 4, 5] result = Q(woah).filter(value > 2) result2 = result.filter(value > 3) result3 = result2.exclude(5) class Bleh: """Example class to test testing arbitrary class attributes """ def __init__(self, value): self.prop = value def __repr__(self): return str(self.prop) assert list(result) == [3, 4, 5], list(result) assert list(result) == [3, 4, 5], list(result) assert list(result2) == [4, 5], list(result2) assert list(result3) == [4], list(result3) woah = [Bleh(1), Bleh(2), Bleh(3), Bleh(4), Bleh(5)] result = Q(woah).filter(value.prop > 2) result2 = result.filter(value.prop > 3) assert list(result) == woah[2:], list(result) assert list(result2) == woah[3:], list(result2) woah = [Bleh(Bleh(1)), Bleh(Bleh(5))] result = Q(woah).filter(value.prop.prop > 2) assert list(result) == woah[1:], list(result) woah = [Bleh(Bleh(Bleh(2))), Bleh(Bleh(Bleh(6)))] result = Q(woah).filter(value.prop.prop.prop > 3) assert list(result) == woah[1:], list(result) # woah2 = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
#!/usr/bin/python #Filename:using_dict.py #'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]' } print "Swaroop's address is %s" % ab['Swaroop'] #Adding a key/value pair ab['Guido'] = '[email protected]' #Deleting a key/value pair del ab['Spammer'] print '\nThere are %d contacts in the address-book\n' % len(ab) for name, address in ab.items(): print 'Contact %s at %s' %(name, address) if 'Guido' in ab: # OR ab.has_key('Guido') print "\nGuido's address is %s" % ab['Guido']
#!/usr/bin/python #coding:UTF-8 #Filename:time.py import time import datetime print time.clock() print time.time() print time.ctime() print time.strftime('%Y-%m-%d %H:%M:%S') print time.strftime('%Y%m%d') print time.strftime('%Y') ##day dec one day yesterday = datetime.date.today() - datetime.timedelta(days=1) print yesterday.strftime('%Y%m%d') print datetime.date.today() #print time.__doc__ dt = "2016-05-05 20:28:00" #转换成时间数组 timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S") print timeArray #转换成时间戳 timestamp = time.mktime(timeArray) print timestamp print(datetime.datetime.now()) print(datetime.datetime.now() + datetime.timedelta(days=1)) print(datetime.datetime.now() - datetime.timedelta(hours=1)) print(datetime.datetime.now() + datetime.timedelta(minutes=1)) print(datetime.datetime.now() + datetime.timedelta(seconds=1))
#!/usr/bin/python #-*- coding: UTF-8 -*- import os def child(): print('Hello from child',os.getpid()) def parent(): for i in range(3): print(i) newpid = os.fork() if newpid == 0: child() else: print('Hello from parent',os.getpid(),newpid) parent()
#python program to check armstrong number # i=int(input("Enter the number to check for armstrong")) # orig=i # sum=0 # while(i>0): # sum=sum+(i%10)*(i%10)*(i%10) # i=i//10 # if orig==sum: # print("number is armstrong") # else: # print("number is not armstrong") #second way # n=int(input("enter the number \n")) # sum=0 # order=len(str(n)) # copy_n=n # while(n>0): # digit=n%10 # sum+=digit**order # n=n//10 # if(sum==copy_n): # print(f"{copy_n}is an armstrong number") # else: # print(f"{copy_n}is not an armstrong number") #third way for i in range(1001): num=i #i value store in num result=0 n=len(str(i)) while(i!=0): digit=i%10 result=result+digit**n i=i//10 if num==result: print(num)
def longest_common_prefix(strs): def is_common_prefix(strs, length): str1 = strs[0][:length] for i in range(1, len(strs)): if not strs[i].startswith(str1): return False return True if not strs: return "" min_len = len(min(strs, key=len)) low, high = 1, min_len # The binary search on the length of the prefix on the first word while low <= high: mid = (low + high) // 2 if is_common_prefix(strs, mid): low = mid + 1 else: high = mid - 1 return strs[0][:high] if __name__ == '__main__': n = int(input()) input_string = list(input().strip().split()) print(longest_common_prefix(input_string))
"""Using the random module, generates two positive one-digit numbers. Displays a question to the user incorporating those numbers, e.g. “What is the sum of x and y?”. Uses random to generate +, -, or * as the operators. Conducts error-checking on the answer and notifies the user whether the answer is correct or not. At the end gives a running total, e.g. "You got 10 out of 10" You will do the math as asked and input the answer. If you are wrong you will be told that is incorrect, if you are right, you will be told as such. At the end of the quiz, you will getting a running total of correct answers. """ import random from operator import add, sub, mul name = input("What is your name? ") print("Hello, {}. You will be completing a quiz that will ask you 10 questions which will test you on adding, subtracting and multiplying two numbers together.".format(name)) score = 0 for count in range(10): ops = {'+': add, '-': sub, 'x': mul} op = random.choice(list(ops.keys())) x = random.randint(1,9) y = random.randint(1,9) print("What is {} {} {}? ".format(x, op, y)) question = int(input()) answer = ops[op](x,y) if question == answer: print("Well done, this is correct!") score += 1 else: print("Sorry, but this is incorrect.") print("Well done {}! You have completed the quiz. Your final score {} out of 10.".format(name, score))
# # a='qwert123' # # s=('q','2','4') # # d=['w','1','2','5'] # # f={'y','e','q','3'} # # g={'name':'小柒','are':'女','log':'12'} # # print('q'in a) # # print('q'in d) # # print('log'in g) # # # # money=77 # # # # if(money<=100): # # print('找富婆') # # elif(money<200): # # print('何智彬鸭鸭包邮') # # elif (money<1000): # # print('李森林吹牛b') # # elif(money<10000): # # # print('森林当鸭') # # # else: # # # print('让国服瑶妹当鸡') # # # # # # for i in range(100): # # # print(i) # # # print('找富婆') # # # # # # print(list(range(1,2))) # # # i=2 # # while(i<20): # # print(i) # # i += 1 # # # while True: # # # print('') # # for i in range(1,11): # if i in [1,3,6]: # continue # print(i) # print('森林骚') # # for i in range(1,11): # if i in [1,3,6]: # continue # print(i) # print('找富婆') # # -*- coding: utf-8 -*- # # for m in range(1,10): # # for n in range(1,10): # # print('%s×%s=%s'%(m,n,m*n)) # for i in range(1, 10): # for j in range(1, i + 1): # print('{}x{}={}\t'.format(j, i, i * j), end='') # print() # for i range(1,11) # # # def div(a,b): # if (b == 0): # print('shao') # else: # print(a / b) # div(3,0) # div(4,9) # # def shao(gfhl): # res = '7' # return res # a = shao('') # print(a) # def s(a,b): # return a+b # c = s(3,7) # print(c) # def a(t=1,o=2): # return t/o # print(a(1,3)) # def s(a,*args,b=10,**kwargs): # print(a) # print(b) # print(args) # print(kwargs) # # s(1,2,4,5,6,7,name="shao",age=10,b=2) # i%10 == 5 个位数去5 # i//10%10 == 5 十位数去5 # i//100%10 == 5 百位数去5 # # i //1000 ==5 千位数去5 # for i in range(1,10001): # if (i%10 == 5 or i//10%10 == 5 or i//100%10 == 5 or i //1000 ==5): # continue # print(i) # q = open('a.txt','w') # q.write('hdfdfh') # # c=10 # # def a(): # global c # c=20 # a() # print(c) # # a='123,45,678,90,261,91,125' # a=a.replace(',',',') # print(a.split(',')) # for i in range(1,10): # for j in range(1,i+1): # print('{} x {} = {}'.format(j,i,j*i),end='\t') # print() # # q=[1,23,4,5,6,7,8,9,0] # q[0]=10 # q.append(1000000) # q.insert(3,999) # import random # # # l = [10,1,35,61,89,36,55] # # 依次比较相邻的两个数据,如果前边的数据比后边的大, 则交换两个数据的位置,直到把最大的数据都放到最后第一次排序结束, # 第二次排序重复第一次排序的动作,把第二大的放到倒数第二的位置,依次类推,直到所有的数据都排好序为止 # for i in range(len(l)-1,0,-1): # i代表最后一个未排好序的数据下标 # for j in range(0,i): # j 代表每次循环时,当前位置的下标 # if(l[j] > l[j+1]): # 比较当前位置和下一个位置的数据大小,如果当前位置大于下个位置,则交换两个数据的位置 # l[j],l[j+1] = l[j+1],l[j] # 交换两个数据的位置 # # print(l) # i%10 == 5 个位数去5 # i//10%10 == 5 十位数去5 # i//100%10 == 5 百位数去5 # i //1000 ==5 千位数去5 # for i in range(1,10001): # if (i%10 == 5 or i//10%10 == 5 or i//100%10 == 5 or i //1000 ==5): # continue # print(i) # i = 1 # while(i<10): # print(i) # i += 1 # #打印出100以内可以被3整除的数 # # for i in range(1,101):# i在1-100这个范围内依次取值 # # if (i % 3 == 0):# 如果i除以3取余是0,(表示可以除尽) # # print(i)#可以得到 # # #计算1-100的和 即1+2+3....+100 # # a=0#赋值 # # for i in range(1,101):#i在1-100这个范围内依次取值 # # a+=i #(等同于a=a+i a+=1等同于a=a+1) # # print(a) # # class s_xin(): # # a = 8 # # def replace(self): # print('1') # # def split(self): # print('李森林JJN') # # # sx=s_xin() # # sx.a='dis' # # sx.replace() # # sx.split() # import requests # # ''' # 1、编写一个返回随机手机号的方法 # def phoe(): # import random # # q = random.choices("0123456789", k=8) # print(('135')+(''.join(q))) # phoe() # # import random # a=('134','187','199','178') # d=random.choice(a) # #print(d) # f=random.choices('1234567890',k=8) # g=''.join(f) # #print(g) # print(d+g) # def phoe(): # s=("135","189","178","199","134") # a=print(random.choice(s)) # #print(a) # q = random.choices("0123456789", k=8) # f=''.join(q) # # # 2、编写一个返回指定长度和内容的随机字符串方法 # # def s6(): # # import random # # q = random.choices("0123456789ggfdgfrh", k=6) # # print(''.join(q)) # # s6() # # def s6(s,d): # import random # q = random.choices(s,k=d) # print(''.join(q)) # s6("jfdfdjf34325",5) # 3、 # 编写一个返回随机姓名的方法 # ''' # 100逢七过 7的倍数或者以7结尾就说过 # for i in range(1,101): # import random # # # def random_name(): # xing_list = ["赵","钱","孙","李","周","武","郑","王","欧阳","诸葛","轩辕","上官","司徒"] # zi_list = "花赤橙黄绿青蓝紫冬梅建国华世凯" # xing = random.choice(xing_list) # zi_length = random.randint(1,2) # res = random.choices(zi_list, k=zi_length) # zi=''.join(res) # return xing + zi#return此将数据返回random_name # # print(random_name()) # print('我正测登陆') # try: # r = open('t.txt','r') # except (Exception) as 错误详情1: # print(错误详情1) # print('报错1') # try: # print(1 / 0) # except (Exception) as 错误详情2: # print(错误详情2) # print('报错2') # else: # print("整个程序没错") # finally: # print('不管有没错误都运行') # print('测试结束') s='123678356598' l='687987' print(s)
def domain_name(url): url = url.replace('http://', '') url = url.replace('https://', '') url = url.replace('www.', '') url = url.split('.') return url[0] print(domain_name("http://google.com")) print(domain_name("http://google.co.jp")) print(domain_name("www.xakep.ru")) print(domain_name("https://youtube.com"))
while True: try: n = input("Please input integer: ") n = int(n) break except ValueError: print("Input not integer, please try again.") print("Correct input") # until user correct input, then run out of the loop
import random import string SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 } path = '/Users/Xeus/my-project/MIT-Python-6.001x/Week_04/PS4/' WORDLIST_FILENAME = path + "words.txt" def loadWords(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print("Loading word list from file...") # inFile: file inFile = open(WORDLIST_FILENAME, 'r') # wordList: list of strings wordList = [] for line in inFile: wordList.append(line.strip().lower()) print(" ", len(wordList), "words loaded.") return wordList def getFrequencyDict(sequence): """ Returns a dictionary where the keys are elements of the sequence and the values are integer counts, for the number of times that an element is repeated in the sequence. sequence: string or list return: dictionary """ # freqs: dictionary (element_type -> int) freq = {} for x in sequence: freq[x] = freq.get(x, 0) + 1 return freq chk = {'h': 1, 't': 2, 'u': 2, 'o': 2, 'a': 1, 'y': 1, 'c': 2, 'z': 1} word = 'chayote' temp = [] for i in chk: temp.append(chk[i]) print(sum(temp))
balance = 42 annualInterestRate = 0.2 monthlyPaymentRate = 0.04 month = 0 while month < 12: month += 1 minimum_paid = monthlyPaymentRate * balance unpaid_b = balance - minimum_paid interest = (annualInterestRate / 12) * unpaid_b balance = unpaid_b + interest balance = round(balance, 2) print('Month ', month, 'Remaining balance is', balance) print('Remaining Balance:', balance)
import datetime class Person(object): def __init__(self, name): """crete person called name""" self.name = name self.birthday = None self.lastname = name.split(' ')[-1] def get_lastname(self): """return self's lastname""" return self.lastname def set_birthday(self, month, day, year): self.birthday = datetime.date(year, month, day) def get_age(self): """return self's current age in days""" if self.birthday is None: raise ValueError return (datetime.date.today() - self.birthday).days def __lt__(self, other): """return True if self's name is lexicographically less than other's name, False otherwise""" if self.lastname == other.lastname: return self.name < other.name return self.lastname < other.lastname def __str__(self): """return self's name""" return self.name # example usage p1 = Person('Mark Zuckerberg') p1.set_birthday(5, 14, 84) p2 = Person('Drew Houston') p2.set_birthday(3, 4, 83) p3 = Person('Bill Gates') p3.set_birthday(10, 28, 55) p4 = Person('Andrew Gates') p5 = Person('Steve Wozniak') person_list = [p1, p2, p3, p4, p5] for ele in person_list: print(ele) print('-------------') person_list.sort() for ele in person_list: print(ele) class MITPerson(Person): # class variable next_id_num = 0 def __init__(self, name): # using init method from parent class Person.__init__(self, name) self.id_num = MITPerson.next_id_num MITPerson.next_id_num += 1 def get_id_num(self): return self.id_num def __lt__(self, other): return self.id_num < other.id_num def speak(self, utterance): return (self.get_lastname() + ' says: ' + utterance) m3 = MITPerson("Mark Zuckerburg") Person.set_birthday(m3, 5, 14, 84) m2 = MITPerson("Drew Houston") Person.set_birthday(m2, 3, 14, 83) m1 = MITPerson("Bill Gates") Person.set_birthday(m1, 10, 28, 55) MITPerson_list = [m1, m2, m3] print(m3) print(m3.speak("I'm invester")) print("-----------------------") # class student which is inherit from MITPerson class Student(MITPerson): pass # Create Undergraduate MIT class which is inherit from Student class UG(Student): def __init__(self, name, classYear): # using MITPerson init method MITPerson.__init__(self, name) self.year = classYear def get_class(self): return self.year def speak(self, utterance): return MITPerson.speak(self, "Dude, " + utterance) # Create class Grad which is inherit from MITPerson class Grad(Student): pass class TransferStudent(Student): pass def isStudent(obj): return isinstance(obj, Student) s1 = UG("Matt Damon", 2017) s2 = UG("Ben Affleck", 2017) s3 = UG("Lin Miranda", 2018) s4 = Grad("Leonardo Di Carpio") student_list = [s1, s2, s3, s4] print(s1) print(s1.get_class()) print(s1.speak("Where is the quiz?")) print(s2.speak("I have no clue!")) print("-----------------------") class Professor(MITPerson): def __init__(self, name, department): MITPerson.__init__(self, name) self.department = department def speak(self, utterance): new_utterance = "In course " + self.department + " we say " return MITPerson.speak(self, new_utterance, utterance) def lecture(self, topic): return self.speak("It is obviuos that " + topic) faculty = Professor("Doctor Arrogant", "six") print(s1.speak("Hi, there"))
import random class Animal(object): def __init__(self, age): self.age = age self.name = None def get_age(self): return self.age def get_name(self): return self.name def set_age(self, new_age): self.age = new_age def set_name(self, new_name): self.name = new_name def __str__(self): return 'animal: ' + str(self.name) + " : " + str(self.age) # Inheritance class Cat(Animal): def speak(self): print("Meowwww...") # method overriding from parent class def __str__(self): return 'Cat: ' + str(self.name) + " : " + str(self.age) class Rabbit(Animal): def speak(self): print("Meeepp...") # method overriding from parent class def __str__(self): return 'Rabbit: ' + str(self.name) + " : " + str(self.age) # Create class Person which inherit from Animal class Person(Animal): def __init__(self, name, age): Animal.__init__(self, age) # call Animal constructor Animal.set_name(self, name) # call Animal Method self.friends = [] # add new data attribute def get_friends(self): return self.friends def add_friend(self, friend_name): if friend_name not in self.friends: self.friends.append(friend_name) def speak(self): print('Hello') def age_diff(self, other): diff = self.get_age() - other.get_age() if self.age > other.age: print(self.name, "is", diff, "years older than", other.name) else: print(self.name, "is", -diff, "years younger than", other.name) # overide Animal's method def __str__(self): return 'Person: ' + str(self.name) + " : " + str(self.age) # Create student class which inherit from Person class Student(Person): def __init__(self, name, age, major=None): # inherit Person and Animal attributes Person.__init__(self, name, age) self.major = major def change_major(self, major): self.major = major def speak(self): r = random.random() if r < 0.25: print('I have homework') elif 0.25 <= r < 0.5: print("I need to slepp") elif 0.5 <= r < 0.75: print("I should eat") else: print("I am watching TV") def __str__(self): return 'Student: ' + str(self.name) + " : " + str(self.age) + " : " + self.major platoo = Cat(2) platoo.set_name("Platoo") print(platoo) print(platoo.speak()) mojo = Rabbit(3) mojo.set_name("Mojo") print(mojo) print(mojo.speak()) francis = Animal(4) # print(francis.speak()) # error, cannot get method from child class eric = Person('Eric', 45) teerapat = Person("", 33) teerapat.set_name("Teerapat") print(eric.speak()) print(eric.age_diff(teerapat)) fred = Student('Fred', 18, 'Course VI') print(fred) print(fred.speak()) print(fred.speak()) print(fred.speak()) print(fred.speak())
animals = {'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') # print(animals) def how_many(aDict): temp = [] sub_list = [] for i in aDict: temp.append(aDict[i]) for j in temp: sub_list.append(j) answer = sum(sub_list, []) return len(answer) print(how_many(animals)) # MIT answer def how_many2(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many individual values are in the dictionary. ''' result = 0 for value in aDict.values(): # Since all the values of aDict are lists, aDict.values() will # be a list of lists result += len(value) return result def how_many3(aDict): ''' Another way to solve the problem. aDict: A dictionary, where all the values are lists. returns: int, how many individual values are in the dictionary. ''' result = 0 for key in aDict.keys(): result += len(aDict[key]) return result
x = int(input('Please think of a number between 0 and 100!')) epsilon = 0 guess_range = 0 high = x low = answer = (high + low) / 2 print("Is your secret number 50?") print("Enter 'h' to indicate the guess is too high.", end=' ') print("Enter 'l' to indicate the guess is too low.", end=' ') print("Enter 'c' to indicate to indicate I guessed correctly.", end=' ') while abs(answer - x) >= epsilon: checking = input() if checking not in 'hlc': print('Sorry, I did not understand your input.') if checking == 'h': low = mid guess_range = (high - low) / 2 checking_range = guess_range + low print('Is your secret number ', str(checking_range), '?') if checking == 'l': high = mid
print('Please think of a number between 0 and 100!') num_guesses = 0 low = 0 high = 100 answer = int((high + low) / 2.0) checking = '' while checking != 'c': answer = int((high + low) / 2.0) print("Is your secret number ", answer, '?') print("Enter 'h' to indicate the guess is too high.", end=' ') print("Enter 'l' to indicate the guess is too low.", end=' ') print("Enter 'c' to indicate to indicate I guessed correctly.", end=' ') checking = input() if checking not in 'hlc': print('Sorry, I did not understand your input.') if checking == 'h': high = answer answer = int((high + low) / 2) if checking == 'l': low = answer answer = int((high + low) / 2) if checking == 'c': break print('Game over. Your secret number was:', answer)
def fib_efficient(n, d): """ n = number of fibonacci that want to calculate d = base case dictionanries """ if n in d: return d[n] else: answer = fib_efficient(n-1, d) + fib_efficient(n-2, d) d[n] = answer return answer # base case d = {1: 1, 2: 2} # fib(1) = 1, fib(2) = 2 print(fib_efficient(8, d))
# we can iterate over string using for-loop s = 'Hello World' for char in s: print(char) print('-------------------------') # or we can iterate over range of length for i in range(len(s)): print(s[i])
def hasPalindromePermutation(input): """ Check if any of a string's permutations are a palindrome e.g. Input: rraceca Output: true ('racecar' is a palindrome and permutation of input) Runtime complexity O(N) Space complexity O(N) """ asciiChars = [0 for i in range(128)] for c in input: asciiChars[ord(c)] += 1 seenOneOdd = False for c in asciiChars: if c % 2 != 0: if seenOneOdd: return False seenOneOdd = True return True print(hasPalindromePermutation('racerac')) print(hasPalindromePermutation('abcdefg'))
#Google ''' Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than one dupplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1. Sample Input: a = [2, 1, 3, 5, 3, 2] Sample Output: FirstDuplicate(a) = 3 There are two duplicates: number 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3. ''' def FirstDuplicate(a): dic = {} for i in a: if i not in dic: dic[i] = 1 else: return i else: return -1
with open("day09") as file: stream = file.readline() garbage = False ignorenext = False grp = 0 grp_depth = 0 garbage_count = 0 for char in stream: if garbage == True and char != "!" and char != ">" and not ignorenext: garbage_count += 1 if ignorenext: ignorenext = False elif char == "<": garbage = True elif char == ">": garbage = False elif garbage == True and char == "!": ignorenext = True elif char == "{" and garbage == False: grp_depth += 1 elif char == "}" and garbage == False: grp += grp_depth grp_depth -= 1 # Part 1 print(grp) # Part 2 print(garbage_count)
def findItinerary(tickets): from collections import defaultdict graph=defaultdict(list) # 그래프를 역순으로 구성해서 pop사용 for a,b in sorted(tickets,reverse=True): graph[a].append(b) visit=[] def dfs(a): # 마지막값(역순으로해서 pop)을 어휘 순으로 방문 while graph[a]: dfs(graph[a].pop()) visit.append(a) dfs('JFK') # 역순으로 그래프를 구성했으니 뒤집어서 리턴 return visit[::-1] print(findItinerary([["MUC", "LHR"], ["JFK", "MUC"], ["SFO", "SJC"], ["LHR", "SFO"]])) print(findItinerary([["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]))
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def mergeTwoLists(self,l1: ListNode, l2: ListNode) -> ListNode: if (not l1) or (l2 and l1.val>l2.val): l1,l2=l2,l1 if l1: l1.next=self.mergeTwoLists(l1.next,l2) return l1 l1=ListNode([1,2,4]) l2=ListNode([1,3,4]) # print(mergeTwoLists(self,l1,l2))
def numIslands(matrix): def dfs(i,j): # 육지가 아니면 종료 if i < 0 or i >= len(matrix) or j < 0 or j >= len(matrix[0]) or matrix[i][j] != "1": return matrix[i][j]=0 dfs(i+1,j) dfs(i-1,j) dfs(i,j+1) dfs(i,j-1) cnt=0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]=="1": dfs(i,j) # 모든 육지를 탐색 후 카운트1증가 cnt+=1 return cnt matrix = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","0"] ] print(numIslands(matrix))
# class Solution: def evalRPN(tokens): num=[] cal=['-','+','*','/'] for i in tokens: if i not in cal: num.append(int(i)) else: num1=num.pop() num2=num.pop() print(num2,num1,i) if i=='+': num.append(num2+num1) elif i=='-': num.append(num2-num1) elif i=='*': num.append(num2*num1) elif i=='/': num.append(int(num2/num1)) return num[0] tokens=["4","-2","/","2","-3","-","-"] # tokens=["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"] # tokens=["2", "1", "+", "3", "*"] # tokens=["4", "13", "5", "/", "+"] print(evalRPN(tokens))
"""함수의 적분 사다리꼴 방법을 이용한 함수의 적분량 계산 """ import numpy as np import matplotlib.pyplot as plt from scipy.integrate import trapezoid h = 0.01 min_x = 1 max_x = 5 def f(x): return 3 * x ** 2 + 2 * x + 6 def int_f(func, x_min, x_max, h): output = 0 x = np.arange(x_min, x_max, h) for idx in range(len(x) - 1): output += (func(x[idx]) + func(x[idx + 1])) * h / 2 return output if __name__ == "__main__": x = np.linspace(0, 8) x_inf = np.arange(min_x, max_x, h) y_inf = f(x_inf) x_inf = np.concatenate(([x_inf[0]], x_inf, [x_inf[-1]])) y_inf = np.concatenate(([0], y_inf, [0])) plt.plot(x, f(x)) plt.fill(x_inf, y_inf, "r", alpha=0.5) plt.text(0.1, 55, f"TZ int: {int_f(f, min_x, max_x, h):.3f}") plt.text(0.1, 65, f"SCIPY: {trapezoid(f(x_inf), x_inf, h):.3f}") plt.grid(True) plt.xlim(0, 8) plt.ylim(0, 200) plt.show()
"""개미집단 최적화 """ import matplotlib.pyplot as plt import numpy as np area = np.ones([20, 20]) # 지역 생성 start = (1, 1) # 개미 출발지점 goal = (19, 14) # 도착해야 하는 지점 path_count = 40 # 경로를 만들 개미 수 path_max_len = 20 * 20 # 최대 경로 길이 pheromone = 1.0 # 페로몬 가산치 volatility = 0.3 # 스탭 당 페로몬 휘발율 def get_neighbors(x, y): """x, y와 이웃한 좌표 목록 출력""" max_x, max_y = area.shape return [ (i, j) for i in range(x - 1, x + 2) for j in range(y - 1, y + 2) if (i != x or j != y) and (i >= 0 and j >= 0) and (i < max_x and j < max_y) ] def ant_path_finding(): """개미 경로 생성""" path = [start] x, y = start count = 0 while x != goal[0] or y != goal[1]: count += 1 if count > path_max_len: return None neighbors = get_neighbors(x, y) values = np.array([area[i, j] for i, j in neighbors]) p = values / np.sum(values) x, y = neighbors[np.random.choice(len(neighbors), p=p)] while (x, y) == path[-1]: x, y = neighbors[np.random.choice(len(neighbors), p=p)] path.append((x, y)) return path def step_end(path): """경로를 따라 페로몬을 더하고 전 지역의 페로몬을 한번 휘발시킴""" global area if path is None: return for x, y in set(path): area[x, y] += pheromone / len(set(path)) area[:, :] = area * (1 - volatility) return if __name__ == "__main__": # 계산 및 그래프 작성 count = 0 while count < path_count: path = ant_path_finding() if path is None: continue count += 1 print(f"Ant Pathfinding: {count} / {path_count}") step_end(path) # 최종 경로와 페로몬 맵 그리기 x, y = [], [] for _x, _y in path: x.append(_x) y.append(_y) plt.plot(x, y, "b", alpha=0.3) plt.imshow(area.T, cmap="Greens") plt.xlim(0, 20) plt.ylim(0, 20) plt.show()
''' Character-Level LSTM in PyTorch In this code, I'll construct a character-level LSTM with PyTorch. The network will train character by character on some text, then generate new text character by character. This model will be able to generate new text based on the text from any provided book! This network is based off of Udacity RNN mini project and which is in turn based off of Andrej Karpathy's post on RNNs and implementation in Torch. Below is the general architecture of the character-wise RNN. ''' import numpy as np import torch from torch import nn import torch.nn.functional as F import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt ## Pre-processing the data # one-hot encodeing def one_hot_encode(arr, n_labels): ''' Each character is converted into an integer (via our created dictionary) and then converted into a column vector where only it's corresponding integer index will have the value of 1 and the rest of the vector will be filled with 0's. Arguments: arr: An array of integers to be encoded, a Numpy array of shape -> (batch_size, sequence_length) n_labels: Dimension of the converted vector, an integer Returns: ont_hot: Encoded vectors that representing the input arr integers, a Numpy array of shape -> (batch_size, sequence_length, n_labels) ''' # Initialize the encoded array # at this stage of shape (batch_size * sequence_length, n_labels) one_hot = np.zeros((np.multiply(*arr.shape), n_labels), dtype=np.float32) # Fill the appropriate elements with ones one_hot[np.arange(one_hot.shape[0]), arr.flatten()] = 1.0 # Finally reshape it to get back the original array (but each element changed from # integer to an array, or an one-hot vector with shape) one_hot = one_hot.reshape((*arr.shape, n_labels)) return one_hot ## Create training batches def get_batches(arr, batch_size, seq_len): ''' Create a generator that returns batches of size batch_size x seq_len from arr. If: N --> batch size M --> number of time steps in a sequence (sequence length) K --> total number of batches L --> total length of text Then has a relationship: L = N * M * K Arguments: arr: Array of encoded text batch_size: Number of sequence per batch seq_len: Number of encoded chars in a sequence Returns: yield a batch ''' # total number of full batches n_batches = len(arr) // (batch_size * seq_len) # keep only enough characters to make full batches arr = arr[:batch_size * seq_len * n_batches] # reshape into batch_size rows arr = arr.reshape((batch_size, -1)) # change to dtype int64 (long), otherwise will occur RuntimeError in lstm training: # Expected object of scalar type Long but got scalar type Int for argument #2 'target' arr = arr.astype('int64') # iterate over the batches using a window of size seq_len for n in range(0, arr.shape[1], seq_len): x = arr[:, n: n+seq_len] y = np.zeros_like(x) try: y[:, :-1], y[:, -1] = x[:, 1:], x[:, n+seq_len] except IndexError: y[:, :-1], y[:, -1] = x[:, 1:], x[:, 0] yield x, y ## LSTM Model class CharRNN(nn.Module): def __init__(self, tokens, n_hidden=256, n_layers=2, drop_prob=0.5, lr=0.001): ''' Initialize CharRNN model. Arguments: tokens: Number of unique characters, or volume of vocabulary n_hidden: Number of neurons in a hidden layer n_layers: Number of hidden layers in RNN drop_prob: Dropout rate lr: Learning rate ''' super().__init__() self.drop_prob = drop_prob self.n_layers = n_layers self.n_hidden = n_hidden self.lr = lr # creating character dictionaries self.chars = tokens self.int2char = dict(enumerate(self.chars)) self.char2int = {ch: ii for ii, ch in self.int2char.items()} # input_size is the total number of characters (as the vector length) input_size = len(self.chars) # define the LSTM layer self.lstm = nn.LSTM(input_size, n_hidden, n_layers, dropout=drop_prob, batch_first=True) # define a dropout layer self.dropout = nn.Dropout(drop_prob) # define a fully connected layer self.fc = nn.Linear(n_hidden, input_size) def forward(self, x, hidden): ''' Forward pass through the network. These inputs are x, and the hidden/cell state. Arguments: x: Shaped (seq_len, batch, input_size) hidden: Shaped (num_layers * num_directions, batch, hidden_size) Returns: out: Shaped (seq_len, batch, num_directions * hidden_size) hidden: Shaped (num_layers * num_directions, batch, hidden_size) ''' # Get LSTM outputs # reshape hidden state hidden = tuple([h.permute(1, 0, 2).contiguous() for h in hidden]) lstm_out, hidden = self.lstm(x, hidden) # add dropout layer out = self.dropout(lstm_out) # shape the output to be (batch_size * seq_len, hidden_dim) out = out.contiguous().view(-1, self.n_hidden) out = self.fc(out) # return the final output and the hidden state hidden = tuple([h.permute(1, 0, 2).contiguous() for h in hidden]) return out, hidden def init_hidden(self, batch_size): ''' Initialize hidden state. Create two new tensors with sizes n_layers x batch_size x n_hidden, initialized to zero, for hidden state and cell state of LSTM Arguments: batch_size: batch size, an integer Returns: hidden: hidden state initialized ''' weight = next(self.parameters()).data if train_on_multi_gpus or train_on_gpu: hidden = (weight.new(batch_size, self.n_layers, self.n_hidden).zero_().cuda(), weight.new(batch_size, self.n_layers, self.n_hidden).zero_().cuda()) else: hidden = (weight.new(batch_size, self.n_layers, self.n_hidden).zero_(), weight.new(batch_size, self.n_layers, self.n_hidden).zero_()) return hidden # Utility to plot learning curve def loss_plot(losses, valid_losses): ''' Plot the validation and training loss. Arguments: losses: A list of training losses valid_losses: A list of validation losses Returns: No returns, just plot the graph. ''' # losses and valid_losses should have same length assert len(losses) == len(valid_losses) epochs = np.arange(len(losses)) # plt.plot(epochs, losses, 'r-', valid_losses, 'b-') # train the model! def train(net, data, epochs=10, batch_size=16, seq_len=50, lr=0.001, clip=5, val_frac=0.1, every=10): ''' Training a network and serialize it to local file. Arguments: net: CharRNN network data: text data to train the network epochs: Number of epochs to train batch_size: Number of mini-sequences per mini-batch, aka batch size seq_len: Number of character steps per mini-batch lr: learning rate clip: gradient clipping val_frac: Fraction of data to hold out for validation every: Number of steps for printing training and validation loss ''' # training mode net.train() # define optimizer and loss opt = torch.optim.Adam(net.parameters(), lr=lr) criterion = nn.CrossEntropyLoss() # creating training and validation data val_idx = int(len(data) * (1 -val_frac)) data, val_data = data[: val_idx], data[val_idx:] # count total time steps: counter = 0 try: n_chars = len(net.chars) except AttributeError: # using DataParallel wrappper to use multiple GPUs n_chars = len(net.module.chars) if train_on_multi_gpus: net = torch.nn.DataParallel(net).cuda() elif train_on_gpu: net = net.cuda() else: print('Training on CPU...') # list to contain losses to be plotted losses = [] vlosses = [] for e in range(epochs): # initialize hidden state try: hidden = net.init_hidden(batch_size) except: # if using DataParallel wrapper to use multiple GPUs hidden = net.module.init_hidden(batch_size) for x, y in get_batches(data, batch_size, seq_len): counter += 1 # One-hot encode our data and make them Torch tensors x = one_hot_encode(x, n_chars) inputs, targets = torch.from_numpy(x), torch.from_numpy(y) if train_on_gpu or train_on_multi_gpus: inputs, targets = inputs.cuda(), targets.cuda() # Creating new variables for the hidden state, otherwise we'd backprop # through the entire training history. hidden = tuple([each.data for each in hidden]) # zero acculated gradients net.zero_grad() # reshape inputs shape because not using batch_first=True as in solution code: ## inputs = inputs.permute(1, 0, 2) ## inputs = inputs.contiguous() # get output from model output, hidden = net(inputs, hidden) # calculate the loss and perform backprop loss = criterion(output, targets.view(batch_size * seq_len)) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs nn.utils.clip_grad_norm(net.parameters(), clip) opt.step() # loss stats if counter % every == 0: # get validation loss try: val_h = net.init_hidden(batch_size) except AttributeError: # if using DataParallel wrapper to use multipl GPUs val_h = net.module.init_hidden(batch_size) val_losses = [] net.eval() for x, y in get_batches(val_data, batch_size, seq_len): # ont-hot encode our data and make them Torch tensors x = one_hot_encode(x, n_chars) val_h = tuple([each.data for each in val_h]) inputs, targets = torch.from_numpy(x), torch.from_numpy(y) if train_on_gpu or train_on_multi_gpus: inputs, targets = inputs.cuda(), targets.cuda() output, val_h = net(inputs, val_h) val_loss = criterion(output, targets.view(batch_size * seq_len)) val_losses.append(val_loss.item()) # append loss into losses list losses.append(loss) vlosses.append(np.mean(val_losses)) net.train() print(f'Epoch: {e+1}/{epochs}...', f'Step: {counter}...', f'Loss: {loss.item():.4f}...', f'Val Loss: {np.mean(val_losses):.4f}') # decide file name by hyperparameters try: n_hidden = net.n_hidden n_layers = net.n_layers tokens = net.chars state_dict = net.state_dict() except AttributeError: # using DataParallel n_hidden = net.module.n_hidden n_layers = net.module.n_layers tokens = net.module.chars state_dict = net.module.state_dict() checkpoint = {'n_hidden': n_hidden, 'n_layers': n_layers, 'state_dict': state_dict, 'tokens': tokens} model_name = f'RNN-{n_hidden}-{n_layers}-{batch_size}-{seq_len}-{lr}-{clip}.net' with open(model_name, 'wb') as f: torch.save(checkpoint, f) # plot loss curve loss_plot(losses, vlosses) # predict using the trained model and top-k sampling def predict(net, char, hidden=None, top_k=None): ''' Predict next character given the trained model and a starting sequence. Parameters: net: The training model char: A character hidden: Hidden state top_k: Choose a K (integer) to decide some K most probable characters Returns: The encoded value of the predicted char and the hidden state ''' # tensor inputs try: num_tokens = len(net.chars) x = np.array([[net.char2int[char]]]) x = one_hot_encode(x, num_tokens) except AttributeError: # using DataParallel x = np.array([[net.module.char2int[char]]]) x = one_hot_encode(x, num_tokens) # conver numpy array to torch tensor inputs = torch.from_numpy(x) if train_on_gpu or train_on_multi_gpus: inputs = inputs.cuda() # detach hidden state from history hidden = tuple([each.data for each in hidden]) # get output of model output, hidden = net(inputs, hidden) # get output probabilities p = F.softmax(output, dim=1).data if train_on_gpu or train_on_multi_gpus: # move p back to cpu to use numpy p = p.cpu() # get top characters if top_k is None: top_ch = np.arange(num_tokens) else: p, top_ch = p.topk(top_k) top_ch = top_ch.numpy().squeeze() # select the likely next character with some element of randomness p = p.numpy().squeeze() char = np.random.choice(top_ch, p=p/p.sum()) # return the encoded value of the predicted char and the hidden state try: string = net.int2char[char] except AttributeError: # using DataParallel string = net.module.int2char[char] return string, hidden # Sample def sample(net, size, prime='The', top_k=None): ''' Sample a paragraph. Parameters: net: Trained model size: Length to be sampled prime: Starting words top_k: Use top_k or not Returns: A paragraph of sampled string ''' if train_on_gpu or train_on_multi_gpus: net.cuda() else: net.cpu() net.eval() # eval mode # First off, run through the prime characters chars = [ch for ch in prime] try: hidden = net.init_hidden(1) except AttributeError: # using DataParallel hidden = net.module.init_hidden(1) for ch in prime: char, hidden = predict(net, ch, hidden, top_k=top_k) chars.append(char) # Now pass in the previous character and get a new one for ii in range(size): char, hidden = predict(net, chars[-1], hidden, top_k=top_k) chars.append(char) return ''.join(chars) if __name__ == '__main__': ## We'll load text file and convert it into integers for our network to use. # open text file and read data as 'text' with open('data/stone.txt', 'r') as f: text = f.read() ## Tokenization # encode the text and map each character to an interger and vice versa # create two dictionaries: # 1. int2char, maps integers to characters # 2. char2int, maps characters to integers chars = tuple(set(text)) int2char = dict(enumerate(chars)) char2int = {ch: ii for ii, ch in int2char.items()} # encode the text to integer array encoded = np.array([char2int[ch] for ch in text]) # CUDA semantics: train_on_gpu = torch.cuda.is_available() train_on_multi_gpus = (torch.cuda.device_count() >= 2) gpus = torch.cuda.device_count() if train_on_multi_gpus: print(f"Tranning on {gpus} GPUs!") elif train_on_gpu: print('Training on GPU!') else: print('No GPU available, training on CPU; consider making n_epochs very small.') # hyperparameters: n_hidden = 1024 n_layers = 2 batch_size = 32 seq_len = 256 n_epochs = 20 lr = 0.001 clip = 5 # instantiate model net = CharRNN(chars, n_hidden, n_layers) total_params = sum(p.numel() for p in net.parameters() if p.requires_grad) print(f'Total trainable parameters: {total_params}') # train the model # Comment the line below if already trained, will add interface in the future. train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_len=seq_len, lr=lr, clip=clip, every=100) # Load the trained. The saved model name is saved in the format of # 'RNN-{n_hidden}-{n_layers}-{batch_size}-{seq_len}-{lr}-{clip}.net' # Here we have loaded in a model that trained over 20 epochs `rnn_20_epoch.net` with open(f'RNN-{n_hidden}-{n_layers}-{batch_size}-{seq_len}-{lr}-{clip}.net', 'rb') as f: checkpoint = torch.load(f) loaded = CharRNN(checkpoint['tokens'], n_hidden=checkpoint['n_hidden'], n_layers=checkpoint['n_layers']) loaded.load_state_dict(checkpoint['state_dict']) # sample from the trained model to obtain a novel! text = sample(loaded, 1000, top_k=5, prime='the') print(text)
print() print("Project: Linear Regression") print() print("Reggie is a mad scientist who has been hired by the local fast food joint to") print("build their newest ball pit in the play area. As such, he is working on") print("researching the bounciness of different balls to optimize the hole. Reggie is") print("running an experiment on bouncy balls of various sizes, and then fitting lines") print("to the data points he records. Reggie has heard of linear regression but needs") print("your help to implement a linear regression in Python.") print() print("Linear Regression is when you have a group of points on a graph, on which you") print("find a line that approximately resembles that group of points. A good Linear") print("Regression algorithm minimizes the error, the distance from each end to the") print("line. A line with the least error is the line that fits the data the best. We") print("call this a line of best fit.") print() print("We will use loops, lists, and arithmetic to create a function that will find a") print("line of best fit when given a set of data.") print() print("Part 1: Calculating Error") print() print("The line we will end up with will have a formula that looks like:") print() print(" y = m*x + b") print() print("m is the line's slope, and b is the intercept, where the line crosses the") print("y-axis.") print() print("Create a function, get_y(), that takes in m, b, and x and returns what the y") print("value would be for that x on that line!") print() print("def get_y(m, b, x):") print(" y = m*x + b") print(" return y") def get_y(m, b, x): y = m*x + b return y print() print("get_y(1, 0, 7)") print("y ==", get_y(1, 0, 7)) print() print("get_y(5, 10, 3)") print("y ==", get_y(5, 10, 3)) print() print("Reggie wants to try many different m values and b values and see which line") print("produces the least error. To calculate the error between a point and a line, he") print("wants a function called calculate_error(), which will take in m, b, and an [x,") print("y] point named point and return the distance between the line and the point.") print() print("To find the distance:") print() print(" 1. Get the x-value from the point and store it in a variable called x_point") print(" 2. Get the y-value from the point and store it in a variable called y_point") print(" 3. Use get_y() to get the y-value that x_point would be on the line") print(" 4. Find the difference between the y from get_y and y_point") print(" 5. Return the absolute value of the distance (You can use the built-in") print(" function abs() to do this.)") print() print("The distance represents the error between the line y = m*x + b and the point") print("given.") print() print("def calculate_error(m, b, point):") print(" x_point, y_point = point") print(" y = m*x_point + b") print(" distance = abs(y - y_point)") print(" return distance") def calculate_error(m, b, point): x_point, y_point = point y = m*x_point + b distance = abs(y - y_point) return distance print() print("Let's test this function!") print() print("this is a line that looks like y = x, so (3, 3) should lie on it. thus, error") print("should be 0:") print("calculate_error(1, 0, (3, 3))") print("distance ==", calculate_error(1, 0, (3, 3))) print("the point (3, 4) should be 1 unit away from the line y = x:") print("calculate_error(1, 0, (3, 4))") print("distance ==", calculate_error(1, 0, (3, 4))) print("the point (3, 3) should be 1 unit away from the line y = x - 1:") print("calculate_error(1, -1, (3, 3))") print("distance ==", calculate_error(1, -1, (3, 3))) print("the point (3, 3) should be 5 units away from the line y = -x + 1:") print("calculate_error(-1, 1, (3, 3))") print("distance ==", calculate_error(-1, 1, (3, 3))) print() print("Great! Reggie's datasets will be sets of points. For example, he ran an") print("experiment comparing the width of bouncy balls to how high they bounce:") print() print("datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]") datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)] print() print("The first data point, (1, 2), means that his 1cm bouncy ball bounced 2 meters.") print("The 4cm bouncy ball bounced 4 meters.") print() print("As we try to fit a line to this data, we will need a function called") print("calculate_all_error, which takes m and b that describe a line, and points, a set") print("of data like the example above.") print() print("calculate_all_error should iterate through each point in points and calculate") print("the error from that point to the line (using calculate_error). It should keep a") print("running total of the error, and then return that total after the loop.") print() print("def calculate_all_error(m, b, points):") print(" total_error = 0") print(" for point in datapoints:") print(" point_error = calculate_error(m, b, point)") print(" total_error += point_error") print(" return total_error") def calculate_all_error(m, b, points): total_error = 0 for point in datapoints: point_error = calculate_error(m, b, point) total_error += point_error return total_error print() print("Let's test this function!") print() print("every point in this dataset lies upon y=x, so the total error should be zero:") print("datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]") datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)] print("calculate_all_error(1, 0, datapoints)") print("total_error ==", calculate_all_error(1, 0, datapoints)) print() print("every point in this dataset is 1 unit away from y = x + 1, so the total error") print("should be 4:") print("datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]") datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)] print("total_error ==", calculate_all_error(1, 1, datapoints)) print() print("every point in this dataset is 1 unit away from y = x - 1, so the total error") print("should be 4:") "datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]" datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)] print("calculate_all_error(1, -1, datapoints)") print("total error ==", calculate_all_error(1, -1, datapoints)) print() print("the points in this dataset are 1, 5, 9, and 3 units away from y = -x + 1,") print("respectively, so total error should be 1 + 5 + 9 + 3 = 18") datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)] print("datapoints = [(1, 1), (3, 3), (5, 5), (-1, -1)]") print("calculate_all_error(-1, 1, datapoints))") print("total error ==", calculate_all_error(-1, 1, datapoints)) print() print("Great! It looks like we now have a function that can take in a line and Reggie's") print("data and return how much error that line produces when we try to fit it to the") print("data.") print() print("Our next step is to find the m and b that minimizes this error, and thus fits") print("the data best!") print() print("Part 2: Try a bunch of slopes and intercepts!") print() print("The way Reggie wants to find a line of best fit is by trial and error. He wants") print("to try a bunch of different slopes (m values) and a bunch of different") print("intercepts (b values) and see which one produces the smallest error value for") print("his dataset.") print() print("Using a list comprehension, let's create a list of possible m values to try.") print("Make the list possible_ms that goes from -10 to 10 inclusive, in increments of") print("0.1.") print() print("Hint: you can go through the values in the range(-100, 100) and multiply each") print("one by 0.1") print() print("possible_ms = [m * 0.1 for m in range(-100, 101)]") possible_ms = [m * 0.1 for m in range(-100, 101)] print() print("Now, let's make a list of possible_bs to check that would be the values from -20") print("to 20 inclusive, in steps of 0.1:") print() print("possible_bs = [b * 0.1 for b in range(-200, 201)]") possible_bs = [b * 0.1 for b in range(-200, 201)] print() print("We are going to find the smallest error. First, we will make every possible y") print("= m*x + b line by pairing all of the likely ms with all possible bs. We will") print("then see which y = m*x + b line produces the smallest total error with the data") print("stored in the datapoint.") print() print("First, create the variables that we will be optimizing:") print() print(" • smallest_error — this should start at infinity (float(inf)) so that any") print(" error we get at first will be smaller than our value of smallest_error") print(" • best_m — we can begin this at 0") print(" • best_b — we can start this at 0") print() print("We want to:") print() print(" • Iterate through each element m in possible_ms") print(" • For every m value, take every b value in possible_bs") print(" • If the value returned from calculate_all_error on this m value, this b value") print(" and data points are less than our current smallest_error.") print(" • Set best_m and best_b to be these values, and set smallest_error to this") print(" error.") print() print("By the end of these nested loops, the smallest_error should hold the smallest") print("error we have found, and best_m and best_b should be the values that produced") print("that smallest error value.") print() print("Print out best_m, best_b, and smallest_error after the loops.") print() print("datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)]") datapoints = [(1, 2), (2, 0), (3, 4), (4, 4), (5, 3)] print("smallest_error = float(\"inf\")") print("best_m = 0") print("best_b = 0") print() print("for m in possible_ms:") print(" for b in possible_bs:") print(" error = calculate_all_error(m, b, datapoints)") print(" if error < smallest_error:") print(" best_m = m") print(" best_b = b") print(" smallest_error = error") smallest_error = float("inf") best_m = 0 best_b = 0 print() for m in possible_ms: for b in possible_bs: error = calculate_all_error(m, b, datapoints) if error < smallest_error: best_m = m best_b = b smallest_error = error print("best m ==", best_m,) print("best b ==", best_b) print("smallest error ==", smallest_error) print() print("Part 3: What does our model predict?") print() print("The line that fits the data best has an m of 0.3 and a b of 1.7:") print() print(" y = 0.3x + 1.7") print() print("This line produced a total error of 5.") print() print("Using this m and this b, what does your line predict the bounce height of a ball") print("with a width of 6 to be? In other words, what is the output of get_y() when we") print("call it with:") print() print(" • m = 0.3") print(" • b = 1.7") print(" • x = 6") print() print("get_y(0.3, 1.7, 6)") print("y = ", get_y(0.3, 1.7, 6)) print() print("Our model predicts that the 6cm ball will bounce 3.5m.") print() print("Reggie can now use this model to predict the bounce of all kinds of sizes of") print("balls he may choose to include in the ball pit!") print()
#!/usr/bin/env python """ Demonstrates the cleaning and normalization of data. The Indian Diabetes dataset has 768 rows. However, many of them have zeros as values, which are wrong values, e.g. in the case of BloodPressure. Nobody has such blood pressure. ToDo: Instead of dropout these records, replace the zeros by the mean value of the feature The tests demonstrate that normalization improves the learning, avoiding erratic (up/down) evolutions of loss and accuracy. On the other hand, applying the standarization, the model stop working :-( ToDO: Why? Thanks to Jason Brownlee: https://machinelearningmastery.com/how-to-improve-neural-network-stability-and-modeling-performance-with-data-scaling/ """ __author__ = "Rui Humberto Pereira" __copyright__ = "Copyright 2021, RHP" __credits__ = ["Me","Jason Brownlee"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Rui Humberto Pereira" __email__ = "[email protected]" __status__ = "Development" from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam import pandas as pd from sklearn.model_selection import train_test_split import rhplib.datasets_pandas import rhplib.plot_functions param_epochs=50 param_learningrate=0.001 param_do_clean=True param_do_scaling=1 # 0-None, 1-Normalizatio and 2-Standardization # load the dataset using numpy #from numpy import loadtxt #dataset = loadtxt('../datasets/PimaIndiansDiabetesDatabase.csv', skiprows=1, delimiter=',') # split into input (X) and output (y) variables #X = dataset[:,0:8] #y = dataset[:,8] # load Pima dataset dataset = pd.read_csv('../datasets/PimaIndiansDiabetesDatabase.csv',delimiter=',',header=0) #print(dataset.head()) rhplib.datasets_pandas.plot_hist_dataset(dataset,100) if param_do_clean: #Clean the data dataset=rhplib.datasets_pandas.clean_pima_indian_diabetes_dataset(dataset) #print(dataset.head()) rhplib.datasets_pandas.plot_hist_dataset(dataset,100) if param_do_scaling==1: #Normalize the data dataset=rhplib.datasets_pandas.normalize(dataset); #tmp_dataset=tmp_dataset.drop(0, axis='index') dataset.to_csv("../datasets/tmp.csv",index=False) #print(dataset.head()) rhplib.datasets_pandas.plot_hist_dataset(dataset,100) elif param_do_scaling==2: #Standardization the data dataset=rhplib.datasets_pandas.standardization(dataset); #tmp_dataset=tmp_dataset.drop(0, axis='index') dataset.to_csv("../datasets/tmp.csv",index=False) #print(dataset.head()) rhplib.datasets_pandas.plot_hist_dataset(dataset,100) else: print('No data scaling!') # dataset_train, dataset_validation = train_test_split(dataset, test_size=0.1) print('Dataset Train:',len(dataset_train),'\nDataset validation:',len(dataset_validation)) #rhplib.datasets_pandas.plot_hist_col(dataset.Pregnancies,20) #rhplib.datasets_pandas.plot_hist_col(dataset.Age,120) #rhplib.datasets_pandas.plot_hist_col(dataset.Glucose,120) #rhplib.datasets_pandas.plot_hist_col(dataset.BloodPressure,120) # split into input (X) and output (y) variables X = dataset_train.values[:,0:8] y = dataset_train.values[:,8] X_validation = dataset_validation.values[:,0:8] y_validation = dataset_validation.values[:,8] # define the keras model model = Sequential() model.add(Dense(12, input_dim=8,activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) #Optimizer my_opt = Adam(learning_rate=param_learningrate) # compile the keras model (loss:binary_crossentropy,mse) model.compile(loss='mse', optimizer='adam',metrics=['accuracy']) # fit the keras model on the dataset train_history = model.fit(X, y, epochs=param_epochs, batch_size=10,validation_data=(X_validation,y_validation)) #plot the model performance train_loss = train_history.history['loss'] train_accuracy = train_history.history['accuracy'] test_loss = train_history.history['val_loss'] test_accuracy = train_history.history['val_accuracy'] rhplib.plot_functions.plot_train_and_test_loss_accuracy(train_loss, train_accuracy, test_loss, test_accuracy) # evaluate the keras model _, accuracy = model.evaluate(X, y) print('Accuracy: %.2f' % (accuracy*100))
#!/usr/local/bin/python3 # # choose_team.py : Choose a team of maximum skill under a fixed budget # # Code by: [PLEASE PUT YOUR NAMES AND USER IDS HERE] # # Based on skeleton code by D. Crandall, September 2019 # import sys def load_people(filename): people={} with open(filename, "r") as file: for line in file: l = line.split() people[l[0]] = [ float(i) for i in l[1:] ] return people # This function implements a greedy solution to the problem: # It adds people in decreasing order of "skill per dollar," # until the budget is exhausted. It exactly exhausts the budget # by adding a fraction of the last person. # def approx_solve(people, budget): solution=() for (person, (skill, cost)) in sorted(people.items(), key=lambda x: x[1][0]/x[1][1]): if budget - cost > 0: solution += ( ( person, 1), ) budget -= cost else: return solution + ( ( person, budget/cost ), ) return solution if __name__ == "__main__": if(len(sys.argv) != 3): raise Exception('Error: expected 2 command line arguments') budget = float(sys.argv[2]) people = load_people(sys.argv[1]) solution = approx_solve(people, budget) print("Found a group with %d people costing %f with total skill %f" % \ ( len(solution), sum(people[p][1]*f for p,f in solution), sum(people[p][0]*f for p,f in solution))) for s in solution: print("%s %f" % s)