text
stringlengths
37
1.41M
d ={'a' : 1,'b' : 2,'c' :3} for key in d: print(key, d[key]) print(d) d.clear() print(d) thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.popitem() print(len(d)) for x in thisdict: print(x) print(thisdict[x])
# Create a string and break it in exactly 140 characters headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" for headline in headlines: # Check if the len of your new string + the value of the next string would be <= 140 if len(news_ticker) + len(headline) <= 140: news_ticker += headline + " " else: # If we can't add the entire string otherwise will pass the value of 140, then we go by character for character in headline: if len(news_ticker) + len(character) <= 140: news_ticker += character else: break print(news_ticker) print(len(news_ticker)) print('\n') ## Your code should check if each number in the list is a prime number check_prime = [26, 39, 51, 53, 57, 79, 85] for number in check_prime: i = 2 while i < number: if number % i == 0: print("{} is not a prime number, because {} is a factor of {}".format(number, i, number)) break if i == (number - 1): print('{} is not prime'.format(number)) i += 1 print('\n')
# -*- coding: utf-8 -*- import scipy as sp import scipy.stats as st def friedman_test(*args): """ Performs a Friedman ranking test. Tests the hypothesis that in a set of k dependent samples groups (where k >= 2) at least two of the groups represent populations with different median values. Parameters ---------- sample1, sample2, ... : array_like The sample measurements for each group. Returns ------- F-value : float The computed F-value of the test. p-value : float The associated p-value from the F-distribution. rankings : array_like The ranking for each group. pivots : array_like The pivotal quantities for each group. References ---------- M. Friedman, The use of ranks to avoid the assumption of normality implicit in the analysis of variance, Journal of the American Statistical Association 32 (1937) 674–701. D.J. Sheskin, Handbook of parametric and nonparametric statistical procedures. crc Press, 2003, Test 25: The Friedman Two-Way Analysis of Variance by Ranks """ k = len(args) if k < 2: raise ValueError('Less than 2 levels') n = len(args[0]) if len(set([len(v) for v in args])) != 1: raise ValueError('Unequal number of samples') rankings = [] for i in range(n): row = [col[i] for col in args] row_sort = sorted(row, reverse=True) rankings.append([row_sort.index(v) + 1 + (row_sort.count(v) - 1) / 2. for v in row]) # print rankings rankings_avg = [sp.mean([case[j] for case in rankings]) for j in range(k)] rankings_cmp = [r / sp.sqrt(k * (k + 1) / (6. * n)) for r in rankings_avg] chi2 = ((12 * n) / float((k * (k + 1)))) * ( (sp.sum(r ** 2 for r in rankings_avg)) - ((k * (k + 1) ** 2) / float(4))) iman_davenport = ((n - 1) * chi2) / float((n * (k - 1) - chi2)) p_value = 1 - st.f.cdf(iman_davenport, k - 1, (k - 1) * (n - 1)) return iman_davenport, p_value, rankings_avg, rankings_cmp
M = [] noOfRows = int(input("enter row value: ")) noOfColumns = int(input("enter column value: ")) for i in range(noOfRows): R = [] for j in range(noOfColumns): element = int(input(f"enter number {j+1} ")) R.append(element) M.append(R) def displayMatrix(): for i in range(noOfRows): for j in range(noOfColumns): print("%10.3f" % M[i][j],end ="\t") print() displayMatrix() pivotRow = int(input("Enter pivot row number: ")) pivotColumn = int(input("Enter pivot column number: ")) pivotRow -= 1 pivotColumn -=1 while (pivotRow >= 0 and pivotColumn >= 0): pivotElement = M[pivotRow][pivotColumn] for c in range(noOfColumns): M[pivotRow][c] = M[pivotRow][c]/pivotElement #displayMatrix() for r in range(noOfRows): if (r == pivotRow): continue if (r != pivotRow): pivotValue = M[r][pivotColumn] for c in range (noOfColumns): M[r][c] = M[r][c] -M[pivotRow][c] * pivotValue displayMatrix() pivotRow = int(input("Enter pivot row number: ")) pivotColumn = int(input("Enter pivot column number: ")) pivotRow -= 1 pivotColumn -= 1
""" Problem 0.8.3: tuple_sum(A,B) input: list A and B of the same length, where each element in each list is a pair(x,y) of numbers output: list of pairs(x,y) in which the first element of the ith pair is the sum of the first element of the ith pair in A and the first element of the ith pair in B example: given lists [(1,2), (10,20)] and [(3,4), (30, 40)], return [(4,6), (40, 60)] """ def tuple_sum(A, B): result_list = [] for i in range(len(A)): result_list.append((A[i][0] + B[i][0], A[i][1] + B[i][1])) return result_list # one line code should be # return [ (t[0][0] + t[1][0], t[0][1] + t[1][1]) for t in zip(A, B) ] # test the code test_tuple_one = [(1, 2), (3, 4), (5, 6), (7, 8)] test_tuple_two = [(11, 12), (13, 14), (15, 16), (17, 18)] print(tuple_sum(test_tuple_one, test_tuple_two))
output = 0 with open('..//input.txt', 'r') as input: for line in input.readlines(): # print(line) output += int(line) print(output)
import sqlite3 """ Setup Parameters """ sqlite_file = '../../data/database/deeplearning.sqlite' table_name = 'tweets' column_names = ['Id', 'Time', 'Author', 'Text', 'Hashtags', 'Mentions', 'Replies', 'Favourites', 'Retweets'] column_types = ['INTEGER', 'TEXT', 'TEXT', 'TEXT', 'TEXT', 'TEXT', 'INTEGER', 'INTEGER', 'INTEGER'] """ Establish connection to db """ cnxn = sqlite3.connect(sqlite_file) c = cnxn.cursor() """ Setup our createtable query """ create_query = 'CREATE TABLE {} ('.format(table_name) for nm, tp in zip(column_names, column_types): if nm != column_names[-1]: create_query += '{} {}, '.format(nm, tp) else: create_query += '{} {}'.format(nm, tp) create_query += ')' print('Query to be executed: {}'.format(create_query)) """ Execute query """ c.execute(create_query) cnxn.commit() cnxn.close()
# A Function in Python is used to utilize the code in more than one place in a program. It is also called method or procedures. Python provides you many inbuilt functions like print(), but it also gives freedom to create your own functions. def func1(): print("I am learning python function") # Significance of Indentation (Space) in Python print("Ok boss") func1() def square(x): return x*x print(square(4)) # Arguments in Functions def multiply(x,y): print(x*y) multiply(2,8) def multiply(x,y=0): return x*y print(multiply(5, y=4)) def qodr(*args): print(args) qodr(1,2,3,4,5) def sum(a,b): print(f"{a}+{b}={a+b}") sum(3.0,7.9) # Python return statement def func2(a): if a%2==0: return 0 else: return 1 print(func2(7)) def sum2(a=5,b=9): return a+b print(sum2(2,3)) print(sum2()) # Local Scope def func3(): z=7 print(z) print(func3()) # Global Scope f=7 def func4(): print(f) print(func4()) #del func4() # deleting function # Lifetime # def func1(): # counter=0 # counter+=1 # print(counter) # print(func1()) myvar=lambda a,b:(a*b)+2 print(myvar(3,5)) def facto(n): if n==1: return 1 return n*facto(n-1) print(facto(3))
var1 = "python!" var2 = "Programmer league" print ("var1[0]:",var1[0]) print ("var2[1:5]:",var2[1:5]) print ("y" in var1) print ("p" not in var1) print (f"Hello {var1} {var2}") # string format name = 'python' number = 99 print ('%s %d' %(name, number)) x = "Guru" y = "99" print (x*2) # Python String replace() Method oldstring = 'I like you' newstring = oldstring.replace('like', 'love') print(newstring) # Changing upper and lower case strings string = 'python at mama' print(string.upper()) print(string.capitalize()) print(string.lower()) # Using "join" function for the string print(":".join("Python")) # Reversing String string="12345" print(''.join(reversed(string))) # split strings word="guru99 career guru99" print(word.split(' ')) print(word.split('r'))
# Calendar module in Python has the calendar class that allows the calculations for various task based on date, month, and year. On top of it, the TextCalendar and HTMLCalendar class in Python allows you to edit the calendar and use as per your requirement. import calendar c = calendar.TextCalendar(calendar.SUNDAY) # str = c.formatmonth(2020, 5) # print(str) for i in c.itermonthdays(2020, 5): print(i) for name in calendar.month_name: print(name) for day in calendar.day_name: print(day) for month in range (1,13): mycal = calendar.monthcalendar(2020, month) week1 = mycal[0] week2 = mycal[1] if week1[calendar.MONDAY] != 0: auditday = week1[calendar.MONDAY] else: auditday = week2[calendar.MONDAY] print("%10s %2d" % (calendar.month_name[month], auditday))
def Merge(dict1, dict2): dict2.update(dict1) dict1 = {'a': 10, 'b': 8} dict2 = {'d': 6, 'c': 4} Merge(dict1, dict2) print(dict2)
''' Venn diagram plotting routines. Copyright 2012, Konstantin Tretyakov. http://kt.era.ee/ Licensed under MIT license. This package contains routines for plotting area-weighted two- and three-circle venn diagrams. There are four main functions here: :code:`venn2`, :code:`venn2_circles`, :code:`venn3`, :code:`venn3_circles`. The :code:`venn2` and :code:`venn2_circles` accept as their only required argument a 3-element list of subset sizes: subsets = (Ab, aB, AB) That is, for example, subsets[0] contains the size of the subset (A and not B), and subsets[2] contains the size of the set (A and B), etc. Similarly, the functions :code:`venn3` and :code:`venn3_circles` require a 7-element list: subsets = (Abc, aBc, ABc, abC, AbC, aBC, ABC) The functions :code:`venn2_circles` and :code:`venn3_circles` simply draw two or three circles respectively, such that their intersection areas correspond to the desired set intersection sizes. Note that for a three-circle venn diagram it is not possible to achieve exact correspondence, although in most cases the picture will still provide a decent indication. The functions :code:`venn2` and :code:`venn3` draw diagram as a collection of separate colored patches with text labels. The functions :code:`venn2_circles` and :code:`venn3_circles` return the list of Circle patches that may be tuned further to your liking. The functions :code:`venn2` and :code:`venn3` return an object of class :code:`Venn2` or :code:`Venn3` respectively, which give access to constituent patches and text elements. Example:: from matplotlib import pyplot as plt import numpy as np from matplotlib_venn import venn3, venn3_circles plt.figure(figsize=(4,4)) v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C')) v.get_patch_by_id('100').set_alpha(1.0) v.get_patch_by_id('100').set_color('white') v.get_label_by_id('100').set_text('Unknown') v.get_label_by_id('A').set_text('Set "A"') c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed') c[0].set_lw(1.0) c[0].set_ls('dotted') plt.title("Sample Venn diagram") plt.annotate('Unknown set', xy=v.get_label_by_id('100').get_position() - np.array([0, 0.05]), xytext=(-70,-70), ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color='gray')) ''' #### Begin __math.py ''' Venn diagram plotting routines. Math helper functions. Copyright 2012, Konstantin Tretyakov. http://kt.era.ee/ Licensed under MIT license. ''' import sys,string,os sys.path.insert(1, os.path.join(sys.path[0], '..')) ### import parent dir dependencies from scipy.optimize import brentq import numpy as np tol = 1e-10 def circle_intersection_area(r, R, d): ''' Formula from: http://mathworld.wolfram.com/Circle-CircleIntersection.html Does not make sense for negative r, R or d >>> circle_intersection_area(0.0, 0.0, 0.0) 0.0 >>> circle_intersection_area(1.0, 1.0, 0.0) 3.1415... >>> circle_intersection_area(1.0, 1.0, 1.0) 1.2283... ''' if np.abs(d) < tol: minR = np.min([r, R]) return np.pi * minR**2 if np.abs(r - 0) < tol or np.abs(R - 0) < tol: return 0.0 d2, r2, R2 = float(d**2), float(r**2), float(R**2) arg = (d2 + r2 - R2) / 2 / d / r arg = np.max([np.min([arg, 1.0]), -1.0]) # Even with valid arguments, the above computation may result in things like -1.001 A = r2 * np.arccos(arg) arg = (d2 + R2 - r2) / 2 / d / R arg = np.max([np.min([arg, 1.0]), -1.0]) B = R2 * np.arccos(arg) arg = (-d + r + R) * (d + r - R) * (d - r + R) * (d + r + R) arg = np.max([arg, 0]) C = -0.5 * np.sqrt(arg) return A + B + C def circle_line_intersection(center, r, a, b): ''' Computes two intersection points between the circle centered at <center> and radius <r> and a line given by two points a and b. If no intersection exists, or if a==b, None is returned. If one intersection exists, it is repeated in the answer. >>> circle_line_intersection(np.array([0.0, 0.0]), 1, np.array([-1.0, 0.0]), np.array([1.0, 0.0])) array([[ 1., 0.], [-1., 0.]]) >>> np.round(circle_line_intersection(np.array([1.0, 1.0]), np.sqrt(2), np.array([-1.0, 1.0]), np.array([1.0, -1.0])), 6) array([[ 0., 0.], [ 0., 0.]]) ''' s = b - a # Quadratic eqn coefs A = np.linalg.norm(s)**2 if abs(A) < tol: return None B = 2 * np.dot(a - center, s) C = np.linalg.norm(a - center)**2 - r**2 disc = B**2 - 4 * A * C if disc < 0.0: return None t1 = (-B + np.sqrt(disc)) / 2.0 / A t2 = (-B - np.sqrt(disc)) / 2.0 / A return np.array([a + t1 * s, a + t2 * s]) def find_distance_by_area(r, R, a, numeric_correction=0.0001): ''' Solves circle_intersection_area(r, R, d) == a for d numerically (analytical solution seems to be too ugly to pursue). Assumes that a < pi * min(r, R)**2, will fail otherwise. The numeric correction parameter is used whenever the computed distance is exactly (R - r) (i.e. one circle must be inside another). In this case the result returned is (R-r+correction). This helps later when we position the circles and need to ensure they intersect. >>> find_distance_by_area(1, 1, 0, 0.0) 2.0 >>> round(find_distance_by_area(1, 1, 3.1415, 0.0), 4) 0.0 >>> d = find_distance_by_area(2, 3, 4, 0.0) >>> d 3.37... >>> round(circle_intersection_area(2, 3, d), 10) 4.0 >>> find_distance_by_area(1, 2, np.pi) 1.0001 ''' if r > R: r, R = R, r if np.abs(a) < tol: return float(r + R) if np.abs(min([r, R])**2 * np.pi - a) < tol: return np.abs(R - r + numeric_correction) return brentq(lambda x: circle_intersection_area(r, R, x) - a, R - r, R + r) def circle_circle_intersection(C_a, r_a, C_b, r_b): ''' Finds the coordinates of the intersection points of two circles A and B. Circle center coordinates C_a and C_b, should be given as tuples (or 1x2 arrays). Returns a 2x2 array result with result[0] being the first intersection point (to the right of the vector C_a -> C_b) and result[1] being the second intersection point. If there is a single intersection point, it is repeated in output. If there are no intersection points or an infinite number of those, None is returned. >>> circle_circle_intersection([0, 0], 1, [1, 0], 1) # Two intersection points array([[ 0.5 , -0.866...], [ 0.5 , 0.866...]]) >>> circle_circle_intersection([0, 0], 1, [2, 0], 1) # Single intersection point (circles touch from outside) array([[ 1., 0.], [ 1., 0.]]) >>> circle_circle_intersection([0, 0], 1, [0.5, 0], 0.5) # Single intersection point (circles touch from inside) array([[ 1., 0.], [ 1., 0.]]) >>> circle_circle_intersection([0, 0], 1, [0, 0], 1) is None # Infinite number of intersections (circles coincide) True >>> circle_circle_intersection([0, 0], 1, [0, 0.1], 0.8) is None # No intersections (one circle inside another) True >>> circle_circle_intersection([0, 0], 1, [2.1, 0], 1) is None # No intersections (one circle outside another) True ''' C_a, C_b = np.array(C_a, float), np.array(C_b, float) v_ab = C_b - C_a d_ab = np.linalg.norm(v_ab) if np.abs(d_ab) < tol: # No intersection points return None cos_gamma = (d_ab**2 + r_a**2 - r_b**2) / 2.0 / d_ab / r_a if abs(cos_gamma) > 1.0: return None sin_gamma = np.sqrt(1 - cos_gamma**2) u = v_ab / d_ab v = np.array([-u[1], u[0]]) pt1 = C_a + r_a * cos_gamma * u - r_a * sin_gamma * v pt2 = C_a + r_a * cos_gamma * u + r_a * sin_gamma * v return np.array([pt1, pt2]) def vector_angle_in_degrees(v): ''' Given a vector, returns its elevation angle in degrees (-180..180). >>> vector_angle_in_degrees([1, 0]) 0.0 >>> vector_angle_in_degrees([1, 1]) 45.0 >>> vector_angle_in_degrees([0, 1]) 90.0 >>> vector_angle_in_degrees([-1, 1]) 135.0 >>> vector_angle_in_degrees([-1, 0]) 180.0 >>> vector_angle_in_degrees([-1, -1]) -135.0 >>> vector_angle_in_degrees([0, -1]) -90.0 >>> vector_angle_in_degrees([1, -1]) -45.0 ''' return np.arctan2(v[1], v[0]) * 180 / np.pi def normalize_by_center_of_mass(coords, radii): ''' Given coordinates of circle centers and radii, as two arrays, returns new coordinates array, computed such that the center of mass of the three circles is (0, 0). >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 3.0]]), np.array([1.0, 1.0, 1.0])) array([[-1., -1.], [ 1., -1.], [ 0., 2.]]) >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 2.0]]), np.array([1.0, 1.0, np.sqrt(2.0)])) array([[-1., -1.], [ 1., -1.], [ 0., 1.]]) ''' # Now find the center of mass. radii = radii**2 sum_r = np.sum(radii) if sum_r < tol: return coords else: return coords - np.dot(radii, coords) / np.sum(radii) #### End __math.py #### Begin __venn2.py ''' Venn diagram plotting routines. Two-circle venn plotter. Copyright 2012, Konstantin Tretyakov. http://kt.era.ee/ Licensed under MIT license. ''' import numpy as np from matplotlib.patches import Circle from matplotlib.colors import ColorConverter from matplotlib.pyplot import gca #from _math import * #from _venn3 import make_venn3_region_patch, prepare_venn3_axes, mix_colors def compute_venn2_areas(diagram_areas, normalize_to=1.0): ''' The list of venn areas is given as 3 values, corresponding to venn diagram areas in the following order: (Ab, aB, AB) (i.e. last element corresponds to the size of intersection A&B&C). The return value is a list of areas (A, B, AB), such that the total area is normalized to normalize_to. If total area was 0, returns (1.0, 1.0, 0.0)/2.0 Assumes all input values are nonnegative (to be more precise, all areas are passed through and abs() function) >>> compute_venn2_areas((1, 1, 0)) (0.5, 0.5, 0.0) >>> compute_venn2_areas((0, 0, 0)) (0.5, 0.5, 0.0) >>> compute_venn2_areas((1, 1, 1), normalize_to=3) (2.0, 2.0, 1.0) >>> compute_venn2_areas((1, 2, 3), normalize_to=6) (4.0, 5.0, 3.0) ''' # Normalize input values to sum to 1 areas = np.array(np.abs(diagram_areas), float) total_area = np.sum(areas) if np.abs(total_area) < tol: return (0.5, 0.5, 0.0) else: areas = areas / total_area * normalize_to return (areas[0] + areas[2], areas[1] + areas[2], areas[2]) def solve_venn2_circles(venn_areas): ''' Given the list of "venn areas" (as output from compute_venn2_areas, i.e. [A, B, AB]), finds the positions and radii of the two circles. The return value is a tuple (coords, radii), where coords is a 2x2 array of coordinates and radii is a 2x1 array of circle radii. Assumes the input values to be nonnegative and not all zero. In particular, the first two values must be positive. >>> c, r = solve_venn2_circles((1, 1, 0)) >>> np.round(r, 3) array([ 0.564, 0.564]) >>> c, r = solve_venn2_circles(compute_venn2_areas((1, 2, 3))) >>> np.round(r, 3) array([ 0.461, 0.515]) ''' (A_a, A_b, A_ab) = map(float, venn_areas) r_a, r_b = np.sqrt(A_a / np.pi), np.sqrt(A_b / np.pi) radii = np.array([r_a, r_b]) if A_ab > tol: # Nonzero intersection coords = np.zeros((2, 2)) coords[1][0] = find_distance_by_area(radii[0], radii[1], A_ab) else: # Zero intersection coords = np.zeros((2, 2)) coords[1][0] = radii[0] + radii[1] + np.mean(radii) * 1.1 coords = normalize_by_center_of_mass(coords, radii) return (coords, radii) def compute_venn2_regions(centers, radii): ''' See compute_venn3_regions for explanations. >>> centers, radii = solve_venn2_circles((1, 1, 0.5)) >>> regions = compute_venn2_regions(centers, radii) ''' intersection = circle_circle_intersection(centers[0], radii[0], centers[1], radii[1]) if intersection is None: # Two circular regions regions = [("CIRCLE", (centers[a], radii[a], True), centers[a]) for a in [0, 1]] + [None] else: # Three curved regions regions = [] for (a, b) in [(0, 1), (1, 0)]: # Make region a&not b: [(AB, A-), (BA, B+)] points = np.array([intersection[a], intersection[b]]) arcs = [(centers[a], radii[a], False), (centers[b], radii[b], True)] if centers[a][0] < centers[b][0]: # We are to the left label_pos_x = (centers[a][0] - radii[a] + centers[b][0] - radii[b]) / 2.0 else: # We are to the right label_pos_x = (centers[a][0] + radii[a] + centers[b][0] + radii[b]) / 2.0 label_pos = np.array([label_pos_x, centers[a][1]]) regions.append((points, arcs, label_pos)) # Make region a&b: [(AB, A+), (BA, B+)] (a, b) = (0, 1) points = np.array([intersection[a], intersection[b]]) arcs = [(centers[a], radii[a], True), (centers[b], radii[b], True)] label_pos_x = (centers[a][0] + radii[a] + centers[b][0] - radii[b]) / 2.0 label_pos = np.array([label_pos_x, centers[a][1]]) regions.append((points, arcs, label_pos)) return regions def compute_venn2_colors(set_colors): ''' Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 3 elements, providing colors for regions (10, 01, 11). >>> compute_venn2_colors(('r', 'g')) (array([ 1., 0., 0.]), array([ 0. , 0.5, 0. ]), array([ 0.7 , 0.35, 0. ])) ''' ccv = ColorConverter() base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors] return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1])) def venn2_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, **kwargs): ''' Plots only the two circles for the corresponding Venn diagram. Useful for debugging or enhancing the basic venn diagram. parameters sets and normalize_to are the same as in venn2() kwargs are passed as-is to matplotlib.patches.Circle. returns a list of three Circle patches. >>> c = venn2_circles((1, 2, 3)) >>> c = venn2_circles({'10': 1, '01': 2, '11': 3}) # Same effect ''' complete_subets = subsets subsets_abrev = [] for i in subsets: subsets_abrev.append(len(i)) subsets = tuple(subsets_abrev) if isinstance(subsets, dict): subsets = [subsets.get(t, 0) for t in ['10', '01', '11']] areas = compute_venn2_areas(subsets, normalize_to) centers, radii = solve_venn2_circles(areas) ax = gca() prepare_venn3_axes(ax, centers, radii) result = [] for (c, r) in zip(centers, radii): circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs) ax.add_patch(circle) result.append(circle) return result class Venn2: ''' A container for a set of patches and patch labels and set labels, which make up the rendered venn diagram. ''' id2idx = {'10': 0, '01': 1, '11': 2, 'A': 0, 'B': 1} def __init__(self, patches, subset_labels, set_labels): self.patches = patches self.subset_labels = subset_labels self.set_labels = set_labels def get_patch_by_id(self, id): '''Returns a patch by a "region id". A region id is a string '10', '01' or '11'.''' return self.patches[self.id2idx[id]] def get_label_by_id(self, id): ''' Returns a subset label by a "region id". A region id is a string '10', '01' or '11'. Alternatively, if the string 'A' or 'B' is given, the label of the corresponding set is returned (or None).''' if len(id) == 1: return self.set_labels[self.id2idx[id]] if self.set_labels is not None else None else: return self.subset_labels[self.id2idx[id]] def venn2(subsets, set_labels=('A', 'B'), set_colors=('r', 'g'), alpha=0.4, normalize_to=1.0): '''Plots a 2-set area-weighted Venn diagram. The subsets parameter is either a dict or a list. - If it is a dict, it must map regions to their sizes. The regions are identified via two-letter binary codes ('10', '01', and '11'), hence a valid set could look like: {'01': 10, '01': 20, '11': 40}. Unmentioned codes are considered to map to 0. - If it is a list, it must have 3 elements, denoting the sizes of the regions in the following order: (10, 10, 11) Set labels parameter is a list of two strings - set labels. Set it to None to disable set labels. The set_colors parameter should be a list of two elements, specifying the "base colors" of the two circles. The color of circle intersection will be computed based on those. The normalize_to parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together with the overall fiture size) may be useful to fit the text labels better. The return value is a Venn2 object, that keeps references to the Text and Patch objects used on the plot. >>> from matplotlib_venn import * >>> v = venn2(subsets={'10': 1, '01': 1, '11': 1}, set_labels = ('A', 'B')) >>> c = venn2_circles(subsets=(1, 1, 1), linestyle='dashed') >>> v.get_patch_by_id('10').set_alpha(1.0) >>> v.get_patch_by_id('10').set_color('white') >>> v.get_label_by_id('10').set_text('Unknown') >>> v.get_label_by_id('A').set_text('Set A') ''' complete_subets = subsets subsets_abrev = [] for i in subsets: subsets_abrev.append(len(i)) subsets = subsets_abrev if isinstance(subsets, dict): subsets = [subsets.get(t, 0) for t in ['10', '01', '11']] areas = compute_venn2_areas(subsets, normalize_to) centers, radii = solve_venn2_circles(areas) if (areas[0] < tol or areas[1] < tol): raise Exception("Both circles in the diagram must have positive areas.") centers, radii = solve_venn2_circles(areas) regions = compute_venn2_regions(centers, radii) colors = compute_venn2_colors(set_colors) ax = gca() prepare_venn3_axes(ax, centers, radii) # Create and add patches and text patches = [make_venn3_region_patch(r) for r in regions] for (p, c) in zip(patches, colors): if p is not None: p.set_facecolor(c) p.set_edgecolor('none') p.set_alpha(alpha) ax.add_patch(p) texts = [ax.text(r[2][0], r[2][1], str(s), va='center', ha='center', size = 17) if r is not None else None for (r, s) in zip(regions, subsets)] # Position labels if set_labels is not None: padding = np.mean([r * 0.1 for r in radii]) label_positions = [centers[0] + np.array([0.0, - radii[0] - padding]), centers[1] + np.array([0.0, - radii[1] - padding])] labels = [ax.text(pos[0], pos[1], txt, size=20, ha='right', va='top') for (pos, txt) in zip(label_positions, set_labels)] labels[1].set_ha('left') else: labels = None return Venn2(patches, texts, labels) #### End __venn2.py #### Begin __venn3.py ''' Venn diagram plotting routines. Three-circle venn plotter. Copyright 2012, Konstantin Tretyakov. http://kt.era.ee/ Licensed under MIT license. ''' import numpy as np import warnings from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path from matplotlib.colors import ColorConverter from matplotlib.pyplot import gca #from _math import * def compute_venn3_areas(diagram_areas, normalize_to=1.0): ''' The list of venn areas is given as 7 values, corresponding to venn diagram areas in the following order: (Abc, aBc, ABc, abC, AbC, aBC, ABC) (i.e. last element corresponds to the size of intersection A&B&C). The return value is a list of areas (A_a, A_b, A_c, A_ab, A_bc, A_ac, A_abc), such that the total area of all circles is normalized to normalize_to. If total area was 0, returns (1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0)/3.0 Assumes all input values are nonnegative (to be more precise, all areas are passed through and abs() function) >>> compute_venn3_areas((1, 1, 0, 1, 0, 0, 0)) (0.33..., 0.33..., 0.33..., 0.0, 0.0, 0.0, 0.0) >>> compute_venn3_areas((0, 0, 0, 0, 0, 0, 0)) (0.33..., 0.33..., 0.33..., 0.0, 0.0, 0.0, 0.0) >>> compute_venn3_areas((1, 1, 1, 1, 1, 1, 1), normalize_to=7) (4.0, 4.0, 4.0, 2.0, 2.0, 2.0, 1.0) >>> compute_venn3_areas((1, 2, 3, 4, 5, 6, 7), normalize_to=56/2) (16.0, 18.0, 22.0, 10.0, 13.0, 12.0, 7.0) ''' # Normalize input values to sum to 1 areas = np.array(np.abs(diagram_areas), float) total_area = np.sum(areas) if np.abs(total_area) < tol: return (1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0, 0.0, 0.0, 0.0) else: areas = areas / total_area * normalize_to A_a = areas[0] + areas[2] + areas[4] + areas[6] A_b = areas[1] + areas[2] + areas[5] + areas[6] A_c = areas[3] + areas[4] + areas[5] + areas[6] # Areas of the three intersections (ab, ac, bc) A_ab, A_ac, A_bc = areas[2] + areas[6], areas[4] + areas[6], areas[5] + areas[6] return (A_a, A_b, A_c, A_ab, A_bc, A_ac, areas[6]) def solve_venn3_circles(venn_areas): ''' Given the list of "venn areas" (as output from compute_venn3_areas, i.e. [A, B, C, AB, BC, AC, ABC]), finds the positions and radii of the three circles. The return value is a tuple (coords, radii), where coords is a 3x2 array of coordinates and radii is a 3x1 array of circle radii. Assumes the input values to be nonnegative and not all zero. In particular, the first three values must all be positive. The overall match is only approximate (to be precise, what is matched are the areas of the circles and the three pairwise intersections). >>> c, r = solve_venn3_circles((1, 1, 1, 0, 0, 0, 0)) >>> np.round(r, 3) array([ 0.564, 0.564, 0.564]) >>> c, r = solve_venn3_circles(compute_venn3_areas((1, 2, 40, 30, 4, 40, 4))) >>> np.round(r, 3) array([ 0.359, 0.476, 0.453]) ''' (A_a, A_b, A_c, A_ab, A_bc, A_ac, A_abc) = map(float, venn_areas) r_a, r_b, r_c = np.sqrt(A_a / np.pi), np.sqrt(A_b / np.pi), np.sqrt(A_c / np.pi) intersection_areas = [A_ab, A_bc, A_ac] radii = np.array([r_a, r_b, r_c]) # Hypothetical distances between circle centers that assure # that their pairwise intersection areas match the requirements. dists = [find_distance_by_area(radii[i], radii[j], intersection_areas[i]) for (i, j) in [(0, 1), (1, 2), (2, 0)]] # How many intersections have nonzero area? num_nonzero = sum(np.array([A_ab, A_bc, A_ac]) > tol) # Handle four separate cases: # 1. All pairwise areas nonzero # 2. Two pairwise areas nonzero # 3. One pairwise area nonzero # 4. All pairwise areas zero. if num_nonzero == 3: # The "generic" case, simply use dists to position circles at the vertices of a triangle. # Before we need to ensure that resulting circles can be at all positioned on a triangle, # use an ad-hoc fix. for i in range(3): i, j, k = (i, (i + 1) % 3, (i + 2) % 3) if dists[i] > dists[j] + dists[k]: dists[i] = 0.8 * (dists[j] + dists[k]) warnings.warn("Bad circle positioning") coords = position_venn3_circles_generic(radii, dists) elif num_nonzero == 2: # One pair of circles is not intersecting. # In this case we can position all three circles in a line # The two circles that have no intersection will be on either sides. for i in range(3): if intersection_areas[i] < tol: (left, right, middle) = (i, (i + 1) % 3, (i + 2) % 3) coords = np.zeros((3, 2)) coords[middle][0] = dists[middle] coords[right][0] = dists[middle] + dists[right] # We want to avoid the situation where left & right still intersect if coords[left][0] + radii[left] > coords[right][0] - radii[right]: mid = (coords[left][0] + radii[left] + coords[right][0] - radii[right]) / 2.0 coords[left][0] = mid - radii[left] - 1e-5 coords[right][0] = mid + radii[right] + 1e-5 break elif num_nonzero == 1: # Only one pair of circles is intersecting, and one circle is independent. # Position all on a line first two intersecting, then the free one. for i in range(3): if intersection_areas[i] > tol: (left, right, side) = (i, (i + 1) % 3, (i + 2) % 3) coords = np.zeros((3, 2)) coords[right][0] = dists[left] coords[side][0] = dists[left] + radii[right] + radii[side] * 1.1 # Pad by 10% break else: # All circles are non-touching. Put them all in a sequence coords = np.zeros((3, 2)) coords[1][0] = radii[0] + radii[1] * 1.1 coords[2][0] = radii[0] + radii[1] * 1.1 + radii[1] + radii[2] * 1.1 coords = normalize_by_center_of_mass(coords, radii) return (coords, radii) def position_venn3_circles_generic(radii, dists): ''' Given radii = (r_a, r_b, r_c) and distances between the circles = (d_ab, d_bc, d_ac), finds the coordinates of the centers for the three circles so that they form a proper triangle. The current positioning method puts the center of A and B on a horizontal line y==0, and C just below. Returns a 3x2 array with circle center coordinates in rows. >>> position_venn3_circles_generic((1, 1, 1), (0, 0, 0)) array([[ 0., 0.], [ 0., 0.], [ 0., -0.]]) >>> position_venn3_circles_generic((1, 1, 1), (2, 2, 2)) array([[ 0. , 0. ], [ 2. , 0. ], [ 1. , -1.73205081]]) ''' (d_ab, d_bc, d_ac) = dists (r_a, r_b, r_c) = radii coords = np.array([[0, 0], [d_ab, 0], [0, 0]], float) C_x = (d_ac**2 - d_bc**2 + d_ab**2) / 2.0 / d_ab if np.abs(d_ab) > tol else 0.0 C_y = -np.sqrt(d_ac**2 - C_x**2) coords[2, :] = C_x, C_y return coords def compute_venn3_regions(centers, radii): ''' Given the 3x2 matrix with circle center coordinates, and a 3-element list (or array) with circle radii [as returned from solve_venn3_circles], returns the 7 regions, comprising the venn diagram. Each region is given as [array([pt_1, pt_2, pt_3]), (arc_1, arc_2, arc_3), label_pos] where each pt_i gives the coordinates of a point, and each arc_i is in turn a triple (circle_center, circle_radius, direction), and label_pos is the recommended center point for positioning region label. The region is the poly-curve constructed by moving from pt_1 to pt_2 along arc_1, then to pt_3 along arc_2 and back to pt_1 along arc_3. Arc direction==True denotes positive (CCW) direction. There is also a special case, where the region is given as ["CIRCLE", (center, radius, True), label_pos], which corresponds to a completely circular region. Regions are returned in order (Abc, aBc, ABc, abC, AbC, aBC, ABC) >>> centers, radii = solve_venn3_circles((1, 1, 1, 1, 1, 1, 1)) >>> regions = compute_venn3_regions(centers, radii) ''' # First compute all pairwise circle intersections intersections = [circle_circle_intersection(centers[i], radii[i], centers[j], radii[j]) for (i, j) in [(0, 1), (1, 2), (2, 0)]] regions = [] # Regions [Abc, aBc, abC] for i in range(3): (a, b, c) = (i, (i + 1) % 3, (i + 2) % 3) if intersections[a] is not None and intersections[c] is not None: # Current circle intersects both of the other circles. if intersections[b] is not None: # .. and the two other circles intersect, this is either the "normal" situation # or it can also be a case of bad placement if np.linalg.norm(intersections[b][0] - centers[a]) < radii[a]: # In the "normal" situation we use the scheme [(BA, B+), (BC, C+), (AC, A-)] points = np.array([intersections[a][1], intersections[b][0], intersections[c][1]]) arcs = [(centers[b], radii[b], True), (centers[c], radii[c], True), (centers[a], radii[a], False)] # Ad-hoc label positioning pt_a = intersections[b][0] pt_b = intersections[b][1] pt_c = circle_line_intersection(centers[a], radii[a], pt_a, pt_b) if pt_c is None: label_pos = circle_circle_intersection(centers[b], radii[b] + 0.1 * radii[a], centers[c], radii[c] + 0.1 * radii[c])[0] else: label_pos = 0.5 * (pt_c[1] + pt_a) else: # This is the "bad" situation (basically one disc covers two touching disks) # We use the scheme [(BA, B+), (AB, A-)] if (AC is inside B) and # [(CA, C+), (AC, A-)] otherwise if np.linalg.norm(intersections[c][0] - centers[b]) < radii[b]: points = np.array([intersections[a][1], intersections[a][0]]) arcs = [(centers[b], radii[b], True), (centers[a], radii[a], False)] else: points = np.array([intersections[c][0], intersections[c][1]]) arcs = [(centers[c], radii[c], True), (centers[a], radii[a], False)] label_pos = centers[a] else: # .. and the two other circles do not intersect. This means we are in the "middle" of a OoO placement. # The patch is then a [(AB, B-), (BA, A+), (AC, C-), (CA, A+)] points = np.array([intersections[a][0], intersections[a][1], intersections[c][1], intersections[c][0]]) arcs = [(centers[b], radii[b], False), (centers[a], radii[a], True), (centers[c], radii[c], False), (centers[a], radii[a], True)] # Label will be between the b and c circles leftc, rightc = (b, c) if centers[b][0] < centers[c][0] else (c, b) label_x = ((centers[leftc][0] + radii[leftc]) + (centers[rightc][0] - radii[rightc])) / 2.0 label_y = centers[a][1] + radii[a] / 2.0 label_pos = np.array([label_x, label_y]) elif intersections[a] is None and intersections[c] is None: # Current circle is completely separate from others points = "CIRCLE" arcs = (centers[a], radii[a], True) label_pos = centers[a] else: # Current circle intersects one of the other circles other_circle = b if intersections[a] is not None else c other_circle_intersection = a if intersections[a] is not None else c i1, i2 = (0, 1) if intersections[a] is not None else (1, 0) # The patch is a [(AX, A-), (XA, X+)] points = np.array([intersections[other_circle_intersection][i1], intersections[other_circle_intersection][i2]]) arcs = [(centers[a], radii[a], False), (centers[other_circle], radii[other_circle], True)] if centers[a][0] < centers[other_circle][0]: # We are to the left label_pos_x = (centers[a][0] - radii[a] + centers[other_circle][0] - radii[other_circle]) / 2.0 else: # We are to the right label_pos_x = (centers[a][0] + radii[a] + centers[other_circle][0] + radii[other_circle]) / 2.0 label_pos = np.array([label_pos_x, centers[a][1]]) regions.append((points, arcs, label_pos)) (a, b, c) = (0, 1, 2) # Regions [aBC, AbC, ABc] for i in range(3): (a, b, c) = (i, (i + 1) % 3, (i + 2) % 3) if intersections[b] is None: # No region there regions.append(None) continue has_middle_region = np.linalg.norm(intersections[b][0] - centers[a]) < radii[a] if has_middle_region: # This is the "normal" situation (i.e. all three circles have a common area) # We then use the scheme [(CB, C+), (CA, A-), (AB, B+)] points = np.array([intersections[b][1], intersections[c][0], intersections[a][0]]) arcs = [(centers[c], radii[c], True), (centers[a], radii[a], False), (centers[b], radii[b], True)] # Ad-hoc label positioning pt_a = intersections[b][1] dir_to_a = pt_a - centers[a] dir_to_a = dir_to_a / np.linalg.norm(dir_to_a) pt_b = centers[a] + dir_to_a * radii[a] label_pos = 0.5 * (pt_a + pt_b) else: # This is the situation, where there is no common area # Then the corresponding area is made by scheme [(CB, C+), (BC, B+), None] points = np.array([intersections[b][1], intersections[b][0]]) arcs = [(centers[c], radii[c], True), (centers[b], radii[b], True)] label_pos = 0.5 * (intersections[b][1] + intersections[b][0]) regions.append((points, arcs, label_pos)) # Central region made by scheme [(BC, B+), (AB, A+), (CA, C+)] (a, b, c) = (0, 1, 2) if intersections[a] is None or intersections[b] is None or intersections[c] is None: # No middle region regions.append(None) else: points = np.array([intersections[b][0], intersections[a][0], intersections[c][0]]) label_pos = np.mean(points, 0) # Middle of the central region arcs = [(centers[b], radii[b], True), (centers[a], radii[a], True), (centers[c], radii[c], True)] has_middle_region = np.linalg.norm(intersections[b][0] - centers[a]) < radii[a] if has_middle_region: regions.append((points, arcs, label_pos)) else: regions.append(([], [], label_pos)) # (Abc, aBc, ABc, abC, AbC, aBC, ABC) return (regions[0], regions[1], regions[5], regions[2], regions[4], regions[3], regions[6]) def make_venn3_region_patch(region): ''' Given a venn3 region (as returned from compute_venn3_regions) produces a Patch object, depicting the region as a curve. >>> centers, radii = solve_venn3_circles((1, 1, 1, 1, 1, 1, 1)) >>> regions = compute_venn3_regions(centers, radii) >>> patches = [make_venn3_region_patch(r) for r in regions] ''' if region is None or len(region[0]) == 0: return None if region[0] == "CIRCLE": return Circle(region[1][0], region[1][1]) pts, arcs, label_pos = region path = [pts[0]] for i in range(len(pts)): j = (i + 1) % len(pts) (center, radius, direction) = arcs[i] fromangle = vector_angle_in_degrees(pts[i] - center) toangle = vector_angle_in_degrees(pts[j] - center) if direction: vertices = Path.arc(fromangle, toangle).vertices else: vertices = Path.arc(toangle, fromangle).vertices vertices = vertices[np.arange(len(vertices) - 1, -1, -1)] vertices = vertices * radius + center path = path + list(vertices[1:]) codes = [1] + [4] * (len(path) - 1) return PathPatch(Path(path, codes)) def mix_colors(col1, col2, col3=None): ''' Mixes two colors to compute a "mixed" color (for purposes of computing colors of the intersection regions based on the colors of the sets. Note that we do not simply compute averages of given colors as those seem too dark for some default configurations. Thus, we lighten the combination up a bit. Inputs are (up to) three RGB triples of floats 0.0-1.0 given as numpy arrays. >>> mix_colors(np.array([1.0, 0., 0.]), np.array([1.0, 0., 0.])) # doctest: +NORMALIZE_WHITESPACE array([ 1., 0., 0.]) >>> mix_colors(np.array([1.0, 1., 0.]), np.array([1.0, 0.9, 0.]), np.array([1.0, 0.8, 0.1])) # doctest: +NORMALIZE_WHITESPACE array([ 1. , 1. , 0.04]) ''' if col3 is None: mix_color = 0.7 * (col1 + col2) else: mix_color = 0.4 * (col1 + col2 + col3) mix_color = np.min([mix_color, [1.0, 1.0, 1.0]], 0) return mix_color def compute_venn3_colors(set_colors): ''' Given three base colors, computes combinations of colors corresponding to all regions of the venn diagram. returns a list of 7 elements, providing colors for regions (100, 010, 110, 001, 101, 011, 111). >>> compute_venn3_colors(['r', 'g', 'b']) (array([ 1., 0., 0.]),..., array([ 0.4, 0.2, 0.4])) ''' ccv = ColorConverter() base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors] return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]), base_colors[2], mix_colors(base_colors[0], base_colors[2]), mix_colors(base_colors[1], base_colors[2]), mix_colors(base_colors[0], base_colors[1], base_colors[2])) def prepare_venn3_axes(ax, centers, radii): ''' Sets properties of the axis object to suit venn plotting. I.e. hides ticks, makes proper xlim/ylim. ''' ax.set_aspect('equal') ax.set_xticks([]) ax.set_yticks([]) min_x = min([centers[i][0] - radii[i] for i in range(len(radii))]) max_x = max([centers[i][0] + radii[i] for i in range(len(radii))]) min_y = min([centers[i][1] - radii[i] for i in range(len(radii))]) max_y = max([centers[i][1] + radii[i] for i in range(len(radii))]) ax.set_xlim([min_x - 0.1, max_x + 0.1]) ax.set_ylim([min_y - 0.1, max_y + 0.1]) ax.set_axis_off() def venn3_circles(subsets, normalize_to=1.0, alpha=1.0, color='black', linestyle='solid', linewidth=2.0, **kwargs): ''' Plots only the three circles for the corresponding Venn diagram. Useful for debugging or enhancing the basic venn diagram. parameters sets and normalize_to are the same as in venn3() kwargs are passed as-is to matplotlib.patches.Circle. returns a list of three Circle patches. >>> plot = venn3_circles({'001': 10, '100': 20, '010': 21, '110': 13, '011': 14}) ''' complete_subets = subsets subsets_abrev = [] for i in subsets: subsets_abrev.append(len(i)) subsets = tuple(subsets_abrev) # Prepare parameters if isinstance(subsets, dict): subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']] areas = compute_venn3_areas(subsets, normalize_to) centers, radii = solve_venn3_circles(areas) ax = gca() prepare_venn3_axes(ax, centers, radii) result = [] for (c, r) in zip(centers, radii): circle = Circle(c, r, alpha=alpha, edgecolor=color, facecolor='none', linestyle=linestyle, linewidth=linewidth, **kwargs) ax.add_patch(circle) result.append(circle) return result class Venn3: ''' A container for a set of patches and patch labels and set labels, which make up the rendered venn diagram. ''' id2idx = {'100': 0, '010': 1, '110': 2, '001': 3, '101': 4, '011': 5, '111': 6, 'A': 0, 'B': 1, 'C': 2} def __init__(self, patches, subset_labels, set_labels): self.patches = patches self.subset_labels = subset_labels self.set_labels = set_labels def get_patch_by_id(self, id): '''Returns a patch by a "region id". A region id is a string like 001, 011, 010, etc.''' return self.patches[self.id2idx[id]] def get_label_by_id(self, id): ''' Returns a subset label by a "region id". A region id is a string like 001, 011, 010, etc. Alternatively, if you provide either of 'A', 'B' or 'C', you will obtain the label of the corresponding set (or None).''' if len(id) == 1: return self.set_labels[self.id2idx[id]] if self.set_labels is not None else None else: return self.subset_labels[self.id2idx[id]] def venn3(subsets, set_labels=('A', 'B', 'C'), set_colors=('r', 'g', 'b'), alpha=0.4, normalize_to=1.0): global coordinates coordinates={} '''Plots a 3-set area-weighted Venn diagram. The subsets parameter is either a dict or a list. - If it is a dict, it must map regions to their sizes. The regions are identified via three-letter binary codes ('100', '010', etc), hence a valid set could look like: {'001': 10, '010': 20, '110':30, ...}. Unmentioned codes are considered to map to 0. - If it is a list, it must have 7 elements, denoting the sizes of the regions in the following order: (100, 010, 110, 001, 101, 011, 111). Set labels parameter is a list of three strings - set labels. Set it to None to disable set labels. The set_colors parameter should be a list of three elements, specifying the "base colors" of the three circles. The colors of circle intersections will be computed based on those. The normalize_to parameter specifies the total (on-axes) area of the circles to be drawn. Sometimes tuning it (together with the overall fiture size) may be useful to fit the text labels better. The return value is a Venn3 object, that keeps references to the Text and Patch objects used on the plot. >>> from matplotlib_venn import * >>> v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C')) >>> c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed') >>> v.get_patch_by_id('100').set_alpha(1.0) >>> v.get_patch_by_id('100').set_color('white') >>> v.get_label_by_id('100').set_text('Unknown') >>> v.get_label_by_id('C').set_text('Set C') ''' # Prepare parameters complete_subets = subsets subsets_abrev = [] for i in subsets: subsets_abrev.append(len(i)) subsets = tuple(subsets_abrev) if isinstance(subsets, dict): subsets = [subsets.get(t, 0) for t in ['100', '010', '110', '001', '101', '011', '111']] areas = compute_venn3_areas(subsets, normalize_to) if (areas[0] < tol or areas[1] < tol or areas[2] < tol): raise Exception("All three circles in the diagram must have positive areas. Use venn2 or just a circle to draw diagrams with two or one circle.") centers, radii = solve_venn3_circles(areas) regions = compute_venn3_regions(centers, radii) colors = compute_venn3_colors(set_colors) ax = gca() prepare_venn3_axes(ax, centers, radii) # Create and add patches and text patches = [make_venn3_region_patch(r) for r in regions] for (p, c) in zip(patches, colors): if p is not None: p.set_facecolor(c) p.set_edgecolor('none') p.set_alpha(alpha) ax.add_patch(p) subset_labels = [ax.text(r[2][0], r[2][1], str(s), va='center', ha='center', size=17) if r is not None else None for (r, s) in zip(regions, subsets)] #null = [coordinates[120, 200]=labels['1000'] if r is not None else None for (r, s) in zip(regions, complete_subets)] # Position labels if set_labels is not None: # There are two situations, when set C is not on the same line with sets A and B, and when the three are on the same line. if abs(centers[2][1] - centers[0][1]) > tol: # Three circles NOT on the same line label_positions = [centers[0] + np.array([-radii[0] / 2, radii[0]]), centers[1] + np.array([radii[1] / 2, radii[1]]), centers[2] + np.array([0.0, -radii[2] * 1.1])] labels = [ax.text(pos[0], pos[1], txt, size=20) for (pos, txt) in zip(label_positions, set_labels)] labels[0].set_horizontalalignment('right') labels[1].set_horizontalalignment('left') labels[2].set_verticalalignment('top') labels[2].set_horizontalalignment('center') else: padding = np.mean([r * 0.1 for r in radii]) # Three circles on the same line label_positions = [centers[0] + np.array([0.0, - radii[0] - padding]), centers[1] + np.array([0.0, - radii[1] - padding]), centers[2] + np.array([0.0, - radii[2] - padding])] labels = [ax.text(pos[0], pos[1], txt, size='large', ha='center', va='top') for (pos, txt) in zip(label_positions, set_labels)] else: labels = None return Venn3(patches, subset_labels, labels) #### End __venn3.py if __name__ == '__main__': from matplotlib import pyplot as plt import numpy as np #from matplotlib_venn import venn3, venn3_circles plt.figure(figsize=(4,4)) v = venn3(subsets=(1, 1, 1, 1, 1, 1, 1), set_labels = ('A', 'B', 'C')) v.get_patch_by_id('100').set_alpha(1.0) v.get_patch_by_id('100').set_color('white') v.get_label_by_id('100').set_text('Unknown') v.get_label_by_id('A').set_text('Set "A"') c = venn3_circles(subsets=(1, 1, 1, 1, 1, 1, 1), linestyle='dashed') c[0].set_lw(1.0) c[0].set_ls('dotted') plt.title("Sample Venn diagram") plt.annotate('Unknown set', xy=v.get_label_by_id('100').get_position() - np.array([0, 0.05]), xytext=(-70,-70), ha='center', textcoords='offset points', bbox=dict(boxstyle='round,pad=0.5', fc='gray', alpha=0.1), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.5',color='gray')) plt.show()
''' Write a script that accepts a directory as an argument as well as a container name. The script should upload the contents of the specified directory to the container (or create it if it doesn't exist). The script should handle errors appropriately. (Check for invalid paths, etc.) ''' import pyrax import os def ask_path(): path = raw_input('Directory: ') if os.path.exists(path): return path else: print 'Invalid directory path.' ask_path() pyrax.set_credential_file(os.path.join(os.path.expanduser('~'), '.rackspace_cloud_credentials')) print '''Please type in the name of an existing container or of a new container to be created''' container_name = raw_input('Container: ') print '''Pleaes type in the path for the directory you would like to upload''' path = ask_path() files = [ os.path.join(path,f) for f in os.listdir(path) if os.path.isfile(os.path.join(path,f))] if container_name in pyrax.cloudfiles.list_containers(): #container exists cont = pyrax.cloudfiles.get_container(container_name) else: #new container cont = pyrax.cloudfiles.create_container(container_name) for file in files: obj = cont.upload_file(file) if pyrax.utils.get_checksum(file) != obj.etag: print '[ERROR]: %s uploaded unsuccesfully' %(file) else: print ' %s uploaded successfully.' %(file)
import string def to_rna(sequence): pairs = list(sequence) rna = [] for pair in pairs: rna.append(convert(pair)) rna_sequence = "".join(rna) if len(rna_sequence) == len(sequence): return rna_sequence return "" def convert(pair): if pair == "C": return "G" elif pair == "G": return "C" elif pair == "A": return "U" elif pair == "T": return "A" else: return ""
from functools import reduce def largest_product(number_string, nums): length = len(number_string) - nums + 1 if length <= 0 or nums < 0: raise ValueError if nums == 0: return 1 products = [] for i in range(length): sub_string = number_string[i:i+nums] int_list = [int(x) for x in sub_string] product = reduce(lambda x, acc: x*acc, int_list) products.append(product) return max(products)
""" If the file is a directory, create a directory with the same name in usr, if it doesn't exist if the file is not a directory, just create a symbolic link pointing to the file. """ # see in Packages/<package_name> import os import sys import glob import errno import textwrap from os.path import join, realpath, abspath, isdir, isfile def force_symlink(file1, file2): try: os.symlink(file1, file2) except OSError as e: if e.errno == errno.EEXIST: os.remove(file2) os.symlink(file1, file2) def usage(): sys.stdout.write( textwrap.dedent( """\ usage : program folder_origin [folder_destin] folder_origin is the original folder with all the files\ and folders to be linked folder_destin is where you want to create symlinks, defaults to 'usr' """ ) ) def do_recursion(origin, dirname): AlternatePrefix = "usr" dirlist = glob.glob(dirname + os.sep + "*") for name in dirlist: newName = name.replace(origin, "") newName = AlternatePrefix + os.sep + newName if os.path.isdir(name): # check if file exists in usr/... if not isdir(newName): # create the directory there print("creating directory: ", newName) os.mkdir(newName) do_recursion(origin, name) else: print(name, " --> ", newName) if not isfile(newName): force_symlink( os.getcwd() + os.sep + name, os.getcwd() + os.sep + newName ) def create_symlinks(origin, destin, display_passage=True): """we go over the files and folders in origin and create a symlink in destin folders if not existing will be explicitly created, others files symlinked""" origin = realpath(origin) destin = abspath(destin) os.chdir(origin) # make sure destin exists if display_passage is False and os.path.isdir(destin) is False: os.makedirs(destin) for root, dirs, files in os.walk(os.curdir): for dirn in dirs: # dir_orig = join(join(origin, root), dirn) dir_dest = join(join(destin, root), dirn) if os.path.exists(dir_dest) is False: if display_passage is True: sys.stdout.write("%s does not exists, creating it.\n" % dir_dest) else: os.makedirs(dir_dest) for filen in files: file_orig = realpath(join(join(origin, root), filen)) file_dest = abspath(join(join(destin, root), filen)) if display_passage is True: msg = "%35s ---> %s\n" % (file_orig, file_dest) sys.stdout.write(msg) else: force_symlink(file_orig, file_dest) if display_passage: msg = """\n\n Will perform the previous listed actions. Do you wish to continue? <ctrl-c> to abort""" input(msg) create_symlinks(origin, destin, display_passage=False) # for now assume Packages/sys.argv[1] exists, and do the recursion here prefixDir = "Packages" # do_recursion(prefixDir + os.sep + sys.argv[1] + os.sep, # prefixDir + os.sep + sys.argv[1]) def main(): if len(sys.argv) < 2: usage() sys.exit(-1) origin = sys.argv[1] destin = "usr" if len(sys.argv) > 2: destin = sys.argv[2] # create_symlinks(sys.argv[1], '.') create_symlinks(origin, destin) if __name__ == "__main__": main() # vim: cc=80
from cs50 import get_int def main(): credit = get_int("Number: ") # check to see if the number is too short to be a credit card if (digits(credit) < 13): print("INVALID") return # check if card is valid by calling check_sum function - card is syntactically valid if this is true if (check_sum(credit)): # find the 2 digit prefix of number that is 15 digits long prefix = credit / 10000000000000 # find the 2 digit prefix if the number is 16 digits long prefix_m = credit / 100000000000000 # find the single digit prefix if the number is 13 digits long prefix_v = credit / 1000000000000 # find the single digit prefix if the number is 16 digits long prefix_vi = credit / 1000000000000000 length = digits(credit) if (length == 15 and (prefix == 34 or prefix == 37)): print("AMEX") return 0 elif (length == 16 and (prefix_m == 51 or prefix_m == 52 or prefix_m == 53 or prefix_m == 54 or prefix_m == 55)): print("MASTERCARD") return 0 elif ((length == 13 or length == 16) and (prefix_v == 4 or prefix_vi == 4)): print("VISA") return 0 else: print("INVALID") else: print("INVALID") def digits(x): counter = 0 while(x > 0): x /= 10 counter += 1 return counter def check_sum(num): # initiate a variable to store the sum of every other digit multiplied by 2 sumTotal = 0 alt_num = num num2 = num for i in range (0, digits(num), 2): alt_num /= 10 other = int(2 * (alt_num % 10)) alt_num /= 10 if (digits(other) < 2): sumTotal += other; # if after multiplying by 2 you get two digits - you need to add them digit by digit else: sumTotal += int(other % 10) sumTotal += int(other / 10) # now you need to add that temporary number to all the other digits in the credit card that you did not look at for i in range (0, digits(num), 2): sumTotal += int(num2 % 10) num2 /= 100 print(sumTotal) if (sumTotal % 10 == 0): return True else: return False if __name__ == "__main__": main()
cake_tuples = [(7, 160), (3, 90), (2, 15)] capacity1 = 20 def max_monetay_value(cake_tuples, bag_capacity): # allocate list which will represent max_monetay value of all capacities up to and including desired one: list_capacities = [0]*(bag_capacity + 1) for current_capacity in range(bag_capacity +1): current_max_value = 0 for weight, value in cake_tuples: if current_capacity>=weight: # print(bag_capacity) # print(weight) max_value = value + list_capacities[current_capacity - weight] current_max_value=max(current_max_value, max_value) list_capacities[current_capacity]=current_max_value print(list_capacities) return list_capacities[bag_capacity] print(max_monetay_value(cake_tuples, capacity1))
class Node: def __init__(self, data): self.value = data self.left = None self.right = None def insert(self, data): if self.value == data: return False elif data < self.value: if self.left: return self.left.insert(data) else: self.left = Node(data) return True elif data > self.value: if self.right: return self.right.insert(data) else: self.right = Node(data) return True def find(self, data): if self.value == data: return True elif data < self.value: if self.left: return self.left.find(data) else: return False elif data > self.value: if self.right: return self.right.find(data) else: return False def preorder(self): if self: print(self.value) if self.left: self.left.preorder() if self.right: self.right.preorder() def inorder(self): if self: if self.left: self.left.inorder() print(self.value) if self.right: self.right.preorder() def postorder(self): if self: if self.left: self.left.postorder() if self.right: self.right.postorder() print(self.value) def find_largest(self): if self.right: # print('1') # print(self.value) # print(self.right.value) return self.right.find_largest() # print("largest value is {}".format(self.value)) return self def find_smallest(self): if self.left: return self.left.find_smallest() return self.value # def find_second_largest(self): # if self. class Tree: def __init__(self): self.root = None def insert(self, data): if self.root == None: self.root = Node(data) return True else: return self.root.insert(data) def find(self, data): if self.root: return self.root.find(data) else: return False def preorder(self): print("PreOrder") self.root.preorder() def inorder(self): print("InOrder") self.root.inorder() def postorder(self): print("PostOrder") self.root.postorder() def find_largest(self): # initiate the find largest if self.root: return self.root.find_largest() # there're no items in tree else: raise Exception("Tree is empty") def find_smallest(self): if self.root: return self.root.find_smallest() else: raise Exception("Tree is empty") def find_second_largest(self): if (self.root is None) or (self.root.right is None and self.root.left is None): raise Exception("Root has less than 2 elements, which makes it impossible to find \ second largest item") # if we have left child of the largest element, then second largest would be there largest_node = self.find_largest() # in case left node is not none if largest_node.left is not None: print("Yes, left child is not none, looking for largest Node") print(largest_node.left.find_largest().value) else: print(largest_node.value) print("it must be in the parent node") if __name__ == "__main__": l = [17, 2, 6, 16, 6, 20, 4, 16, 18, 16, 11] l = [17, 2, 6, 16, 6, 20, 4, 16, 16, 11, 19] tr = Tree() for i in l: tr.insert(i) tr.preorder() tr.postorder() tr.inorder() print(tr.find(20)) print(tr.find(30))
'''A crack team of love scientists from OkEros (a hot new dating site) have devised a way to represent dating profiles as rectangles on a two-dimensional plane. They need help writing an algorithm to find the intersection of two users' love rectangles. They suspect finding that intersection is the key to a matching algorithm so powerful it will cause an immediate acquisition by Google or Facebook or Obama or something. Two rectangles overlapping a little. It must be love. Write a function to find the rectangular intersection of two given love rectangles. As with the example above, love rectangles are always "straight" and never "diagonal." More rigorously: each side is parallel with either the x-axis or the y-axis.''' rect1 = { # coordinates of bottom-left corner 'left_x': 2, 'bottom_y': 1, # width and height 'width': 4, 'height': 3, } rect2 = { # coordinates of bottom-left corner 'left_x': 1, 'bottom_y': 3, # width and height 'width': 3, 'height': 3, } rect3 = { # coordinates of bottom-left corner 'left_x': 5, 'bottom_y': 1, # width and height 'width': 3, 'height': 2, } rect4 = { # coordinates of bottom-left corner 'left_x': 7, 'bottom_y': 1, # width and height 'width': 1, 'height': 5, } def find_overlap_range(point1, length1, point2, length2): highest_start_point = max(point1, point2) # print highest_start_point lowest_end_point = min(point1+length1, point2 + length2) # print lowest_end_point if lowest_end_point <= highest_start_point: return None overlap_length = lowest_end_point - highest_start_point return (highest_start_point, overlap_length) def find_total_overlap(rect1, rect2): left_x, width = find_overlap_range(rect1["left_x"], rect1["width"], rect2["left_x"], rect2["width"]) bottom_y, height = find_overlap_range(rect1["bottom_y"], rect1["height"], rect2["bottom_y"], rect2["height"]) return {"left_x": left_x, "bottom_y": bottom_y, "width": width, "height": height} print find_total_overlap(rect1, rect2) list_of_rect = [rect1, rect2, rect3, rect4] def find_list_overlap(rect_list): result = [] for position, rectangular in enumerate(rect_list): # print position, rectangular while position + 1< len(rect_list): print "Verifying overlap of 2 rectangulars:" print rectangular, position print rect_list[position+1], position+1 result = find_total_overlap(rectangular, rect_list[position+1]) print "overlap resulting", result position +=1 print "--"*6 print "==========" * 6 return result # if position+1<len(rect_list): # pass # print # while position != len(list_of_rect) - 1: # print position, rectangular, rect_list[position +1] # position +=1 # print find_list_overlap(rectangular, rect_list[position + 1]) # rect1, rect2 # rect1, rect3 # rect1, rect4 # rect2, rect3 # rect2, rect4 # rect3, rect4 find_list_overlap(list_of_rect)
""" https://en.wikipedia.org/wiki/Knapsack_problem http://stackoverflow.com/questions/3420937/algorithm-to-find-which-number-in-a-list-sum-up-to-a-certain-number https://www.topcoder.com/community/data-science/data-science-tutorials/dynamic-programming-from-novice-to-advanced/ task list = [1,2,3,10] sum = 12 result = [2,10] """ lst1 = [1, 2, 3, 9] lst2 = [1, 2, 4, 4] lst = [1,2,3,10,2, 6, 3] target = 8 import cProfile def find_sum_from_the_list(sum, lst): result = [] for index, elem in enumerate(lst): for j in lst[index:]: if elem+j==target and ([elem, j] not in result): result.append([elem, j]) break return result print find_sum_from_the_list(target, lst) def sum_1(sum, lst): if len(lst)<2: raise ValueError("List must contain at least 2 values") smallest = lst[0] largest = lst[-1] print smallest, largest for index, elem in enumerate(lst): print "=== Current largest {0}\n === Current smallest {1}".format(largest, smallest) if smallest+largest == sum: return smallest, largest elif smallest+largest > sum: largest = lst[len(lst)-1-index] print "changed largest to: ", largest elif smallest+largest < sum: smallest = lst[index] print "changes smallest to: ", smallest return False def sum_2(num, lst): diff = set() for item in lst: if item in diff: return [item, num-item], diff diff.add(num-item) return False print sum_2(8, lst) def sum_that_returns_nubmers(num, lst): # assuming the list is not sorted if len(lst)<2: return False diff = set() for item in lst: if type(item) not in [int, float]: continue if item in diff: return [item, num - item] diff.add(num - item) return False lst = [1, "a", 2, -5,3] print sum_that_returns_nubmers(-2, lst)
from random import randint def ran(): return randint(1,5) def rand7(): while True: roll1 = ran() roll2 = ran() outcome_number = (roll1 - 1)*5 + (roll2 - 1) + 1 print(outcome_number) if outcome_number == 7 or outcome_number == 1: break if outcome_number > 21: continue return outcome_number % 7 + 1 def rand7_table(): results = [ [1, 2, 3, 4, 5], [6, 7, 1, 2, 3], [4, 5, 6, 7, 1], [2, 3, 4, 5, 6], [7, 0, 0, 0, 0], ] while True: # do our die rolls row = rand5() - 1 column = rand5() - 1 # case: we hit an extraneous outcome # so we need to re-roll if row == 4 and column > 0: continue # our outcome was fine. return it! return results[row][column] if __name__ == "__main__": # for i in range(10): # print(randint(1, 5)) print(rand7())
# coding=utf-8 # Suppose we could access yesterday's stock prices as a list, where: # # The indices are the time in minutes past trade opening time, which was 9:30am local time. # The values are the price in dollars of Apple stock at that time. # So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500. # # Write an efficient function that takes stock_prices_yesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday. stock_prices_yesterday = [10, 7, 5, 8, 11, 9] # # get_max_profit(stock_prices_yesterday) # returns 6 (buying for $5 and selling for $11) # stock_prices_yesterday = [12, 11, 10, 9, 7, 4] def get_max_profit(lst): # at this point I'll assume that all items in the list are integers if len(lst)<2: raise ValueError("You need more than 2 prices to calculate a profit") # we could brute force it, but maybe there's a better solution? # how about "Greedy" approach # we shall walk through the list calculating the profit and # storing the maximum profit "so far" # for that we'll need maxim price and minimum price so far as well max_profit = lst[1] - lst[0] # got the profit min_price = lst[0] for index, current_price in enumerate(lst): if index == 0: continue potential_profit = current_price - min_price max_profit = max(potential_profit, max_profit) min_price = min(current_price, min_price) return max_profit print(stock_prices_yesterday) print(get_max_profit(stock_prices_yesterday)) print(get_max_profit([1, 2])) print(get_max_profit([2, 1]))
__author__ = 'bkapusta' ''' Your queue should have an enqueue and a dequeue function and it should be "first in first out" (FIFO). ''' class queue_with_2_stacks: def __init__(self): # create 2 stacks self.in_stack = [] self.out_stack = [] def enqueue(self, item): # append new items in the "in stack" return self.in_stack.append(item) def dequeue(self): # if length of "out_stack" is ==0 we pop items from # in_stack and append those to "out_stack". # With this approach we figure out the problem # of enqueue new items, and deque already existing # ones if len(self.out_stack)==0: while len(self.in_stack) > 0: self.out_stack.append(self.in_stack.pop()) # in case there's nothing in the queue raise # Index Error if len(self.out_stack) == 0: raise IndexError("Can't dequeue from empty queue!") return self.out_stack.pop() ''' complexity: enqueue - O(1) dequeue - O(m) (counted ustin accounting method. In the accounting method, you simply look at the time cost incurred by each item passing through the system instead of the time cost of each operation.) So let's look at the worst case for a single item, which is the case where it is enqueued and then later dequeued. In this case, the item enters in_stack (costing 1 push), then later moves to out_stack (costing 1 pop and 1 push), then later comes off out_stack to get returned (costing 1 pop). Each of these 4 pushes and pops is O(1)O(1) time. So our total cost per item is O(1). Our m enqueue and dequeue operations put m or fewer items into the system, giving a total runtime of O(m). ''' my_q = queue_with_2_stacks() my_q.enqueue(1) my_q.enqueue(2) my_q.enqueue(3) my_q.enqueue(4) print my_q.in_stack print my_q.dequeue() print my_q.in_stack print my_q.out_stack my_q.enqueue(5) my_q.enqueue("asdf") print my_q.in_stack print my_q.dequeue() print my_q.dequeue() print my_q.dequeue() print my_q.dequeue() print my_q.dequeue()
"""Common types and functions.""" # Classes # ======= class Direction: Fwd = 1 Rvs = 2 class TurnDirection: Cw = 1 Ccw = 2 class Point(object): def __init__(self, x, y): self.X = x self.Y = y def __str__(self): return '(' + str(self.X) + ',' + str(self.Y) + ')' def __repr__(self): return str(self) def __eq__(self, other): return (self.X == other.X) & (self.Y == other.Y) def __ne__(self, other): return not self.__eq__(other) class Waypoint(object): def __init__(self, point, direction, speed, size): self.Position = point self.Direction = direction self.Speed = speed self.Size = size # Waypoint is treated as a square, size denotes half the width self.Traversed = False def __str__(self): return '[' + str(self.Position) + ',' + str(self.Direction) + ',' + str(self.Speed) + ',' + str(self.Size) + ']' def __repr__(self): return str(self)
class DoubleStack(): def __init__(self, size=10): self.arr = list(range(10)) self.top1 = -1 self.top2 = size + 1 self.size = size def push1(self, data): if self.top2 - 1 > self.top1: self.top1 += 1 self.arr[self.top1] = data else: print('Stack1 is full') def push2(self, data): if self.top2 - 1 > self.top1: self.top2 -= 1 self.arr[self.top2] = data else: print('Stack2 Overflow') def __str__(self): stack1 = 'Stack1 :' + str(self.arr[:self.top1 + 1]) stack2 = '\nStack2 :' + str([self.arr[ind] for ind in range(self.size - 1, self.top2 - 1, -1)]) return stack1 + stack2 def pop1(self): if self.top1 < 0: print('Stack1 is Empty') else: temp = self.arr[self.top1] self.top1 -= 1 return temp def pop2(self): if self.top2 >= self.size: print('stack2 is empty') else: temp = self.arr[self.top2] self.top2 += 1 return temp if __name__ =='__main__': stack = DoubleStack() stack.push1(5) stack.push1(4) stack.push1(3) print(stack) stack.push2(14) stack.push2(15) stack.push2(16) print(stack) print('Stack2 pop :',stack.pop2()) print('Stack1 pop :', stack.pop1()) print(stack)
# Implement two stack in one Arry class TwoStack(object): def __init__(self, size = 10): self.arr= list(range(size)) self.top1 = -1 self.top2 = size self.size = size def push1(self,data): if self.top1 < self.top2-1 : #condition for overflow self.top1 +=1 self.arr[self.top1] = data else: print('Stack OverFlow') def push2(self,data): if self.top2 > self.top1 +1: self.top2 -=1 self.arr[self.top2] = data else: print('Stack OverFlow') def pop1(self): if self.top1 >=0: temp = self.arr[self.top1] self.top1 -=1 return temp else: print("Stack 1 is empty") def pop2(self): if self.top2 < self.size: temp = self.arr[self.top2] self.top2 +=1 return temp else: print("Stack2 is empty") def print_stack1(self): print(' Stack 1 : ',end='') if self.top1 >=0: print(' ,'.join([str(x) for x in self.arr[:self.top1+1]])) def print_stack2(self): print(' Stack 2 : ', end='') if self.top2 < self.size: stack2 = self.arr[self.top2:][::-1] #reverse to print print(' ,'.join([str(x) for x in stack2])) if __name__ == '__main__': two_stack = TwoStack(5) two_stack.push1(1) two_stack.push1(2) two_stack.push1(3) two_stack.push2(5) two_stack.push2(4) two_stack.push2(3) #print stack over flow two_stack.push1(4) #print stack over flow two_stack.print_stack1() two_stack.print_stack2() two_stack.pop1() two_stack.pop1() two_stack.pop1() two_stack.pop1() # stack is empty two_stack.pop2() two_stack.pop2() two_stack.pop2() #stack is empty
class Employee: raise_percentage = 1.05 number_of_employee = 0 ''' raise is a class variable shared by all instance of class ''' def __init__(self, name, sal): self.name = name self.sal = sal Employee.number_of_employee +=1 def raise_salary(self): return self.sal * self.raise_percentage def __str__(self): return self.name + ', ' + str(self.sal) + ', raise = ' + str(self.raise_percentage) + ', new sal = ' + str(self.raise_salary()) def __repr__(self): '''if str is not defiend basicy this function get used here try to return object that can be used to recreat object ''' return "Employee('{}', {})".format(self.name, self.sal) def __add__(self, other): ''' :param other object of same class: :return: sum of salary of this and other object ''' return self.sal + other.sal def __len__(self): return len(self.name) # methods started with __ called dunder method they are special emp = Employee('Sudhanshu', 1000) emp2 = Employee('Akash', 20000) print(repr(emp)) print(int.__add__(1, 2)) print(str.__add__('a', 'b')) print('Sum of salaries of emp and emp2: ', emp.__add__(emp2)) print('len("test") is same as : ', 'test'.__len__())
from BinarySearchTree import BinarySearchTree, Node import copy ''' 1. Insertion Logic 2. Search a node 3. creating Mirror image of tree 4 . delete a Node from tree 5. check tree2 is mirror image of tree1 6. path root to each leaf node ''' class CompleteBinaryTree(BinarySearchTree): ''' most of tree traversal logic is same just need to update insertion and updation logic ''' def __init__(self, root = None): super().__init__(root) def insert(self, key): ''' :param key: insert node with value key at first available position in level order traversal :return:None ''' node = Node(key) if self.root is None: self.root = node return queue = [self.get_root()] while queue: this_node = queue.pop(0) if this_node.left is not None: queue.append(this_node.left) else: this_node.left = node break if this_node.right is not None: queue.append(this_node.right) else: this_node.right = node break @staticmethod def search(this_node, key): if this_node is None: return False elif this_node.key == key: return True return CompleteBinaryTree.search(this_node.left, key) or CompleteBinaryTree.search(this_node.right, key) def create_mirror_image(self, this_node): ''' :param this_node: :return: new tree mirror image tree i.e 180 degree rotated from vertical line ''' if this_node: self.create_mirror_image(this_node.left) self.create_mirror_image(this_node.right) # Actual swapping this_node.left, this_node.right = this_node.right, this_node.left return this_node def delete_deepest(self, last_node): queue = [self.root] while queue: this_node = queue.pop(0) if this_node.left is not None: if this_node.left == last_node: this_node.left = None del last_node return else: queue.append(this_node.left) if this_node.right is not None: if this_node.right == last_node: this_node.right = None del last_node return else: queue.append(this_node.right) def delete(self, key): ''' find node with value key and deppest node , swap and delete deepest node ''' if self.root is None: print('Tree is Empty') return queue = [self.root] while queue: this_node = queue.pop(0) if this_node.key == key: key_node = this_node if this_node.left is not None: queue.append(this_node.left) if this_node.right is not None: queue.append(this_node.right) key_node.key = this_node.key # here this node is last node or deepest node self.delete_deepest(this_node) @staticmethod def are_mirrors(root1, root2): ''' :param root1: :param root2: :return return true if these two trees are mirror images of each other: ''' if root1 is None and root2 is None: return True if root1 is None or root2 is None: return False if root1.key != root2.key: return False else: return CompleteBinaryTree.are_mirrors(root1.left, root2.right)\ and CompleteBinaryTree.are_mirrors(root1.right, root2.left) @staticmethod def print_root_to_leaf(root, path=[]): if root is None: return path.append(root.key) if root.left is None and root.right is None: print('->'.join([str(x) for x in path])) else: CompleteBinaryTree.print_root_to_leaf(root.left, copy.copy(path)) CompleteBinaryTree.print_root_to_leaf(root.right, copy.copy(path)) if __name__ == '__main__': complete_binary_tree = CompleteBinaryTree() complete_binary_tree.insert(1) complete_binary_tree.insert(2) complete_binary_tree.insert(3) complete_binary_tree.insert(4) complete_binary_tree.insert(5) complete_binary_tree.insert(6) complete_binary_tree.insert(7) complete_binary_tree.insert(8) print('_____Level Order Traversal____') complete_binary_tree.level_order_traversal([complete_binary_tree.get_root()]) complete_binary_tree.print('INORDER') print('\nMax Depth >> ', end='') print(complete_binary_tree.max_depth(complete_binary_tree.root)) print('Print All leaf Node >>') complete_binary_tree.print_all_leaf_node(complete_binary_tree.root) print('\n\nSearch a Node 5 :', complete_binary_tree.search(complete_binary_tree.get_root(), 5)) print('\n\nSearch a Node 9 :', complete_binary_tree.search(complete_binary_tree.get_root(), 9)) print('____Delete Node __________') complete_binary_tree.delete(8) print('_____Level Order Traversal____') complete_binary_tree.level_order_traversal([complete_binary_tree.get_root()]) print('________Create mirror image_______') complete_binary_tree.create_mirror_image(complete_binary_tree.root) print('_____Level Order Traversal____') complete_binary_tree.level_order_traversal([complete_binary_tree.get_root()]) #bt = CompleteBinaryTree() #bt.insert(1) #bt.insert(2) #bt.insert(3) #bt.insert(4) #bt.insert(5) #bt.insert(6) #bt.insert(7) #bt.insert(8) #print('_____Level Order Traversal tree_2 ____') #bt.level_order_traversal([bt.get_root()]) #print('__Check is tree1 and tree2 are mirror image__ :', end='') #print(CompleteBinaryTree.are_mirrors(complete_binary_tree.root, bt.root)) print('__Print all the path from root to leaf__') CompleteBinaryTree.print_root_to_leaf(complete_binary_tree.get_root(), [])
import unittest from code_to_test import add, subtract, divide class TestBasic(unittest.TestCase): def test_add(self): self.assertEqual(add(5, 4), 9) self.assertEqual(add('sudh','anshu'),'sudhanshu') def test_subtract(self): self.assertEqual(subtract(7,3),4) def test_divide(self): self.assertEqual(divide(10,5),2) if __name__ == '__main__': unittest.main()
class Employee: raise_percentage = 1.05 number_of_employee = 0 ''' raise is a class variable shared by all instance of class ''' def __init__(self, name, last, sal): self.name = name self.last = last self.sal = sal Employee.number_of_employee +=1 @property def email(self): return self.name+'@gmail.com' def raise_salary(self): return self.sal * self.raise_percentage def __str__(self): return self.fullname + ', Email : ' + self.email + ', ' + str(self.sal) + ', raise = ' \ + str(self.raise_percentage) + ', new sal = ' + str(self.raise_salary()) @property def fullname(self): return self.name+' '+ self.last @fullname.setter def fullname(self, name): self.name, self.last = name.split(' ') @fullname.deleter def fullname(self): print('Delete Name !') self.name = '' self.last = '' emp1 = Employee('sudhanshu', 'patel', 44444) print(emp1) emp1.name = 'Shaan' print('changing the name will not change email id' 'but here we achieve that by using property decorater') print(emp1) emp1.fullname = 'Shaan kumar' print(emp1) del emp1.fullname print(emp1)
##Given an array of integers, find the pair of adjacent elements ##that has the largest product and return that product. def adjacentElementsProduct(inputArray): largestProduct = -1000000000 for i in range(0, len(inputArray) - 1): if inputArray[i] * inputArray[i+1] > largestProduct: largestProduct = inputArray[i] * inputArray[i+1] return largestProduct print(adjacentElementsProduct([1,2,3,4,5,6]))
def allLongestStrings(inputArray): longest = 0 lst = [] if len(inputArray) == 1: return(inputArray) else: for word in inputArray: if len(word) > longest: longest = len(word) for word in inputArray: if len(word) == longest: lst.append(word) return(lst) inputArray = ["aba","aa","ad","vcd","aba"] print(allLongestStrings(inputArray))
# import nltk # # # def clean_str(raw): # raw_words = nltk.word_tokenize(raw) # # Clean words # words = [word for word in raw_words if len(word) > 1] # words = [word for word in words if word.isalpha()] # words = [w.lower() for w in words if w.isalnum()] # # Stop words # #stopwords = set(nltk.corpus.stopwords.words('english')) # #words = [word for word in words if word not in stopwords] # # Lemma or Stem; use Lemmatizer for better results # # wnl = nltk.WordNetLemmatizer() # cleaned_words = [wnl.lemmatize(t) for t in words] # return ' '.join(cleaned_words).strip()
import textwrap # textwrap.fill(text, width=70, **kwargs) # Wraps the single paragraph in text, and returns a single string containing the wrapped paragraph. fill() is shorthand for # "\n".join(wrap(text, ...)) def wrap(string, max_width): return textwrap.fill(string,max_width)
# 每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友, # 今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。 # 其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后, # 他随机指定一个数m,让编号为0的小朋友开始报数。 # 每次喊到m-1的那个小朋友要出列唱首歌, # 然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始, # 继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演, # 并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。 # 请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1) #模拟链表节点 class LinkList(): def __init__(self,val): self.val = val self.next = None class Solution: def LastRemaining_Solution(self, n, m): if not n or not m: return -1 i = 0;j = 0 n = list(range(n)) while len(n) != 1: if m-1 == j: i %= len(n) print(n.pop(i)) j=0 i+=1 j+=1 return n[0] s = Solution() res = s.LastRemaining_Solution(10,7) print(res)
from pygame import * MONSTER_SPEED = 2 LEFT_IMAGE = image.load('blocks_sprites/monster0.png') RIGHT_IMAGE = image.load('blocks_sprites/monster1.png') class Monster(sprite.Sprite): def __init__(self, x, y, left_vel=MONSTER_SPEED, up_vel=3, max_length_up=15): sprite.Sprite.__init__(self) self.reached_final_destination = False # флаг для выбора изображения (т.е. в какую сторону летит) self.can_move = True self.image = LEFT_IMAGE self.rect = Rect(x, y, self.image.get_width(), self.image.get_height()) self.startX = x # начальные координаты self.startY = y self.maxLengthUp = max_length_up # максимальное расстояние, которое может пройти в одну сторону, вертикаль self.x_vel = left_vel # скорость передвижения по горизонтали, 0 - стоит на месте def update(self, obstacles): # по принципу героя if self.can_move: if self.reached_final_destination: self.image = LEFT_IMAGE else: self.image = RIGHT_IMAGE self.rect.x += self.x_vel self.collide(obstacles) if abs(self.startY - self.rect.y) > self.maxLengthUp: self.y_vel = -self.y_vel # если прошли максимальное растояние, то идеи в обратную сторону, вертикаль def collide(self, obstacles): for obj in obstacles: if sprite.collide_rect(self, obj) and self != obj: # если с чем-то или кем-то столкнулись self.x_vel = -self.x_vel # то поворачиваем в обратную сторону self.reached_final_destination = 1 - self.reached_final_destination def stop(self, is_on_pause): self.can_move = 1 - is_on_pause
import random import math #portfolio class Portfolio: def __init__(self): #initial three portfolio props self.cash = 0.0 self.stock = {} self.mutualFunds={} self.propToUse = None self.history = "\n\nportfolio's ledger\n \n" #adding cash to the portfolio def deposit(self, cash): amount= cash self.cash +=amount self.history +="Deposited : $"+str(amount)+" \n\n" #draw cash from the portfolio def withdraw(self, cash): #check if there is balance if self.cash<cash : print("you can't withdraw, insufficient balance") else: self.cash -= int(cash) self.history +="Withdrew :$" + str(cash)+" \n\n " ########################################################################## def buyProp(self, quantity, prop): neededAmount=( quantity * prop.price) if self.cash < neededAmount: print("insufficient balance. you can't buy that now") return #if you have money go on with buying #get the prop type propT=prop.getPropName() if(propT=='stock'): self.propToUse=self.stock pass elif(propT=='mutual fund'): self.propToUse = self.mutualFunds else: self.propToUse = None if self.propToUse == None: return if prop in self.propToUse: self.propToUse[prop] += quantity else: self.propToUse[prop] = quantity self.history += "\nBought %d of %s --- %s\n" % (quantity, prop.getPropName(), prop.symbol) #withdraw the money for the transaction self.withdraw(neededAmount) def buyStock(self, quantity, prop): self.buyProp(int(quantity), prop) def buyMutualFund(self, quantity, prop): self.buyProp(quantity, prop) def buyBond(self, quantity, prop): self.buyProp(quantity, prop) #selling def sellProp(self, prop, quantity): # make sure to use objects rather than prop names # get the prop type propT = prop.getPropName() if (propT == 'stock'): self.propToUse = self.stock pass elif (propT == 'mutual fund'): self.propToUse = self.mutualFunds else: self.propToUse = None if self.propToUse==None: return if prop in self.propToUse: if self.propToUse[prop] < quantity: print("insufficient %s from %s" % (prop.symbol, prop.getPropName())) else: self.propToUse[prop] -= quantity if self.propToUse[prop] == 0: del self.propToUse[prop] self.history +="sold %d of %s ---- %s\n" % (quantity, prop.getPropName(), prop.symbol) self.deposit(quantity * prop.getPrice()) else: print("no %s with name %s found " % (prop.getPropName(), prop.symbol)) def sellStock(self, prop, quantity): self.sellProp( prop,int(quantity)) def sellMutualFund(self, prop, quantity): self.sellProp( prop, quantity) def sellBond(self, prop, quantity): self.sellProp(prop,quantity) ################################## def __str__(self): message ="\n\n------------------\n" message += "Total Balance: $" + str(self.cash) + "\n" self.propToUse=self.stock message += "\nStock\n" if not self.propToUse: message += "\t => nothing in this class \n" for prop in self.propToUse: message += "\t => "+ str(prop.symbol)+" "+str(self.propToUse[prop])+" \n" self.propToUse = self.mutualFunds message += "Mutual Funds\n" if not self.propToUse: message += "\t => nothing in this class \n" for prop in self.propToUse: message += "\t => "+ str(prop.symbol)+" \n" #finally display the balance message+="-------------------\n\n" return message def showHistory(self): print(self.history) #property superclass for ... class Property: def __init__(self,price,symbol): self.price=price self.symbol=symbol def getPropName(self): return "" def getPrice(self): return 0.0 #stock:property class Stock(Property): def __init__(self, price, symbol): super().__init__( price, symbol) # override the get class and get price methods def getPropName(self): return "stock" def getPrice(self): return int(random.uniform(.5 * self.price, 1.5 * self.price)) / 100.0 #Mutual fund:property class MutualFund(Property): def __init__(self, symbol): super().__init__( 1.0, symbol) def getPropName(self): return "mutual funds" def getPrice(self): return int(100 * random.uniform(.9 * self.price,1.2 * self.price)) / 100.0 #bond:property #bonus class Bonds(Property): def __init__(self, symbol): super().__init__(1.0, symbol) def getPropName(self): return "bonds" def getPrice(self): return 0.0; #Main function def main(): portfolio = Portfolio() # Creates a new portfolio portfolio.deposit(300.50) # Adds cash to the portfolio s = Stock(20, "HFH") # Create Stock with price 20 and symbol "HFH" portfolio.buyProp(5, s) # Buys 5 shares of stock s mf1 = MutualFund("BRT") # Create MF with symbol "BRT" mf2 = MutualFund("GHT") # Create MF with symbol "GHT" portfolio.buyMutualFund(10.3, mf1) # Buys 10.3 shares of "BRT" portfolio.buyMutualFund(2, mf2) # Buys 2 shares of "GHT" print(portfolio) # Prints portfolio # cash: $140.50 # stock: 5 HFH # mutual funds: 10.33 BRT # 2 GHT portfolio.sellMutualFund(mf1, 3) # Sells 3 shares of BRT portfolio.sellMutualFund(mf2, 3) # Sells 3 shares of BRT portfolio.sellMutualFund(s, 3) # Sells 3 shares of BRT portfolio.sellProp(s, 1) # Sells 1 share of HFH portfolio.withdraw(50) # Removes $50 portfolio.showHistory() # Prints a list of all transactions # ordered by time print(portfolio) # Prints portfolio main()
from math import atan print("arctan aprēķināšana") x = float(input("Lūdzu ievadiet argument x:")) y = atan(x) print("atan(%.2f) = %.2f"%(x,y)) print(" ---") print(" \\") print(" \\") print("arctan=x/sqr(1+x*x)") print(" /") print(" /") print(" ---")
#!/usr/bin/python3 from Rook_class import Rook from Piece_class import Piece from Position_class import Position from Board_class import Board from King_class import King import sys def main(): chessboard = Board() chessboard.board_init() black_turn = False king_checked = False game_over = False # Game loop: while True: if not black_turn: turn = "white" enemy = "black" else: turn = "black" enemy = "white" print(chessboard) if king_checked: print("{0} king is in check.".format(turn.title())) game_over = chessboard.checkmates_king(black_turn) if game_over: print(f"GAME OVER! CHECKMATE! {enemy.upper()} WINS!") break # First, get player movement input. start_posn = move_input(chessboard, "Start") start_column, start_row = chessboard.get_indices(start_posn) # Validate that the correct color piece is moved. if chessboard.space_array[start_column][start_row].black != black_turn: print(f"Invalid move! You must choose a {turn} piece to move!") continue end_posn = move_input(chessboard, "End") if end_posn == 'undo': continue end_column, end_row = chessboard.get_indices(end_posn) # Validate the movement of the piece. if not chessboard.validate_move(start_column, start_row, end_column, end_row): print("Invalid movement!") continue # Find if any kings are placed in check. bK, wK = chessboard.checks_kings(start_column, start_row, end_column, end_row) if not king_checked: if black_turn and bK.in_check: print(f"Invalid move! Friendly {turn} king would be placed in check.") continue if not black_turn and wK.in_check: print(f"Invalid move! Friendly {turn} king would be placed in check.") continue # Prints different text depending on if the king was in check at the start of the turn. else: if black_turn and bK.in_check: print(f"Invalid move! Friendly {turn} king is still in check.") continue if not black_turn and wK.in_check: print(f"Invalid move! Friendly {turn} king is still in check.") continue # Move the piece. chessboard.move(start_column, start_row, end_column, end_row) # If an enemy king is placed in check, note the gamestate, and find if checkmate has occurred. if black_turn and wK.in_check: king_checked = True elif not black_turn and bK.in_check: king_checked = True else: king_checked = False # Finally, switch turns. if black_turn == False: black_turn = True else: black_turn = False def move_input(chessboard, start_end): '''Gets start or end locations from the player. Chessboard is a Board object. start_end is a string equal to "Start" or "End".''' while True: if start_end == "End": print('Type "undo" to return to beginning of turn.') posn = input(f"{start_end} location? Type \"board\" at any time to view the board.\n") posn = posn.lower().strip() if posn == "board": print(chessboard) continue if posn.lower() == 'undo': return posn elif posn in chessboard.space_list: pass else: print("Invalid location!") continue return posn def test(): '''Prints out board lists and calls board functions for testing.''' chessboard = Board() chessboard.test_init() black_turn = False king_checked = False print(chessboard, '\n\n') print("SPACE ARRAY") print(chessboard.space_array, '\n\n') print("SPACE LIST") print(chessboard.space_list, '\n\n') print("SPACE DICT") print(chessboard.space_dict, "\n\n") print("LOCATION ARRAY") print(chessboard.location_array) chessboard.space_points_ref() # Game loop: while True: if not black_turn: turn = "white" enemy = "black" else: turn = "black" enemy = "white" print(chessboard) game_over = False if king_checked: print("{0} king is in check.".format(turn.title())) game_over = chessboard.checkmates_king(black_turn) if game_over: print(f"GAME OVER! CHECKMATE! {enemy.upper()} WINS!") break # First, get player movement input. start_posn = move_input(chessboard, "Start") start_column, start_row = chessboard.get_indices(start_posn) # Validate that the correct color piece is moved. if chessboard.space_array[start_column][start_row].black != black_turn: print(f"Invalid move! You must choose a {turn} piece to move!") continue end_posn = move_input(chessboard, "End") end_column, end_row = chessboard.get_indices(end_posn) # Validate the movement of the piece. if not chessboard.validate_move(start_column, start_row, end_column, end_row): print("Invalid movement!") continue # Find if any kings are placed in check. bK, wK = chessboard.checks_kings(start_column, start_row, end_column, end_row) if not king_checked: if black_turn and bK.in_check: print(f"Invalid move! Friendly {turn} king would be placed in check.") continue if not black_turn and wK.in_check: print(f"Invalid move! Friendly {turn} king would be placed in check.") continue else: if black_turn and bK.in_check: print(f"Invalid move! Friendly {turn} king is still in check.") continue if not black_turn and wK.in_check: print(f"Invalid move! Friendly {turn} king is still in check.") continue # Move the piece. chessboard.move(start_column, start_row, end_column, end_row) # If an enemy king is placed in check, note the gamestate, and find if checkmate has occurred. if black_turn and wK.in_check: king_checked = True elif not black_turn and bK.in_check: king_checked = True else: king_checked = False # Finally, switch turns. if black_turn == False: black_turn = True else: black_turn = False #test() main() ''' BUGS: Making chessboard = Board() and then running boardinit(), then running main() seems to not work? May be a problem for game restart. ''' ''' POSSIBLE FEATURES: movement hints to get out of check temporarily move pieces as thought experiments, then undo that movement colored pieces ''' ''' TODO: convert chessboard.visual_board() to print(chessboard) add colors to visual board can possibly get rid of the valid_end_check variable in a lot of places '''
class Position: def __init__(self, x, y): '''Defines a coordinate on the chessboard, where the x axis changes with columns, and the y axis changes with rows.''' self.column = x self.row = y def __str__(self): '''Allows the print command to be used to print out a Position in the format "(x, y)".''' return "({0}, {1})".format(self.column, self.row) def __eq__(self, pt2): '''Overloads the equality operator so that two Position objects are equal if they have the same x and y coordinates. Otherwise, they would be considered two different objects.''' return (self.column == pt2.column) and (self.row == pt2.row) '''Sample tests demonstrating deep equality between position objects:''' ''' pt1 = Position(1, 1) pt2 = Position(1, 1) print(pt1 == pt2) # Returns True '''
c=input() if(ord(c)<65): print("Invalid") elif(c=='a' or c=='e' or c=='i' or c=='o' or 'u'): print("Vowel") else: print("Consonant")
from tkinter import * # math function def add(a, b): return a+b def sub(a, b): return a - b def mul(a, b): return a * b def div(a, b): return a / b def mod(a, b): return a % b def lcm(a, b): L = a if a > b else b while L <= a*b: if L % a == 0 and L % b == 0: return L L += 1 def hcf(a, b): H = a if a < b else b while H >= 1: if a % H == 0 and b % H == 0: return H H -= 1 def extractfromtext(text): l = [] for t in text.split(' '): try: l.append(float(t)) except ValueError: pass return l def calculate(): text = textin.get() for word in text.split(' '): if word.upper() in operations.keys(): try: l = extractfromtext(text) r = operations[word.upper()](l[0], l[1]) list.delete(0, END) list.insert(END, r) except: list.delete(0, END) list.insert(END, 'something went wrong please enter again') finally: break elif word.upper() not in operations.keys(): list.delete(0, END) list.insert(END, 'something went wrong please enter again') operations = {'ADD': add, 'ADDITION': add, 'SUM': add, 'PLUS': add, '+': add, 'SUB': sub, 'SUBTRACT': sub, 'MINUS': sub, 'DIFFERENCE': sub, '-': sub, 'HCF': hcf, 'LCM': lcm, 'PRODUCT': mul, '*': mul, "MULTIPLY": mul, 'MULTIPLICATION': mul, 'DIV': div, '/': div, 'DIVISION': div, 'MOD': mod, '%': mod, 'REMAINDER': mod, 'MODULUS': mod} win = Tk() win.geometry('500x300') win.title('Smart Calculator') win.configure(bg='lightgreen') l1 = Label(win, text='Smart Calculator', width=20, padx=3) l1.place(x=150, y=10) l2 = Label(win, text='creator AnimeshRy', width=20, padx=3) l2.place(x=150, y=40) l3 = Label(win, text="What's the equation ? ", width=20, padx=3) l3.place(x=150, y=130) textin = StringVar() el = Entry(win, width=30, textvariable=textin) el.place(x=140, y=160) b1 = Button(win, text='Shall I start?', command=calculate) b1.place(x=210, y=200) list = Listbox(win, width=30, height=3) list.place(x=140, y=230) win.mainloop()
import os import sys from tkinter import * from tkinter import filedialog print("\nPython version: ", sys.version, "\n") def main(): location_of_folders = input('Where do you want the folders: ') name_of_folders = input("What should the prefix for the folders be: ") number_of_folders = int(input("How many folders do you want: ")) if number_of_folders <= 0: print('You have to create at least 1 folder.') terminate() else: create_folders(location_of_folders, name_of_folders, number_of_folders) terminate() def create_folders(location_of_folders, name_of_folders, number_of_folders): for x in range(1, number_of_folders + 1): #concatenates names and numbers of folders name_of_folder = name_of_folders + " " + str(x) #define name of directory to be created path = os.path.join(location_of_folders, name_of_folder) try: os.mkdir(path) except OSError: print("Creation of the directory", name_of_folders, x, "failed") else: print("Successfully created the directory", name_of_folders, x) def terminate(): print(f"Do you want to try again? Y = yes, N = no:") run_again = input("") run_again = str.lower(run_again) if run_again == "yes": main() elif run_again == "no": exit() else: print("Please type either yes or no") terminate() main()
def only_ints(int1, int2): if type(int1) == int: if type(int2) ==int: return True else: return False else: return False print(only_ints(1, 2))
from stop_words import get_stop_words stop_words = set(get_stop_words('en')) def convert_text_to_set_without_stop(text): _set = set() for token in text.split(' '): if token and token.lower() not in stop_words: _set.add(token) return _set
# Leetcode Problem 23 # Name: "Merge k Sorted Lists" # Difficulty: Hard # URL: https://leetcode.com/problems/merge-k-sorted-lists/ # Date: 2020-07-25 from typing import List from python3 import ListNode # My opinion on this problem is that it is a lot like a SumK problem where an efficient implementation of Sum2 is the answer. # To solve this, I will use a modified version of my method problem 21 (Merge 2 sorted lists), and repeatedly apply it # Assuming the Big-O of my merge2 is O(n) where n is the length of the longest list, the runtime of this will be O(kn), where # k is the number of lists class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: if not lists: return None if len(lists) == 1: return lists[0] def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode: if not l1: return l2 if not l2: return l1 out_head, out_tail = None, None while l1 or l2: if not l1: out_tail.next = l2 return out_head if not l2: out_tail.next = l1 return out_head if l1.val < l2.val: next = l1 l1 = l1.next else: next = l2 l2 = l2.next if not out_head: out_head = next else: out_tail.next = next out_tail = next return out_head out = mergeTwoLists(lists[0], lists[1]) for x in range(2, len(lists)): out = mergeTwoLists(out, lists[x]) return out
# Leetcode Problem 3 # Name: "Longest Substring Without Repeating Characters" # Difficulty: Medium # URL: https://leetcode.com/problems/longest-substring-without-repeating-characters/ # Date: 2020-07-24 class Solution: def lengthOfLongestSubstring(self, s: str) -> int: history = list() max_length = 0 length = 0 for letter in s: while letter in history: del history[0] length -= 1 history.append(letter) length += 1 if length > max_length: max_length = length return max_length
# Leetcode Problem 4 # Name: "Median of Two Sorted Arrays" # Difficulty: Hard # URL: https://leetcode.com/problems/median-of-two-sorted-arrays/ # Date: 2020-07-24 from typing import List class Solution: def median(self, lst: List[int]) -> float: length = len(lst) mid = int(length/2) if length % 2: return lst[mid] else: return (lst[mid-1] + lst[mid])/2 def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: # TODO: Time complexity is in excess of O(log(n+m). Revisit this problem in the future return self.median(sorted(nums1 + nums2))
class Student: def __init__(self, name, surname, gender): self.name = name self.surname = surname self.gender = gender self.finished_courses = [] self.courses_in_progress = [] self.grades = {} def rate_lecturer(self, lecturer, course, grade): if isinstance(lecturer, Lecturer) and course in self.courses_attached and course in lecturer.courses_in_progress: if course in lecturer.grade: lecturer.grade[course] += grade else: lecturer.grade[course] = grade def avg_grade(self): my_list = [] for grade in self.grades.values(): for mark in grade: my_list.append(mark) stud_avg = sum(my_list) / len(my_list) return stud_avg def avg_grade_course(students, course): my_list = [] for student in students: if student.grades.get(course) != None: for kurs in student.grades.get(course): my_list.append(course) else: pass avg_grade_course = sum(my_list) / len(my_list) return avg_grade_course def __str__(self): print("Name: ", self.name) print("Surname: ", self.surname) print("Average grade: ", self.avg_grade()) print("Courses in progress: ", self.courses_in_progress) print("Finished courses: ", self.finished_courses) def __lt__(self, other): if not isinstance(other, Student): print("Not a student") else: return self.avg_grade() < other.avg_grade() class Mentor: def __init__(self, name, surname): self.name = name self.surname = surname self.courses_attached = [] class Reviewer(Mentor): def rate_hw(self, student, course, grade): if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress: if course in student.grades: student.grades[course] += [grade] else: student.grades[course] = [grade] else: return 'Ошибка' def __str__(self): print("Name: ", self.name) print("Surname: ", self.surname) class Lecturer (Mentor): def __init__(self, name, surname): self.name = name self.surname = surname self.courses_attached = [] self.courses_in_progress = [] self.grades = {} def lec_avg_grade(self): my_list = [] for grade in self.grades.values(): for mark in grade: my_list.append(mark) lec_avg = sum(my_list) / len(my_list) return lec_avg def __str__(self): print("Name: ", self.name) print("Surname: ", self.surname) print("Average grade: ", self.lec_avg_grade()) def __lt__(self, other): if not isinstance(other, Lecturer): print("Not a lecturer.") else: return self.lec_avg_grade() < other.lec_avg_grade() def lec_avg_grade_kurs(lecturers, course): my_list = [] for lecturer in lecturers: if lecturer.grades.get(course) != None: for kurs in lecturer.grades.get(course): my_list.append(course) else: pass lec_avg_grade_course = sum(my_list) / len(my_list) return lec_avg_grade_course best_student = Student('Ruoy', 'Eman', 'your_gender') best_student.courses_in_progress += ['Python'] cool_mentor = Reviewer('Some', 'Buddy') cool_mentor.courses_attached += ['Python'] cool_mentor.rate_hw(best_student, 'Python', 10) cool_mentor.rate_hw(best_student, 'Python', 10) cool_mentor.rate_hw(best_student, 'Python', 10) lk = Lecturer("Biba", 'Boba') print(best_student.grades)
import numpy as np import matplotlib.pyplot as plt class GaussPlay: """Gaussian Data Creation and functional tool.""" def __init__(self): """ Constructor: to instantiate the data. """ self.data = np.random.randn(2, 200) def scatter(self): """ Scatter Plot the intermediate result :return: """ plt.scatter(self.data[0, :], self.data[1, :]) plt.xlim([-5, 5]) plt.ylim([-5, 5]) return self def scale(self, x, y): """ Scaling the matrix with different scales. :return: """ S = np.array([[x, 0], [0, y]]) self.data = S @ self.data return self def rotate(self, theta): """ Rotation by the required angle. """ R = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]) self.data = R @ self.data return self def plot(self): """ Plot the result in case scatter is not sufficient. :return: """ plt.plot(self.data) plt.show() return self A = GaussPlay() A.scale(2,0.5).rotate(45).rotate(45).scatter()
from sys import argv import string script, filename = argv text = open(filename) word_count = {} # for loop by line: checking for words, adding to dictionary for line in text: line = line.rstrip().lower() for punc in string.punctuation: line= line.replace(punc," ") words = line.split() for word in words: if not word_count.get(word): word_count[word] = 1 else: word_count[word] += 1 # print key and value pairs # keys_list = word_count.keys() # keys_list.sort(word_count, key = word_count.get, reverse = True) sorted_list = sorted(word_count.iteritems(), key = lambda item: (item[1], item[0]), reverse = False) #print sorted_list for item in sorted_list: print "%s, %s" % (item[0], item[1])
for index in range(0,101): if index % 3 == 0 : print( str(index) + " " + "fizz") if index % 5 == 0: print( str(index) + " " + "buzz") if index % 5 == 0 and index % 3 == 0: print( str(index) + " " + "fizzbuzz")
""" Given a m * n matrix of ones and zeros, return how many square submatrices have all ones. Example 1: Input: matrix = [ [0,1,1,1], [1,1,1,1], [0,1,1,1] ] Output: 15 Explanation: There are 10 squares of side 1. There are 4 squares of side 2. There is 1 square of side 3. Total number of squares = 10 + 4 + 1 = 15. Example 2: Input: matrix = [ [1,0,1], [1,1,0], [1,1,0] ] Output: 7 Explanation: There are 6 squares of side 1. There is 1 square of side 2. Total number of squares = 6 + 1 = 7. """
def Merge(arr, p, q, r): l_size = q - p + 1 r_size = r - q arr_left = arr[p:q+1] arr_right = arr[q+1:r+1] i = 0 j = 0 k = p while (i < l_size) and (j < r_size): if (arr_left[i] > arr_right[j]): arr[k] = arr_right[j] j += 1 else: arr[k] = arr_left[i] i += 1 k += 1 while(i < l_size): arr[k] = arr_left[i] i += 1 k += 1 while(j < r_size): arr[k] = arr_right[j] j += 1 k += 1 def MergeSort(arr, p, r): if (p < r): q = (int)((p + r) / 2) MergeSort(arr, p, q) MergeSort(arr, q + 1, r) Merge(arr, p, q, r) arr = [2037, -100, -66, 999, 0, 15, 22, 1024, -66, 10101010, 234, -234] size = len(arr) print("Pre-MergeSort: \n", arr) MergeSort(arr, 0, size - 1) print("Post-MergeSort: \n", arr)
# Remove non-ASCII characters in CSV file import sys import re if __name__ == '__main__': if len(sys.argv) < 2: print('Please specify a CSV file') sys.exit(1) input_file = sys.argv[1] print('Input file: {}'.format(input_file)) if input_file.endswith('.csv'): output_file = input_file.split('.csv')[0] elif input_file.endswith('.txt'): output_file = input_file.split('.txt')[0] else: print('The file must end with ".csv" or ".txt"') sys.exit(1) output_file += '_nonASCII_removed.csv' print('Output file: {}'.format(output_file)) # Detect encoding of input_file # res = chardet.detect(open(input_file, 'rb').read(10)) # input_encoding = res['encoding'] # print('Input encoding detected: {}, with {} confidence'.format(input_encoding, res['confidence'])) with open(input_file, 'rb') as fr, open(output_file, 'w') as fw: lines = fr.read() if b'\r' in lines: print('New line is separated by "\\r"') lines = lines.split(b'\r') elif b'\n' in lines: print('New line is separated by "\\n"') lines = lines.split(b'\n') for line in lines: # replace non-ASCII characters with '' line = ''.join(chr(c) if c < 128 else '' for c in line).strip() # remove rows that do not contain separater '\t' if '\t' not in line: print('Remove a line that does not contain "\\t"') continue # replace consecutive underscores __ with space line = re.sub(r'[_|,]{2,}', ' ', line) # replace double quotes with '' line = re.sub(r'\"', '', line) fw.write(line + '\n') print('Done!')
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. # ask user for the temperature and convert to a string in 1 step far = float(input("What is the temperature? ")) # conversion f_to_c=((far-32) * (5.0/9.0)) # print the conversion from F to C using 1 decimal place print("{:.1f}".format(far) + " degrees F is " + "{:.1f}".format(f_to_c) + " degrees C") # See PyCharm help at https://www.jetbrains.com/help/pycharm/
""" This script generates google search queries and uses requests to go get the HTML from the google search page. This was the most time-consuming step in the process. Certain lines are commented out as evidence of debugging and to help me remember what I had already done. Anyways, this script makes links by week from 2010 to 2016 (included) Spits out html files of google searches""" __author__ = 'Kyle Martin' __email__ = 'me@mkylemartin.com' import requests as r import time import random # year_range = range(2014, 2017) year_range = range(2010, 2013) month_range = range(1, 13) weeks = [(1, 7), (8, 14), (15, 21), (22, 28)] userAgent = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/' '537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36') # for week in weeks: # print('week ' + str(week) + # ' start: ' + str(week[0]) + # ' end: ' + str(week[1])) def get_links(month_range, weeks): """ pass in month and day to write a query that will go get all the links on that google search page. """ links = [] for year in year_range: for month in month_range: for week in weeks: # append to a search_str list link_a = ('https://www.google.com/search?q=de&num=100&lr' '=lang_fr&tbs=cdr:1,cd_min:') link_b = (str(month) + '/' + str(week[0]) + '/' + str(year) + ',cd_max:' + str(month) + '/' + str(week[1])) link_c = '/' + str(year) + ',sbd:1&tbm=nws&cr=countryFR' link = link_a + link_b + link_c links += [link, ] return links query_list = get_links(month_range, weeks) """ I used the following lines to track how often I was getting blocked by google. # 0 - 26 at 10:56 PM mar 15 # 27 - 48 at 4:38 PM mar 16 # 48 - 60 at 10:45 AM mar 17 # stopped at 81 11:52 AM""" # I had to manually set the index value of my query list whenever the script # would die out. index = 120 for url in query_list[120:len(query_list)]: print('GETting {}...'.format(url)) headers = {'user-agent': userAgent} response = r.get(url, headers=headers) with open('new-webpages/search_no_' + str(index) + '.txt', 'w+') as f: f.write(response.text) print('wrote file no. ' + str(index)) time.sleep(random.uniform(30, 45)) index += 1 print('done!')
#!/usr/bin/python3 """ Min value """ def factor(num): """ Return factors of number """ prime_list = [] value = num i = 1 while value != 1: i += 1 if value % i == 0: while (value % i == 0 and value != 1): value /= i prime_list.append(i) return prime_list def minOperations(n): if n < 2 or type(n) is not int: return 0 values = factor(n) return sum(values)
# # Functional Programing (Separation of concerns) # # - Pure functions # # - # # - # # # # Pure functions # # - Given the same input, it will always return # # the same output that is, every time we give # # - Function should not produce any side effects # # def multiply_by2(li): # new_list = [] # for item in li: # new_list.append(item * 2) # return new_list # # # print(multiply_by2([1, 2, 3])) # # Useful functions: map, filter, zip and reduce # # # map # def multiply_by2(item): # we just need an action; what effect we want to produce # return item * 2 # # # my_list = [1, 2, 3] # # map call the func for us and make NEW list with some effect of # # doing something and take a result # print(list(map(multiply_by2, my_list))) # [2, 4, 6] # print(my_list) # Does not change anything outside the world # # # # filter # def only_odd(item): # return item % 2 != 0 # # # my_list = [1, 2, 3, 4] # # filter call the func for us and make NEW list with some effect # # if TRUE it'll be add to new list, or opposite if FALSE! # print(list(filter(only_odd, my_list))) # [1, 3] # print(my_list) # Does not change anything outside the world # # # zip # first_list = [1, 2, 3, 4] # second_list = (10, 20, 30, 40, 50) # third_list = {-1, -2, -3} # # # Take first elem of first list and first elem of second list and .... # # and zips(connect) them, into: [(), (), ...] # print(list(zip(first_list, second_list, third_list))) # [(1, 10, -3), (2, 20, -1), (3, 30, -2)] # # # reduce # from functools import reduce # # def accumulator(acc, item): # return acc + item # # # my_list = [1, 2, 3, 4] # # We go threw over our list with the last returned value # print(reduce(accumulator, my_list, 0)) # # Exercise: # # 1 Capitalize all of the pet names and print the list # my_pets = ['sisi', 'bibi', 'titi', 'carla'] # # # def capitalize_words(item): # return str(item).capitalize() # # # print(list(map(capitalize_words, my_pets))) # # # 2 Zip the 2 lists into a list of tuples, but sort the numbers from lowest to highest. # my_strings = ['a', 'b', 'c', 'd', 'e'] # my_numbers = [5, 4, 3, 2, 1] # # print(list(zip(sorted(my_numbers), my_strings))) # # # # 3 Filter the scores that pass over 50% # def bigger_then_50pers(item): # return item > 50 # # # scores = [73, 20, 65, 19, 76, 100, 88] # print(list(filter(bigger_then_50pers, scores))) # # # # 4 Combine all of the numbers that are in a list on this file using reduce (my_numbers and scores). What is the # total? # def combine(acc, item): # return acc + item # # # print(reduce(combine, (my_numbers + scores))) # # Lambda expressions, we not need more than once # my_list = [1, 2, 3] # # print(list(map(lambda param: param * 2, my_list))) # Just use simple(pure) function # print(list(filter(lambda param: param % 2 != 0, my_list))) # print(reduce(lambda acc, item: acc + item, my_list)) # # Exercise # my_list = [5, 4, 3] # print(list(map(lambda param: param ** 2, my_list))) # # a = [(0, 2), (4, 3), (9, 9), (10, -1)] # a.sort(key=lambda x: x[1]) # print(a) # # Comprehensions: list, set, dictionary # my_list = [char for char in 'hello'] # print(my_list) # ['h', 'e', 'l', 'l', 'o'] # # my_set = {char for char in 'hello'} # print(my_set) # {'l', 'o', 'h', 'e'} # # list_nums = [num * 2 for num in range(0, 100)] # print(list_nums) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, .... # # list_even_nums = [num ** 2 for num in range(0, 100) if num % 2 == 0] # print(list_even_nums) # [0, 4, 16, 36, 64, 100, 144, 196, 256, .... # # # list_nums = [num for num in range(0, 30)] # list_letters = [chr(char) for char in range(97, 123)] # my_dict = {key: value ** 2 for key, value in list(zip(list_letters, list_nums)) if value % 2 == 0} # print(my_dict) # {'a': 0, 'c': 4, 'e': 16, 'g': 36, 'i': 64, # # my_dict = {num: num * 2 for num in range(1, 10) if num % 2 != 0} # print(my_dict) # {1: 2, 3: 6, 5: 10, 7: 14, 9: 18} # # Check for duplicates # some_list = ['a', 'b', 'c', 'b', 'd', 'm', 'n', 'n'] # # duplicates = list({char for char in some_list if some_list.count(char) > 1}) # print(duplicates)
def multiply(num1, num2): try: return num1 * num2 except (ValueError, TypeError): return 'Please input correct value' def divide(num1, num2): try: return num1 / num2 except (ValueError, TypeError): return 'Please input correct value' except ZeroDivisionError: return 'Second number can not be zero!' class Student: pass if __name__ == '__main__': print(__name__)
# # Generators # # we never create a list in memory if use # # generator like this # print((range(0, 100))) # # instead of when we use memory, like this: # print(list(range(0, 100))) # # # def make_list(num): # what we do here: list(range(num)) # result = [] # for item in range(num): # result.append(item) # return result # # # print(make_list(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # # range(10) # is generator and it's iterable # list(range(100)) # a list created from generator and it's iterable, but not a generator # # # if obj has a dander method __iter__ it'll be an iterable obj # # also generator is a subset of an iterable # # Create our own generator: # def generator_function(num): # for it in range(num): # # yield says, just pause the function, just yield i # # give i and when you tell me to keep going again, then i'll keep going # yield it*2 # # # try: # g = generator_function(3) # print(next(g)) # 0 # print(next(g)) # 2 # print(next(g)) # 4 # print(next(g)) # 6 # except StopIteration as err: # print('StopIteration Error') # for i in generator_function(10): # print(f'{i}') # if i > 5: # break # Performance decorator from time import time def performance(func): def wrapper(*args, **kwargs): t1 = time() result = func(*args, **kwargs) t2 = time() print(f'It took {t2 - t1} s') return result return wrapper # @performance # def long_time(): # print('1') # for i in range(10 ** 8): # pass # # # @performance # def long_time2(): # print('2') # for i in list(range(10 ** 8)): # pass # # # long_time() # It took 1.4162635803222656 s # long_time2() # It took 3.464097261428833 s # # Create our own for loop: # def special_for(iterable): # iterator = iter(iterable) # while True: # try: # # print(iterator) # # print(next(iterator)) # next(iterator) # except StopIteration: # print('StopIteration') # break # except Exception as err: # print(err) # # # special_for([1, 2, 3]) # we can see that the obj still in the same position of memory # # # # Create our own range # class MyGen(object): # current = 0 # # def __init__(self, first, last): # self.first = first # self.last = last # # def __iter__(self): # return self # # def __next__(self): # if MyGen.current < self.last: # num = MyGen.current # MyGen.current += 1 # return num # raise StopIteration # # # @performance # def own_types(): # gen = MyGen(0, 10 ** 8) # for i in gen: # pass # # # @performance # def build_in_types(): # gen = range(0, 10 ** 8) # for i in gen: # pass # # # print('Own type') # own_types() # It took 28.199716329574585 s # print('Build in type') # build_in_types() # It took 1.8361592292785645 s # # Create our own fibonacci range # class MyFibonacciGen(object): # current = 0 # next = 1 # state = 0 # # def __init__(self, first, last): # self.first = first # self.last = last # # def __iter__(self): # return self # # def __next__(self): # if MyFibonacciGen.state <= self.last: # MyFibonacciGen.state += 1 # result = MyFibonacciGen.current # temp = MyFibonacciGen.next # MyFibonacciGen.next += MyFibonacciGen.current # MyFibonacciGen.current = temp # return result # raise StopIteration # # # @performance # def own_types(): # gen = MyFibonacciGen(0, 10 ** 3) # for i in gen: # pass # # # def fib(number): # a = 0 # b = 1 # for i in range(number): # yield a # temp = a # a = b # b = temp + b # # # @performance # def Andr_types(): # for x in fib(10 ** 3): # pass # # # print('Own type') # # It took 718.6488845348358 s for 10^7 # own_types() # It took 7.056485652923584 s for 10^6 # print('Andr type') # # It took 692.5728919506073 s for 10^7 # Andr_types() # 6.633790731430054 s for 10^6
# Heard on the Street # Q4.17 # payoff = final dice result # player chooses when to stop import random def play_game(turn): is_next = True remaining_turn = turn while is_next: payoff = random.randint(1,6) remaining_turn += -1 is_next = (remaining_turn > 0) and not(terminate(payoff, remaining_turn)) return payoff def terminate(payoff, remaining_turn): if (payoff >= 5): return True elif (payoff >= 4 and remaining_turn <= 1): return True else: return False def play_many_games(game_count): payoff_total = 0.0 for x in range(game_count): payoff_total += play_game(3) print(payoff_total / game_count) play_many_games(100000)
# You are given a set A and other n sets. # Your job is to find whether set A is a strict superset of each of the N sets. # Print True, if A is a strict superset of each of the N sets. Otherwise, print False. # A strict superset has at least one element that does not exist in its subset. # Example # Set (1,3,4) is a strict superset of set(1,3). # Set(1,3,4) is not a strict superset of set (1,3 4). # Set(1,3,4) is not a strict superset of set (1,3 5). # Input Format # The first line contains the space separated elements of set A. # The second line contains integer n, the number of other sets. # The next n lines contains the space separated elements of the other sets. # Constraints # Output Format # Print True if set A is a strict superset of all other N sets. Otherwise, print False. # Sample Input 0 # 1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78 # 2 # 1 2 3 4 5 # 100 11 12 # Sample Output 0 # False # Explanation 0 # Set A is the strict superset of the set (1,2,3,4,5) but not of the set (100,11,12) because 100 is not in set A. # Hence, the output is False. setSuper = set(input().split()) result = True n = int(input()) for i in range(n): set1 = set(input().split()) if set1.difference(setSuper) != set(): result = False break else: result= True print(result)
# You are given a string . # Your task is to find out whether is a valid regex or not. # Input Format # The first line contains integer , the number of test cases. # The next lines contains the string . # Constraints # Output Format # Print "True" or "False" for each test case without quotes. # Sample Input # 2 # .*\+ # .*+ # Sample Output # True # False # Explanation # .*\+ : Valid regex. # .*+: Has the error multiple repeat. Hence, it is invalid. import re for _ in range(int(input())): result = True try: reg = re.compile(input()) except re.error: result = False print(result)
# Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line. # Input Format # The first line contains an integer, N , the number of students. # The 2N subsequent lines describe each student over 2 lines; the first line contains a student's name, and the second line contains their grade. # Constraints # There will always be one or more students having the second lowest grade. # Output Format # Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line. # Sample Input 0 # 5 # Harry # 37.21 # Berry # 37.21 # Tina # 37.2 # Akriti # 41 # Harsh # 39 # Sample Output 0 # Berry # Harry # Explanation 0 # There are 5 students in this class whose names and grades are assembled to build the following list: # python students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] # The lowest grade of 37.2 belongs to Tina. The second lowest grade of 37.21 belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line. if __name__ == '__main__': students=[] for _ in range(int(input())): list_1 = [] name = input() score = float(input()) students.append([name, score]) minElem = min(students,key= lambda x:x[1]) for i in sorted(students, key = lambda x:x[1]): if i[1] > minElem[1]: minValue = i[1] break result = [] for i,x in enumerate(sorted(students, key = lambda x:x[1])): if x[1] == minValue: result.append(x) for i in sorted(result): print(i[0]) # you can also solve it by: if __name__ == '__main__': result=list() list2 = list() for _ in range(int(input())): list1 = list() name = input() score = float(input()) list1.append(name) list1.append(score) list2.append(list1) minData = min(list2, key= lambda x:x[1] ) for i in sorted(list2, key=lambda x:x[1]): if i[1] > minData[1]: result.append(i); break; for i in sorted(list2, key=lambda x:x[1]): if i[0] != result[0][0]: if i[1] == result[0][1] : result.append(i); for i in sorted(result): print(i[0])
# You are given a string S and width w. # Your task is to wrap the string into a paragraph of width w. # Input Format # The first line contains a string, S. # The second line contains the width, w. # Constraints # Output Format # Print the text wrapped paragraph. # Sample Input 0 # ABCDEFGHIJKLIMNOQRSTUVWXYZ # 4 # Sample Output 0 # ABCD # EFGH # IJKL # IMNO # QRST # UVWX # YZ import textwrap def wrap(string, max_width): # without using textwrap finalResult = "" for i in range(0, len(string), max_width): str1 = "" for j in range(i, i + max_width): if j >= len(string): break; str1 = str1 + string[j] if len(finalResult) == 0: finalResult = str1 else: finalResult = finalResult + "\n" + str1 return finalResult # Using textwrap # return textwrap.fill(string, max_width) # Alternate Method # return "\n".join([string[i:i+max_width] for i in range(0, len(string), max_width)]) if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
# Check Tutorial tab to know how to to solve. # Task # Given an integer, n, perform the following conditional actions: # If n is odd, print Weird # If n is even and in the inclusive range of to , print Not Weird # If n is even and in the inclusive range of to , print Weird # If n is even and greater than , print Not Weird # Input Format # A single line containing a positive integer, . # Constraints # 1 <= n <= 100 # Output Format # Print Weird if the number is weird; otherwise, print Not Weird. # Sample Input 0 # 3 # Sample Output 0 # Weird # Explanation 0 # n=3 # n is odd and odd numbers are weird, so we print Weird. # Sample Input 1 # 24 # Sample Output 1 # Not Weird # Explanation 1 # n=24 # n > 20 and n is even, so it isn't weird. Thus, we print Not Weird. N = int(input()) if N%2 is 1: print("Weird") elif N%2 is 0 and N in range(2,6): print("Not Weird") elif N%2 is 0 and N in range(6,21): print("Weird") else: print("Not Weird")
# Задача 4 (опциональная) # Необходимо сократить дробь, записанную в римской системе счисления (числа от 1 до 999). # Римская система счисления: '''https://ru.wikipedia.org /wiki/%D0%A0%D0%B8%D0%BC%D1%81%D0%BA%D0%B8%D0%B5_%D1%86%D0%B8%D1%84%D1%80%D1%8B ''' # Ввод: "II/IV" # Вывод: "I/II" # Ввод: "XXIV/VIII" # Вывод: "III" # Ввод: "12/16" # Вывод: "ERROR" # ___________________________________________________________________________________________ from fractions import Fraction # ввод данных value = input('enter values: ').replace(' ', '').split('/') # проверка корректности check = list(map(list, value)) if len(check) != 2: print('\nincorrect input') exit() def isroman(num): for any in num: if any not in 'IVXLCDM': print('\nincorrect input') exit() isroman(check[0]) isroman(check[1]) # перевод римских чисел в арабские def inarabic(value): answer = 0 def discharge_inarabic(rom, discharge): # rom от меньшего к большему, пример: CDM nonlocal answer nonlocal value rom = list(rom) X = '' def ent_check(): nonlocal rom nonlocal value nonlocal X for any in rom: if value.startswith(any): X += value[0] value = value[1:] for _ in range(4): ent_check() if X.startswith(rom[0]): if len(X) == 2: if X[1] in rom[1]: answer += discharge * 4 if X[1] in rom[2]: answer += discharge * 9 if X in rom[0] * 3: answer += discharge * len(X) if X.startswith(rom[1]): if len(X) == 1: answer += discharge * 5 if 1 < len(X) <= 4 and X[1:] in rom[0] * 3: answer += discharge * 5 + discharge * (len(X) - 1) discharge_inarabic('CDM', 100) discharge_inarabic('XLC', 10) discharge_inarabic('IVX', 1) if value: print('\nincorrect input') exit() if not answer: print('\nincorrect input') exit() return answer # сокращаем дробь arabic_answer = str(Fraction(inarabic(value[0]), inarabic(value[1]))).split('/') arabic_answer = list(map(int, arabic_answer)) # go back in roman def in_roman(value): answer = '' def discharge_inroman(): nonlocal value nonlocal answer if len(str(value)) == 3: rom = list('CDM') discharge = 100 if len(str(value)) == 2: rom = list('XLC') discharge = 10 if len(str(value)) == 1: rom = list('IVX') discharge = 1 if 5 <= value // discharge <= 8: answer += rom[1] if 6 <= value // discharge <= 8: keks = value // discharge - 5 answer += rom[0] * keks if 1 <= value // discharge <= 3: answer += rom[0] * (value // discharge) if value // discharge == 4: answer += rom[0] answer += rom[1] if value // discharge == 9: answer += rom[0] answer += rom[2] value = value - (value // discharge * discharge) for_range = len(str(value)) for _ in range(for_range): discharge_inroman() return answer # ответыч print(f'\nответ: {in_roman(arabic_answer[0])}/{in_roman(arabic_answer[1])}')
""" # Python实用函数 # 包含函数: print_with_style() ----- 拓展print()函数,使其输出时可以携带样式 print_spend_time()装饰器 ----- 获取某函数执行时所消耗的时间 """ from functools import wraps from datetime import datetime def print_with_style(*args, style='', **kwargs): """带样式的打印,它是对print()函数的拓展. # 参数: style:要使用的样式,它可以是以下值:(多个样式之间用加号'+'隔开) 'r':红色 'g':绿色 'b':蓝色 'B':加粗 'U':下划线 其它: 其它格式控制代码,如:'\033[7m' others:指其它可用于print()函数的参数,如end, sep, file等. # 例子: print_with_style(value, ..., style='g+B') print_with_style(value, ..., style='B+\033[7m', sep='>') """ styles = { 'r': '\033[31m', # 红色 'g': '\033[92m', # 绿色 'b': '\033[94m', # 蓝色 'B': '\033[1m', # 加粗 'U': '\033[4m' # 下划线 } style_lsit = set(style.split('+')) for s in style_lsit: if s in styles: print(styles[s], end='') elif s.startswith('\033'): print(s, end='') print(*args, **kwargs) print('\033[0m', end='') def print_spend_time(format_str='执行函数{func_name},共耗时:{d}天{h}小时{m}分钟{s:02d}秒{ms}微秒', end='\n'): """获取函数执行时间的装饰器,可对输出字符串进行定制. # 参数: format_str: 定制的输出字符串,可在其中使用的插槽有: {d}: 天, {h}:小时, {m}:分钟, {s}:秒, {ms}:微秒, {th}:总小时, {tm}:总分钟, {ts}:总秒, {tms}:带微秒的总秒, {func_name}:执行的函数名 end: 换行符,默认为'\\n' # 例子: @print_spend_time(format_str='执行完成,共耗时:{tms} s') def f(): ... """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): start_time = datetime.now() result = func(*args, **kwargs) # 执行被包装的函数 end_time = datetime.now() spend_time = end_time - start_time m, s = divmod(spend_time.seconds, 60) # seconds h, m = divmod(m, 60) # hours, minutes d = spend_time.days # days ms = spend_time.microseconds # microseconds th = d*24 + h # total hours tm = d*24*60 + h*60 + m # total minutes ts = d*24*60*60 + spend_time.seconds # total seconds tms = ts + spend_time.microseconds # total seconds with microseconds final_str = format_str.format(d=d, h=h, m=m, s=s, ms=ms, th=th, tm=tm, ts=ts, tms=tms, func_name=func.__name__ + '()') print(final_str, end=end) return result return wrapper return decorator
#! /usr/bin/env python """ I was going to implement this in `C++`, but this algorithm is on the front page of Python website. (really!) So, much like my Haskell quicksort implementation, I feel obliged to include this bottom-up fibonacci memoization example.""" def fibonacci(n: int) -> int: a = 0 b = 1 for _ in range(n-1): a,b = b,a+b return b if __name__ == "__main__": index = 0x2f expected = 2971215073 calculated = fibonacci(index) assert expected == calculated, "YOU ARE WRONG!" print(f"Hurray! Fibonacci index {index} is {calculated}!")
import pandas as pd import sqlite3 # Load the XLSX file into a pandas dataframe df = pd.read_excel('./OI - Copy of LumberFut.xlsx') #dropping the cols which does not have any value df.drop(df[df.Open == "-"].index, inplace=True) #collecting the list of columns col_list = df.columns[1:] #converting them to numeric format for col in col_list: df[col] = pd.to_numeric(df[col]) #converting the date column to datetype objecr df['Date'] = pd.to_datetime(df['Date']) # Create a new SQLite database and a new table conn = sqlite3.connect('mydatabase.db') df.to_sql('LumberFut', conn, if_exists='replace', index=False) # Save the changes and close the database connection conn.commit() conn.close()
from lxml import html, etree import requests # functions def build_dictionary_stopwords(string, word_dictionary): """ turns a string into individual, all lowercase words and places them into a dictionary to count them. Includes stopwords""" append_string = "" j = 0 for i in range (len(string)): if string[i].isalnum(): append_string = append_string + string[i].lower() else: if append_string != "": if append_string in word_dictionary: word_dictionary[append_string] += 1 else: word_dictionary[append_string] = 1 append_string = "" return (word_dictionary) def build_dictionary_no_stopwords(string, word_dictionary): """ turns a string into individual, all lowercase words and places them into a dictionary to count them. Doesn't include stopwords""" append_string = "" j = 0 # set that includes every english stopword as defined by NLTK stopwords = set(["i", "me", "my", "myself", "we", "our", "ours", "ourselves", "you", "your", "yours", "yourself", "yourselves", "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself", "they", "them", "their", "theirs", "themselves", "what", "which", "who", "whom", "this", "that", "these", "those", "am", "is", "are", "was", "were", "be", "been", "being", "have", "has", "had", "having", "do", "does", "did", "doing", "a", "an", "the", "and", "but", "if", "or", "because", "as", "until", "while", "of", "at", "by", "for", "with", "about", "against", "between", "into", "through", "during", "before", "after", "above", "below", "to", "from", "up", "down", "in", "out", "on", "off", "over", "under", "again", "further", "then", "once", "here", "there", "when", "where", "why", "how", "all", "any", "both", "each", "few", "more", "most", "other", "some", "such", "no", "nor", "not", "only", "own", "same", "so", "than", "too", "very", "s", "t", "can", "will", "just", "don", "should", "now"]) for i in range (len(string)): if string[i].isalnum(): append_string = append_string + string[i].lower() else: if append_string != "": # if append_string isn't a stopword, add it to word_dictionary if append_string not in stopwords: if append_string in word_dictionary: word_dictionary[append_string] += 1 else: word_dictionary[append_string] = 1 append_string = "" return (word_dictionary) # driver function that pulls data from the website, calls the build dictionary # function, and retrieves the most frequently used words def verbose_counter(website, number_of_words, duplicates_allowed=True, stopwords_allowed=False): """ returns a list of a website's most frequently used words. keyword args: website -- the website url number_of_words -- the number of frequently used words to return duplicates_allowed -- if there is a tie for the last word to return, allowing duplicates will return every word that is tied, and not allowing duplicates will break the tie in alphabetic order (default True) stopwords_allowed -- whether or not stopwords are allowed in the final list. Uses English stopwords from the NLTK. (default False) """ # retrieve html from website (5s timeout) and make tree r = requests.get(website, timeout=5) tree = html.fromstring(r.content) tags = tree.xpath('//body') # if there is text content in the body of the page, save it to the # 'text' string. otherwise make text blank if tags: body = tags[0] text = body.text_content() else: text = "" # intialize the word dictionary and call one of the build_dictionary # functions word_dictionary = dict() if stopwords_allowed: build_dictionary_stopwords(text, word_dictionary) else: build_dictionary_no_stopwords(text, word_dictionary) repeated_list = [] # loop through the dictionary for key, value in word_dictionary.items(): repeated_list.append([value, key]) # sort list in descending order of frequency first # and then alphabetically repeated_list.sort(key=lambda x: (-x[0], x[1])) i = 0 frequent_words = [] if repeated_list != []: if duplicates_allowed: while i < number_of_words: # if this is the last word to append to the list, # check to see if there are multiple words with the same # frequency if i < len(repeated_list): if i == number_of_words - 1: j = i while j < len(repeated_list): # if the word has the same frequency, append it to # frequent_words, otherwise break if (repeated_list[i][0] == repeated_list[j][0]): frequent_words.append(repeated_list[j][1]) else: break j += 1 else: frequent_words.append(repeated_list[i][1]) else: break i += 1 else: while i < number_of_words: if i < len(repeated_list): frequent_words.append(repeated_list[i][1]) i += 1 return frequent_words
from tkinter import * from tkinter.ttk import * root = Tk() dolar = StringVar() txtdolar = Entry(root, textvariable = dolar) txtdolar.pack() resultado = StringVar() lblResultado = Label(root, text = '',font = ("Arial", 25), textvariable = resultado) lblResultado.pack() combo = Combobox(root) combo['values'] = ("Lunes", "Martes", "Miercoles") combo.pack(pady = 15) lista = Listbox(root) lista.insert(0, "María") lista.insert(1, "Pirulo") lista.insert(2, "Jonas") lista.insert(3, "Agripino") lista.pack() radio1 = Radiobutton(root, text = "SQL", value = 1) radio2 = Radiobutton(root, text = "Python", value = 2) radio3 = Radiobutton(root, text = "Java", value = 3) radio1.pack() radio2.pack() radio3.pack() def convertir_dolar(): resultado.set(str(float(dolar.get()) * 58.5)) boton_calcular = Button(root, text = "Convertir", command=convertir_dolar) boton_calcular.pack() # Se establece el tamaño de la root root.geometry("600x400") # Dimension de la root # Se establece el mainloop para que la root queda abierta hasta que el usuario quiera root.mainloop()
# ~~~~~~~~~~~~~~~~~~~~~~~~ # Práctica 3: Saul Azcona # ~~~~~~~~~~~~~~~~~~~~~~~~ # 1- Hacer una función que potencie un número x a la y valor = 10 potencia = 2 # Definición de la función con 2 parámetros def pontenciar(a, b): x = a ** b return print(x) pontenciar(valor, potencia) # 2- Realizar una función que pida por pantalla un número del 1 al 10 y muestre # por pantalla el número escrito en letras. def numeros_a_letras(): n = int(input("Dame un número del 1 al 10: ")) if n > 10: print("Valiste vergas, te pedí un numero del 1 al 10") elif n == 1: print("Uno") elif n == 2: print("Dos") elif n == 3: print("Tres") elif n == 4: print("Cuatro") elif n == 5: print("Cinco") elif n == 6: print("Seis") elif n == 7: print("Siete") elif n == 8: print("Ocho") elif n == 9: print("Nueve") elif n == 10: print("Diez") numeros_a_letras() # 3- Hacer una función que reciba un año como argumento y retorne # verdadero si es bisiesto. def anio_bisiesto(a): if a % 4 == 0: if a % 100 == 0: if a % 400 == 0: print(True) else: print(False) else: print(True) else: print(False) # Probando ... anio_bisiesto(1900) anio_bisiesto(2012) anio_bisiesto(2020) anio_bisiesto(2021) anio_bisiesto(2022) anio_bisiesto(2023) anio_bisiesto(2024) # 4- Crear una función que evalúe dos números y retorne verdadero si ambos números son iguales. def igualdad(x, y): if x == y: print(True) else: print(False) # Se pone en ejecución la función igualdad(1, 5) igualdad(2, 2) # Probando con operaciones aritméticas dentro de la función igualdad(10/2, 5) igualdad(pow(10, 2), 100) # 5- Un número palindrómico se lee igual en ambos sentidos. # El palíndromo más grande hecho del producto de dos números de 2 dígitos es 9009 = 91 × 99. # Cree una función que encuentre el palíndromo más grande hecho del # producto de dos números de 3 dígitos. # # Se define una primera funcion para comprobar si los numeros introducidos son palíndromos def esPalindromo(num): return str(num) == str(num)[::-1] # Funcion para encontrar el palíndromo más grande def masGrande(num1, num2): z = 0 for x in range(num2, num1, -1): for y in range(num2, num1, -1): if esPalindromo( x * y): if x * y > z: z = x * y return z print(masGrande(100,999)) print(masGrande(191,121)) # 6- Hacer una función que reciba una cedula como argumento y diga si la # cedula es válida o no. def comprador_cedulas(): cedula = input("Introduzca la cedula a comprobar sin guiones: ") # Se hace uso de la función len() para comprobar si la longitud de los caracteres es mayor que 11 if len(cedula) > 11: print("Cédula incorrecta") else: print("Cédula válida") comprador_cedulas() # 7- Hacer una función que reciba como argumento una lista de elementos # numéricos y retorno otra lista con cada elemento de la primera lista # duplicados. def duplicador(lista): lista = lista # Con el ciclo for se recorre todos los datos de la lista for i in range(len(lista)): # Se imprime los valores de la lista con el índice i y se duplica print(lista[i] * 2) duplicador([2, 4, 6, 8, 10]) # 8- Hacer una función que reciba un valor iniciar y uno final, y muestre en # pantalla las tablas de multiplicar de los números múltiplos de 6 que hay # entre el valor inicial y el valor final. def tabla_multiplicar_num6(v_inicial, v_final): n = 6 # Número 6 # Si el valor inicial es mayor que el final se detiene la función if v_inicial > v_final: print("Error: Valor Inicial debe ser menor al Valor Final") else: while v_inicial <= v_final: res = n * v_inicial print(f"{n} X {v_inicial} = {res}") v_inicial += 1 # Del 5 al 8 tabla_multiplicar_num6(1, 10) # Del 11 al 20 tabla_multiplicar_num6(11, 20) # Si el inicial es mayor que el final debe lanzar el mensaje de error tabla_multiplicar_num6(10, 1)
class person: countinsatnce=0 def __init__(self,fname,lname,age): person.countinsatnce +=1 self.fname=fname self.lname=lname self.age=age @classmethod def countinsatnce(cls): print(f"heloo you call this function in {cls.countinsatnce} and name is{cls.__name__}") p1=person("sanket","kothiya",20) print(person.countinsatnce())
########################################## # # KNN.py # Juan Andres Carpio # Naomi Serfaty # ########################################## import math #Function that calculates the Eucledian distance between two points #In: #A: first array #B: second array #Out: #Eucledian distance between them def distance(A,B,named=False): result = 0.0 if named: for i in range(0,len(A)-1): result = result + ((A[i]-B[i])*(A[i]-B[i])) else: for i in range(0,len(A)): result = result + ((A[i]-B[i])*(A[i]-B[i])) return math.sqrt(result) #Function that sort the array of distances, # keeping the array of values with the same order #using the algorithm of bubble sort def double_sort(k,distances,values): #Bubblesort algorithm for j in range (0,k-1): min = j for i in range (j+1,k): if distances[i] < distances[min]: min = i #swap min and j temp_d = distances[min] temp_v = values[min] distances[min] = distances[j] values[min] = values[j] distances[j] = temp_d values[j] = temp_v #Function that predict the value for an example using K nearest neighbour algorithm #In: #example: value to classify #data: data to use for the classification #k: number of neighbours #Out: #classification result: yes or no def knearest(k,data,example,named=False): #Initiate values distances = [] values = [] #First k values for i in range(0,k): d = distance(example,data[i],named) distances.append(d) length = len(data[i])-1 values.append(data[i][length]) double_sort(k,distances,values) #For each value calculate the distance. If it is less than the #maximun stored value, switch them and sort the array of neighbours for i in range (k+1,len(data)): d = distance(example,data[i],named) if (d <= distances[k-1]): distances[k-1] = d length = len(data[i])-1 values[k-1] = data[i][length] double_sort(k,distances,values) #Count values yes = 0 no = 0 for i in range (0,k): if values[i] == 'yes': yes = yes + 1 else: no = no + 1 #Classification if yes >= no: return 'yes' if yes < no: return 'no'
''' Pravesh Gaire 7/6/2019 Finds the shortest path from a point to another point in mxn grid A* Algorithm TO DO: Neighbours needs to be generalized ''' # Func to check if a cell is valid or not def isValid(x, y): return (x< ROW and x>=0 and y<COL and y>=0) # Func to check if a cell is blocked or not def isBlocked(x, y): return not MAP[x][y] # Calculate H value using Manhattan Distance def calculateH(x, y): return abs(x - DX) + abs(y - DY) # Grid Size ROW = 10 COL = 10 # MAP # 1 represents movable node & 0 represents blocked node MAP = [ [ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 ], [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 ], [ 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 1, 0, 1, 0, 0, 1 ], [ 1, 0, 1, 0, 1, 1, 1, 0, 1, 0 ], [ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 ], [ 1, 0, 1, 0, 0, 1, 0, 0, 0, 1 ], [ 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 ], [ 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 ], [ 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 ], ] # Source SX, SY = 0, 0 # Destination DX, DY = 3, 1 destinationFound = False validity = True # Check if the given inputs are valid for various conditions if not isValid(SX, SY): print("Source is not valid") validity = False if not isValid(DX, DY): print("Destination is not valid") validity = False if isBlocked(SX, SY): print("Source is blocked") validity = False if isBlocked(DX, DY): print("Destination is blocked") validity = False if ((SX, SY) == (DX, DY)): print("Source and Destination are at same") validity = False # Closed list closedList = [[0 for j in range(COL)] for i in range(ROW)] # list to store the details of the cells cellDetails = [ [ {'f':float("inf"), 'g':float('inf'), 'h':float('inf'), 'PX':-1, 'PY':-1} for j in range(COL) ] for i in range(ROW) ] # initialize the source cellDetails[SX][SY]['f'] = 0.0 cellDetails[SX][SY]['g'] = 0.0 cellDetails[SX][SY]['h'] = 0.0 cellDetails[SX][SY]['PX'] = SX cellDetails[SX][SY]['PY'] = SY # Open List openList = [] openList.append([0, SX, SY]) neighbours = [(-1, 0), (1, 0), (0, 1), (0, -1)] while(openList and validity): parent = min(openList) #parent = openList.pop() openList.remove(parent) closedList[parent[1]][parent[2]] = True # add to closed list # Generate the 4 neighbours in E, W, N & S of the popped cell # N --> North (i-1, j) # S --> South (i+1, j) # E --> East (i, j+1) # W --> West (i, j-1) for i in range(4): if (isValid(parent[1] + neighbours[i][0], parent[2] + neighbours[i][1])): # Check if destination is reached if((parent[1] + neighbours[i][0], parent[2] + neighbours[i][1]) == (DX, DY)): cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['PX'] = parent[1] cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['PY'] = parent[2] print("Destination is found") destinationFound = True break # check if it is already in closed list or blocked elif ((not closedList[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]) and (not isBlocked(parent[1] + neighbours[i][0], parent[2] + neighbours[i][1]))): # find new values newG = cellDetails[parent[1]][parent[2]]['g'] + 1.0 newH = calculateH(parent[1] + neighbours[i][0], parent[2] + neighbours[i][1]) newF = newG + newH # check if it is in open list # if it is in open list compare and replace if it is better # if it is not in open list, add it and details if ((cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['f'] == float('inf')) or (cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['f'] > newF)): openList.append([newF, parent[1] + neighbours[i][0], parent[2] + neighbours[i][1]]) cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['f'] = newF cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['g'] = newG cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['h'] = newH cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['PX'] = parent[1] cellDetails[parent[1] + neighbours[i][0]][parent[2] + neighbours[i][1]]['PY'] = parent[2] # Tracing the path tracedPath = [(SX, SY), (DX, DY)] if not destinationFound: print("Sorry, couldnot find the destination") else: print("\nThe path is\n") row = cellDetails[DX][DY]['PX'] col = cellDetails[DX][DY]['PY'] while(not (row == SX and col == SY)): tracedPath.insert(1, (row, col)) x = cellDetails[row][col]['PX'] y = cellDetails[row][col]['PY'] row, col = x, y # print(*tracedPath) from directions import directions print(directions(tracedPath))
def maxSubArray(nums): if len(nums) == 0: return None if len(nums) == 1: return nums[0] max_num = nums[0] num = nums[0] for i in range(1, len(nums)): if max_num < nums[i]: #动态规划找到各个子序列max_num max_num = nums[i] elif max_num >= nums[i]: max_num = max_num + nums[i] if num < max_num: # 保留最大的子序列num num = max_num return num if __name__ == '__main__': nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(maxSubArray(nums))
from math import log def trie_worst_space(c, n, l, s): if c == 0: return -1 if s == 0: if l == 0: return -1 if n == 0: return c ** l foo = 0 cur = n for level in xrange(l, -1, -1): if log(cur * 1.0) / log(c * 1.0) > level - 1.0: cur = min(cur, c ** level) foo += cur return foo else: foo = 1 cur = 1 for level in xrange(1, l + 1): cur = cur * c if n > 0: cur = min(cur, n) foo += cur if foo > s: return s return foo def main(): while True: try: c, n, l, s = [int(i) for i in raw_input('c, n, l, s\n').strip().split()] print(trie_worst_space(c, n, l ,s)) except (EOFError, TypeError, ValueError): break if __name__ == '__main__': main()
import os, csv, smtplib, ssl message = """Subject: Testing Python Message Capabilities Hi {name}, welcome to the world of python... """ from_address = os.environ.get("EMAIL_HOST_USER") password = os.environ.get("EMAIL_HOST_PASSWORD") get_file = input("""Enter File Name Plus Extension, E.g: contacts.csv Make Sure It's A .csv File, If The File Isn't In The Same Directory As The Program, Then Be Sure To Copy The Full Path Of The File With Extension E.g: C:/Users/james/Documents/New/contacts.csv : """) context = ssl.create_default_context() with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server: server.login(from_address, password) with open(get_file) as file: reader = csv.reader(file) next(reader) # Skip header row for name, email in reader: try: server.sendmail( from_address, email, message.format(name=name), ) print(f"Message Sent To {name}") except Exception: print() print(f"Message Was Not Sent To {name}, Please Confirm Email Address Is Correct") print() print() print("Messages Have Been Sent...") # import csv # with open("users.csv") as file: # reader = csv.reader(file) # next(reader) # Skip header row # for name, email in reader: # print(f"Sending message to {name} with email address: {email}")
def shortest_formula(n): characters = ("0","1","2","3","4","5","6","7","8","9","+","*","**",")","(") i = 1 formulas = [""] while True: formulas = add_perms(formulas, characters) for f in formulas: try: if eval(f) == n: return f, i except: pass i+=1 def permutations(length, characters): if length <= 0: return [""] old_result = permutations(length-1, characters) new_result = [] for i in range(len(characters)): for string in old_result: new_result += [string + characters[i]] return new_result def add_perms(permutations, characters): new_permutations = [] for c in characters: for p in permutations: new_permutations += [p + c] return new_permutations # a1 = shortest_formula(125**3) # print("number {0} | shortest formula {1} | length {2}".format(125**3, a1[0], a1[1])) # a1 = shortest_formula(2**30) # print("number {0} | shortest formula {1} | length {2}".format(2**30, a1[0], a1[1])) # a1 = shortest_formula(2**15+1) # print("number {0} | shortest formula {1} | length {2}".format(2**15+1, a1[0], a1[1])) # a1 = shortest_formula((50*2)**10) # print("number {0} | shortest formula {1} | length {2}".format((50*2)**10, a1[0], a1[1])) # a1 = shortest_formula((2**8)*(2**8-1)) # print("number {0} | shortest formula {1} | length {2}".format((2**8)*(2**8-1), a1[0], a1[1]))
#!/usr/bin/python # encoding: utf-8 # -*- coding: utf8 -*- """ Created by PyCharm. File Name: LinuxBashShellScriptForOps:decodingNonASCII.py Version: 0.0.1 Author: Guodong Author Email: dgdenterprise@gmail.com URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps Download URL: https://github.com/DingGuodong/LinuxBashShellScriptForOps/tarball/master Create Date: 2017/11/28 Create Time: 15:13 Description: try decoding some string(type: str) with right encoding Long Description: Deep understanding of Python2 encoding: py2.str("xxx") = py2.str("xxx") + py2.bytes(b"") + py2.bytes("\xxx") py2.unicode(u"") = py2.unicode(u"") py3.str("xxx") = py2.str("xxx") + py2.unicode(u"") py3.bytes(b"") = py2.bytes(b"") + py2.bytes("\xxx") References: Prerequisites: [] Development Status: 3 - Alpha, 5 - Production/Stable Environment: Console Intended Audience: System Administrators, Developers, End Users/Desktop License: Freeware, Freely Distributable Natural Language: English, Chinese (Simplified) Operating System: POSIX :: Linux, Microsoft :: Windows Programming Language: Python :: 2.6 Programming Language: Python :: 2.7 Topic: Utilities """ import sys def decoding(text): import locale encoding = locale.getpreferredencoding() if isinstance(text, unicode): return text elif isinstance(text, str): try: return text.decode(encoding) except UnicodeDecodeError: return text.decode("utf-8") else: return text def decoding_deprecated(text): import sys import codecs import locale if isinstance(text, unicode): return text elif isinstance(text, (basestring, str)): pass else: return text # do not need decode, return original object if type is not instance of string type # raise RuntimeError("expected type is str, but got {type} type".format(type=type(text))) mswindows = (sys.platform == "win32") try: encoding = locale.getdefaultlocale()[1] or ('ascii' if not mswindows else 'gbk') codecs.lookup(encoding) # codecs.lookup('cp936').name == 'gbk' except Exception as _: del _ encoding = 'ascii' if not mswindows else 'gbk' # 'gbk' is Windows default encoding in Chinese language 'zh-CN' msg = text if mswindows: try: msg = text.decode(encoding) return msg except (UnicodeDecodeError, UnicodeEncodeError): pass return msg if __name__ == '__main__': # The boolean values of all these expressions are True isinstance('\xd6\xd0\xb9\xfa\xba\xba\xd7\xd6'.decode('gbk'), unicode) isinstance('\xe4\xb8\xad\xe5\x9b\xbd\xe6\xb1\x89\xe5\xad\x97'.decode('utf8'), unicode) isinstance('中国汉字'.decode('utf8'), unicode) # only works in some case, such as declare 'utf8' at top isinstance(u'中国汉字', unicode) isinstance(u'中国汉字'.encode('gbk'), str) isinstance(u'中国汉字'.encode('gbk'), basestring) # This function(sys._getframe()) should be used for internal and specialized purposes only. print sys._getframe().f_lineno, decoding(u"中国汉字") # print line no. to make read result easy print sys._getframe().f_lineno, decoding("中国汉字".decode('utf8').encode('gbk')) print sys._getframe().f_lineno, decoding("中国汉字") print sys._getframe().f_lineno, decoding(u"中国汉字") print sys._getframe().f_lineno, decoding('\xd6\xd0\xb9\xfa\xba\xba\xd7\xd6') print sys._getframe().f_lineno, decoding('\xe4\xb8\xad\xe5\x9b\xbd\xe6\xb1\x89\xe5\xad\x97') print sys._getframe().f_lineno, len('\xd6\xd0\xb9\xfa\xba\xba\xd7\xd6') % 2 == 0 # gbk print len('\xe4\xb8\xad\xe5\x9b\xbd\xe6\xb1\x89\xe5\xad\x97') % 3 == 0 # utf-8 with open("gbk.txt", 'w+') as fp: # encoding with default locale fp.write(u'中国汉字'.encode('gbk')) fp.write('中国汉字'.decode("utf-8").encode("gbk")) with open("utf8.txt", 'w+') as fp: # encoding with utf-8 fp.write(u'中国汉字'.encode("utf-8")) fp.write('中国汉字') with open("bytes.txt", 'w+') as fp: # encoding with utf-8 fp.write(b'\xe4\xb8\xad\xe5\x9b\xbd\xe6\xb1\x89\xe5\xad\x97') fp.write('\xe4\xb8\xad\xe5\x9b\xbd\xe6\xb1\x89\xe5\xad\x97')
''' Дан массив целых (в том числе отрицательных) чисел. Нужно на языке Python написать функцию, выдающую минимальное произведение, которое можно составить из двух чисел этого массива. ''' from random import randint from sys import maxsize def minMult(l): min_item = max_item = l[0] min_mult = maxsize for item in l[1:]: for i in [min_item, max_item]: temp_mult = i * item # min_mult = min(min_mult, temp_mult) if min_mult > temp_mult: min_mult = temp_mult # min_item = min(min_item, item) # max_item = max(max_item, item) if min_item > item: min_item = item if max_item < item: max_item = item return min_mult L = [randint(-100, 100) for i in range(30)] print (minMult(L)) ''' В системе авторизации есть ограничение: логин должен состоять из латинских букв, цифр, точки и минуса, начинаться с буквы и заканчиваться только буквой или цифрой; минимальная длина логина — один символ, максимальная — 20 символов. Напишите код на языке Python, проверяющий соответствие входной строки этому правилу. ''' import re def lognameValidation(login): result = re.match(r'^([a-z]{1}|[a-z]{1}[\w.-]{0,18}\w{1})$', login) return '{} login name'.format('Incorrect' if result == None else 'Correct') print(lognameValidation('s')) print(lognameValidation('super-puper.druper')) print(lognameValidation('super-puper.druper2'), end='\n\n') print(lognameValidation('super-puper$druper2')) print(lognameValidation('super-megapuper.druper3')) print(lognameValidation('-megapuper.druper4')) print(lognameValidation('megapuper.druper4-')) print(lognameValidation(''))
#coding=gbk class List(list): def __init__(self): 'ظԶַʵ' def find(self,word): l=len(self) ll=hash(word) fir=0 end=l-1 if fir>end: # self.insert(0,word) return False elif fir<end: #not empty, need to compare while fir<=end: mid=(fir+end)/2 if hash(self[fir])>ll: self.insert(fir,word) return False if mid == l-1: if hash(self[mid])>ll: self.insert(mid,word) return False elif hash(self[mid])<ll: self.insert(mid+1,word) return False else: if self[mid]==word: return True else: self.insert(mid+1,word) return False if hash(self[mid])>ll: end=mid-1 elif hash(self[mid])<ll: fir=mid+1 else: if word == self[mid]: return True break else: #hashgth equals but word is different fir=mid end=mid while fir>=0 and hash(self[fir])==ll: if self[fir]==word: return True break fir-=1 while end<l and hash(self[end])==ll: if self[end]==word: return True break end+=1 self.insert(mid+1,word) return False if hash(self[fir])>ll: self.insert(fir,word) return False else: #self mid equal hashgth of word if self[fir]==word: return True elif hash(self[fir])>ll: self.insert(fir,word) return False else: self.insert(fir+1,word) return False if __name__=='__main__': l=List() print l.find('1') print l.find('11') print l.find('2') print l.find('32123') print l.find('21234') print l.find('23') print l.find('231') while True: data=raw_input('...') print l.find(data) print l if(data=='111'): print l for i in l: print hash(i),i if(data=='000'): break
class Laboratorio(): def __init__(self, producto): self.producto = producto class Producto(): def __init__(self, nombre, porcentaje): self.nombre = nombre self.porcentaje = porcentaje def get_nombre(self): return self.nombre def get_porcentaje(self): return self.porcentaje class Medicamento(Producto): def __init__(self, nombre, porcentaje, composicion, precio): super().__init__(nombre, porcentaje) self.composicion = composicion self.precio = precio def get_composicion(self): return self.composicion def get_precio(self): return self.precio prod1 = Medicamento('paracetamol', 0.2, 'analgesico', 10.0) print(prod1.get_nombre(), prod1.get_precio(), prod1.get_porcentaje(), prod1.get_composicion()) #Funciona :) yuhuu!
import time for i in range(0,101,2): time.sleep(0.1) print(f'{"-"*i:<100}{i:>6.2f}% ',end="\r") """ 单行输出 end="\r" 或者 print(f'\r{"-"*i:<100}{i:>6.2f}% ',end="") 格式化字符串的用法: f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去 如:f' 字符串{变量:[填充符号| <>^左右中对齐 | .数字f 保留几位小数 | 数字d 保留几位整数不够填充符号] } ' """
""" The standard 52-card pack can be stripped to make a deck of: - 32 cards (A, K, Q, J, 10, 9, 8, 7 of each suit), - 28 cards (7s omitted), or - 24 cards (7s and 8s omitted). TODO: In some games, a joker is added. The highest trump is the jack of the trump suit, called the "right bower." The second-highest trump is the jack of the other suit of the same color called the "left bower." (Example: If diamonds are trumps, the right bower is J♦ and left bower is J♥.) The remaining trumps, and also the plain suits, rank as follows: A (high), K, Q, J, 10, 9, 8, 7. TODO: If a joker has been added to the pack, it acts as the highest trump. """ import itertools import random from euchre.card import Card from euchre.suit import Suit from euchre.rank import Rank r = Rank() suit = Suit() class IllegalArgumentError(ValueError): pass class Deck: def __init__(self, low_rank=9): self.low_low_rank = 7 self.high_low_rank = 9 low_rank = int(low_rank) if not self.low_low_rank <= low_rank <= self.high_low_rank: raise IllegalArgumentError("Low rank of {} not permitted, must be between {} and {}" .format(low_rank, self.low_low_rank, self.high_low_rank)) self.suits = list(suit.names.keys()) # apparently there are variations that play with 8's or 7's as the low card # # low_rank will be used to implement this self.ranks = ['A', 'K', 'Q', 'J'] + [str(x) for x in list(range(10, low_rank-1, -1))] self.non_bowers = [x for x in self.ranks if x != "J"] self.cards = [Card(**dict(zip(['card_rank', 'card_suit'], x))) for x in itertools.product(self.ranks, self.suits)] random.shuffle(self.cards) def get_card_ranks_by_trump_and_led(self, trump, led_card): """ :param trump: [S|H|D|C] :param led_card: Card :return: list of card ranks for the hand """ led_suit = led_card.suit lst_extra = [] if trump is not None: left_bower = Card(card_rank="J", card_suit=suit.d_bower_suits[trump]) right_bower = Card(card_rank="J", card_suit=trump) lst_out = [right_bower, left_bower] + \ [Card(**dict(zip(['card_rank', 'card_suit'], x))) for x in itertools.product(self.non_bowers, trump)] if not (led_suit == trump or led_card == left_bower): lst_extra = self.get_non_trump_led_suit_ranks(trump, led_suit) else: lst_out = list(itertools.product(self.ranks, led_suit)) lst_out += lst_extra return lst_out def get_non_trump_led_suit_ranks(self, trump, led_suit): """ :param trump: str - [C|S|D|H] :param led_suit: str - [C|S|D|H] :return: """ if led_suit in [trump, suit.d_bower_suits[trump]]: lst_extra = [Card(**dict(zip(['card_rank', 'card_suit'], x))) for x in itertools.product(self.non_bowers, led_suit)] else: lst_extra = [Card(**dict(zip(['card_rank', 'card_suit'], x))) for x in itertools.product(self.ranks, led_suit)] return lst_extra
# 1) Design model (3wr) # 2) Construct loss and optimizer # 3) Training loop # - forward pass: ocmpute prediction # - backward pass: gradients # - update weights import torch import torch.nn as nn # f = w * x # f = 2 * x X = torch.tensor([1,2,3,4], dtype=torch.float32) Y = torch.tensor([2,4,6,8], dtype=torch.float32) w = torch.tensor(0.0, dtype=torch.float32, requires_grad=True) # model prediction def forward(x): return w * x # loss = MSE def loss(y, y_pred): return ((y_pred - y)**2).mean() print(f'Prediction before training: f(5) = {forward(5):.3f}') # Training learning_rate = 0.01 n_iters = 10000 for epoch in range(n_iters): # prediction = forward pass y_pred = forward(X) # loss l = loss(Y, y_pred) # gradients = backward pass dl/dw l.backward() # update weights with torch.no_grad(): w -= learning_rate * w.grad # zero gradients w.grad.zero_() if epoch % 10 == 0: print(f'epoch {epoch+1}: w = {w:.3f}, loss = {l:.8f}') print(f'Prediction after training: f(5) = {forward(5):.3f}')
#NIM:71200539 #Nama:Deon Bintang Sanjaya #Universitas Kristen Duta Wacana """ Bu Rini ingin memisahkan jumlah murid-muridnya berdasarkan gender, buatlah program tersebut dengan output berupa dictionary input:jumlah laki-laki & perempuan laki2=10 perempuan=15 proses:integer tadi digabung dengan string tuple diconvert menjadi dictionary output:dictionary berisi gender dan jumlah muridnya """ x=int(input("Masukkan jumlah murid laki-laki:")) y=int(input("Masukkan jumlah murid perempuan:")) tuples=(("Laki-laki",x),("Perempuan",y)) print(dict(tuples))
#!/bin/python3 import os # Complete the repeatedString function below. def repeatedString(s, n): len_str = len(s) cnt_a = s.count('a') * (n // len_str) cnt_a += s[slice(n % len_str)].count('a') return(cnt_a) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() n = int(input()) result = repeatedString(s, n) fptr.write(str(result) + '\n') fptr.close()
#!/usr/bin/python3 # coding: utf-8 # Exercício 1: # * Criar um programa para converter um valor em segundos em horas, minutos e segundos # Requisitos Exercício 1: # * O programa deve pedir os segundos ao utilizador e guardar em uma variável # * De seguida o programa deverá calcular o total de horas, minutos e segundos e imprimir o resultado na consola # Exemplo Exercício 1: # - 39050 segundos é igual a 10:50:50 import time hour = 3600 # 1 hour = 3600 seconds minute = 60 # 1 minute = 60 seconds seconds = (input('Introduzir os segundos: ')) print(seconds) conversion = int(seconds) / int(hour) print(conversion) conversion_1 = time.strftime("%S:%M:%H", time.gmtime(conversion)) print(conversion_1) print('- ' + seconds + ' segundos é igual a ' + conversion_1)
""" 函数 函数的目的:代码复用 函数,就是指为一段实现特定功能的代码“取”一个名字,以后即可通过该名字来执行(调用)该函数。 输入:0个或多个参数 返回:0个或多个值 定义函数的语法: def function_name(形参列表): pass [return [返回值]] """ def sum_and_avg(a, b, message="sum and average", *args, **kwargs): """ 说明文档:求和 均值函数 a: 位置参数 b: 位置参数 message="sum and average": 默认参数 *args: 可变参数,类型:tuple **kwargs: 可变关键字参数,类型:dict """ print(message) print(args, type(args), len(args)) print(kwargs, type(kwargs), len(kwargs)) c = a+b for n in args: c += n for k, v in kwargs.items(): c += v return c, c/(2+len(args)+len(kwargs)) # 多个返回值被封装成 tuple print('#'*30) # 说明文档 # help(sum_and_avg) print(sum_and_avg.__doc__) # 返回值 # res 是一个 tuple res = sum_and_avg(1, 2) # 序列解包 s, avg = sum_and_avg(1, 2) # 参数 # 位置参数 print(sum_and_avg(1, 2)) # 关键字参数 print(sum_and_avg(a=1, b=2)) print(sum_and_avg(1, b=2)) # 可变参数 *args print(sum_and_avg(1, 2, "可变参数 *args", 3, 4, 5, 6, 7)) # 可变关键字参数 **kwargs print(sum_and_avg(1, 2, "可变关键字参数 **kwargs", 3, 4, 5, 6, 7, aa=8, bb=9, cc=10, dd=11)) print(sum_and_avg(1, 2, aa=8, bb=9, cc=10, dd=11)) # 参数解包 # 把list 或 tuple 通过 * 解包后传递给形参,然后*args将对应参数收集成tuple my_args = [1, 2, "解包 可变参数 *args", 3, 4, 5, 6, 7] print(sum_and_avg(*my_args)) # 把dict通过 ** 解包后传递给形参,然后**kwargs将对应参数收集成dict my_args = (1, 2, "解包 可变关键字参数 **kwargs", 3, 4, 5, 6, 7) my_dict = {"aa": 8, "bb": 9, "cc": 10, "dd": 11} print(sum_and_avg(*my_args, **my_dict)) """ 参数传递机制 python是 值传递,即传入副本(复制品),所以在函数中对传入副本进行操作,不影响函数外的参数 对于可变对象list或dict,传入的是对象引用的副本,在函数中对传入的list或dict进行操作,会影响 可变对象本身,不影响函数外的对象引用。 如果需要让函数修改某些数据,可以把数据包装成list 或 dict等可变对象,然后将list或dict作为参数传入函数 """ """ 变量作用域 globals(): 返回全局范围内所有变量组成的变量字典 locals(): 返回当前局部范围内所有变量组成的变量字典 vars(object): 返回指定对象范围内所有变量组成的变量字典,如果不指定object,vars() 和 locals() 作用一样 一般来说,使用 locals()和 globals()获取的“变量字典”只应该被访问,不应该被修改。但实际上,都可以被修改。 对globals()的字典进行修改会改变全局变量本身 对locals()的字典进行修改不会改变局部变量本身 """ print('#'*30) name = 'haha' def test(): # global 语句声明全局变量,以便后面修改全局变量 global name print(name) name = 'hihi' test() print(name) """ 局部函数 函数将局部函数返回,且使用变量保存了返回的局部函数,则局部函数的作用域被扩大, """ print('#'*30) def foo(): name = "Charlie" def bar(): # nonlocal 声明访问当前函数所在函数内的局部变量 nonlocal name print(name) name = 'Mark' print(name) bar() foo() """ 函数的高级内容 函数可以赋值给变量,作为参数,作为函数的返回值 1. 函数赋值给变量后,可以使用变量调用函数 2. 当希望函数被调用时某些代码可以动态变化时,可以将动态变化部分封装成函数后作为参数传入。也就是函数中哪里需要变化,哪里就转化为参数 3. 将函数作为其他函数的返回值,可以实现根据参数,返回不同的参数 """ """ lambda表达式 可作为 表达式,函数参数,函数返回值。可以使程序更加简洁 如果函数名的生命周期短,可以考虑使用lambda表达式来简化局部函数的写法 lambda 表达式只是单行函数的简化版本,因此 lambda 表达式的功能比较简单 语法格式: lambda [parameter_list]:表达式 eg: lambda : 1+2+3 lambda x : x**2 lambda x,y: x*y """ print('#'*30) x = map(lambda x: x*x, range(10)) print(list(x))
sentence=raw_input() placeholder=[0]*26 for x in sentence: CODE_X=ord(x) placeholder[CODE_X-97]+=1 Max_freq=max(placeholder) Min_Freq=min([x for x in placeholder if x>0]) Max_Freq_COUNT=sum([1 for x in placeholder if x==Max_freq]) Min_Freq_COUNT=sum([1 for x in placeholder if x==Min_Freq]) if Max_freq==Min_Freq: changes_required=0 elif Max_freq==Min_Freq+1 and Max_Freq_COUNT==1: changes_required=sum([1 for x in placeholder if x==Max_freq]) else: changes_required=sum([x for x in placeholder if x==Min_Freq]) result='YES' if changes_required<=1 else 'NO' print result
""" repeatStr(6, "I") // "IIIIII" repeatStr(5, "Hello") // "HelloHelloHelloHelloHello" """ def repeat_str(repeat, string): return (string*repeat) print("Enter String") string=input() print("Enternumber of times to repeat") repeat=int(input()) print(repeat_str(repeat,string))
""" Return the number (count) of vowels in the given string. We will consider a, e, i, o, and u as vowels for this Kata. The input string will only consist of lower case letters and/or spaces. """ def getCount(inputStr): num_vowels = 0 vows=['a','e','i','o','u'] # your code here for i in inputStr: if i.lower() in vows: num_vowels=num_vowels+1 return num_vowels print("Enter the string") str=input() print(getCount(str))
# -*- coding:utf-8 -*- #ϵͳ from sys import argv script, input_file = argv #庯print_all def print_all(f): print f.read() #庯rewind seekֻǶλ0λ޷ֵ def rewind(f): f.seek(0) #庯print_a_line readlineȡļһ def print_a_line(line_count,f): print line_count,f.readline() #ļ current_file = open(input_file) print "First let's print the whole file:\n" #úprint_allҴ print_all(current_file) print "Now let's rewind,kind of like a tape." #úrewindҴ rewind(current_file) print "Let's print three lines:" # current_line = 1 #úprint_a_lineҴ print_a_line(current_line,current_file) # current_line = current_line + 1 #úprint_a_lineҴ print_a_line(current_line,current_file) # current_line = current_line + 1 #úprint_a_lineҴ print_a_line(current_line, current_file)
from argparse import ArgumentParser, FileType import json5 import os import glob import pandas as pd args = ArgumentParser('''./combine_passed_variants.py', description='This program is a simple one to combine the output files containing the variants that passed HGVS normalization into one csv file. Example usage: ./combine_passed_variants.py --config_file LOVD3_Databases.json --LOVD3_directory output_files --disease_names SCID Metabolic_Diseases --output_directory output_files''') args.add_argument( '-c', '--config_file', help="""This is the config file that was used for the LOVD3 parser. If this option is not provided, the program will look for a json file in your present working directory.""", default = None, ) args.add_argument( '-l', '--LOVD3_directory', help="""This is the name of the directory where the variants from LOVD3 parser are stored. The final output file will be stored in this directory if no output directory is stored with the option --output_directory. Default is output_files.""", default = "output_files" ) args.add_argument( '-d', '--disease_names', nargs='+', help="""This is the same list of disease names supplied into LOVD3_Variant_Parser.py. If this is not specified, the program will try to gather the information from the directory specified with --LOVD3_directory. """, default = None ) args.add_argument( '-o', '--output_directory', help="This is where your output file will be stored. If this option is not used, the directory specified in --LOVD3_directory will be used.", default = None ) args = args.parse_args() disease_names = args.disease_names json_file = args.config_file if not json_file: # If no input config file is present, look for one in the present working directory jsons_list = glob.glob("*.json") if len(jsons_list) == 1: json_file = jsons_list[0] try: if len(jsons_list) == 0: raise ValueError('No JSON file present to use as config file') if len(jsons_list) > 1: raise ValueError('More than one JSON file present and no file specified as config file. Please specify your config file with --config_file.') except ValueError as error: print(repr(error)) raise SystemExit() with open(json_file) as file: databases_list = json5.load(file) directory = args.LOVD3_directory output_directory = args.output_directory if not output_directory : # If no output directory is specified, save the output in the same directory as the input output_directory = directory if not disease_names: # If the disease names are not specified at the command line, you can find them from the subdirectories in the output directory disease_names = [] first_database = databases_list[0]["name"] subdirectories = glob.glob(directory+"/"+first_database+'/*/') # list all subdirectories in the first database directory for subdir in subdirectories: disease_names.append(subdir.rsplit('/')[-2]) columns = ['Genome Assembly', 'Chr', 'Position Start', 'Position Stop', 'Ref', 'Alt', 'Genomic Annotation', 'HGVS Normalized Genomic Annotation', 'Variant Type', 'Variant Length', 'Pathogenicity', 'Disease', 'Genetic Origin', 'Inheritance Pattern', 'Affected Genes', 'Gene Symbol', 'Compound Het Status', 'Transcript', 'Transcript Notation', 'HGVS Transcript Notation', 'Protein Accession', 'Protein Notation', 'HGVS Protein Annotation', 'Chr Accession', 'VCF Pos', 'VCF Ref', 'VCF Alt', 'Database', 'Database Accession', 'Review Status', 'Star Level', 'Submitter', 'Edited Date', 'DNA change (genomic) (hg19)', 'Effect', 'Exon','Reported', 'DB-ID', 'dbSNP ID', 'Published as', 'Variant remarks', 'Reference', 'Frequency', 'ClinVar Accession', 'Transcript Normalization Failure Message', 'Genomic Normalization Failure Message','Overall_MAF', 'Control_MAF', 'African_MAF', 'NonFinish_Euro_MAF', 'Finnish_MAF', 'Ashkenazi_MAF','Latino_MAF', 'East_Asian_MAF', 'South_Asian_MAF', 'Other_Ancestry_MAF'] merged_df = pd.DataFrame(columns = columns) for database in databases_list: database_name = database["name"] for disease_name in disease_names: base_directory = directory+"/"+database_name+"/"+disease_name files = [f for f in glob.glob(base_directory+"/*.csv")] for file in files: tmp_df = pd.read_csv(file, index_col = 0) merged_df = pd.concat([merged_df, tmp_df], sort=False).reset_index(drop=True) merged_df.to_csv(output_directory+"/LOVD3_All_Valid_HGVS_Annotations.csv")
# Rolando Josue Quijije Banchon # Software # #Tercer semestre #Tarea 13 de ejercicios de pagina web """Ejercicio 13 Elabore pseudocódigo para el caso en que se desean escribir los números del 1 al 100.""" class Tarea13: def __init__ (self): pass def Variables(self): print("_______________________________________") print("numeros hasta el 100 con While") i=1 while i <=100: print(i) i=i+1 print("_______________________________________") input("enter para salir") resultado = Tarea13() resultado.Variables()
# Rolando Josue Quijije Banchon # Software # #Tercer semestre #Tarea 6 de ejercicios de pagina web """EJEMPLO 6: Dado el sueldo de un empleado, encontrar el nuevo sueldo si obtiene un aumento del 10% si su sueldo es inferior a $600, en caso contrario no tendrá aumento.""" class Tarea6: def __init__(self): pass def Calcular(self): print("_______________________________________") SUELDO=float(input("Sueldo de empleados:")) if SUELDO < 600: NS=SUELDO + SUELDO*0.1 print() else: NS=SUELDO print() print("_______________________________________") print(NS) print("_______________________________________") input("enter para salir") tarea=Tarea6() tarea.Calcular()