text
stringlengths
37
1.41M
from __future__ import print_function import numpy from logistic_regression import LogisticRegression from hidden_layer import HiddenLayer import theano.tensor as T class MLP(object): """Multi-Layer Perceptron Class A multilayer perceptron is a feedforward artificial neural network model that has one layer or more of hidden units and nonlinear activations. Intermediate layers usually have as activation function tanh or the sigmoid function (defined here by a ``HiddenLayer`` class) while the top layer is a softmax layer (defined here by a ``LogisticRegression`` class). """ def __init__(self, rng, input, n_in, n_hidden, n_out): """Initialize the parameters for the multilayer perceptron :type rng: numpy.random.RandomState :param rng: a random number generator used to initialize weights :type input: theano.tensor.TensorType :param input: symbolic variable that describes the input of the architecture (one minibatch) :type n_in: int :param n_in: number of input units, the dimension of the space in which the datapoints lie :type n_hidden: int :param n_hidden: number of hidden units :type n_out: int :param n_out: number of output units, the dimension of the space in which the labels lie """ # Since we are dealing with a one hidden layer MLP, this will translate # into a HiddenLayer with a tanh activation function connected to the # LogisticRegression layer; the activation function can be replaced by # sigmoid or any other nonlinear function self.hiddenLayer = HiddenLayer( rng=rng, input=input, n_in=n_in, n_out=n_hidden, activation=T.tanh ) # The logistic regression layer gets as input the hidden units # of the hidden layer self.logRegressionLayer = LogisticRegression( input=self.hiddenLayer.output, n_in=n_hidden, n_out=n_out ) # Enforce L1 norm to be small self.L1 = ( abs(self.hiddenLayer.W).sum() + abs(self.logRegressionLayer.W).sum() ) # Enforce square of L2 norm to be small self.L2_sqr = ( (self.hiddenLayer.W ** 2).sum() + (self.logRegressionLayer.W ** 2).sum() ) # negative log likelihood of MLP is negative log likelihood of model # which is NLL of LR layer self.negative_log_likelihood = ( self.logRegressionLayer.negative_log_likelihood ) self.errors = self.logRegressionLayer.errors self.params = self.hiddenLayer.params + self.logRegressionLayer.params self.input = input
#Rajouter une situation où certains nodes ne peuvent plus bouger (drône en panne) #-> définir une nouvelle liste où l'on met les nodes statiques #-> ou un paramètre booléen dans la class node pour indiquer si le noeud peut bouger ou non. #Source for mathematique: https://fr.wikibooks.org/wiki/Math%C3%A9matiques_avec_Python_et_Ruby/Points_en_Python from math import * #Source for drawing: https://matplotlib.org/ #https://stackoverflow.com/questions/21519203/plotting-a-list-of-x-y-coordinates-in-python-matplotlib import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches #obstacle class, define a rectangular area or polygon (python polygon intersection with line) #http://geoexamples.blogspot.com/2014/08/shortest-distance-to-geometry-in.html #Install libaries : $ sudo pip3 install Shapely # $ sudo pip3 install descartes from shapely.geometry import Polygon, Point, LinearRing, LineString from descartes import PolygonPatch class Node:#Definition of a class Node """This class defines a node described by: - its coordinate on X axis - its coordinate on Y axis - its node ID""" def __init__(self, x, y, id): self.coord = Point(x,y) # class Point from shapely.geometry self.id=id self.s=0 # variable to know for how long the node is stable self.mobil=True # variable to know if the node is mobile or not (in case of broken node) def display(self):#Display the coordinates between () separed by ; after converted them in string return 'Node '+str(self.id)+'='+str(self.coord.wkt) def middle(self, p): return Node((self.coord.x+p.coord.x)/2,(self.coord.y+p.coord.y)/2) def vector(self, p): return Vector(p.coord.x-self.coord.x , p.coord.y-self.coord.y) def distance(self, p): return self.vector(p).norm() def translation(self, p): return Node(self.coord.x+p.x, self.coord.y+p.y, self.id) class Vector:#Definition of a class Vector """This class defines a vector described by: - its coordinate on X axis - its coordinate on Y axis""" def __init__(self, x, y): self.x=x self.y=y def display(self): return '('+str(self.x)+';'+str(self.y)+')' def norm(self): return hypot(self.x, self.y) """.hypot(x, y) returns the Euclidean norm, sqrt(x*x + y*y). This is the length of the vector from the origin to point (x, y).""" def __add__(self, v):#Method to add 2 vectors return Vector(self.x+v.x, self.y+v.y) def VF_sensors(i, j):#Function to calculte the VF exert on a node by a neighboor node """This function takes 2 inputs: - i: the node on which the force is exerted - j: the neighboor node which exerted the force It returns a vector Fij_temp""" Fij_temp = Vector(0,0)#temporary Vector initialized to zero vector # d_ij = i.distance(j) d_ij = i.coord.distance(j.coord) if Cr >= d_ij and d_ij>d_th:#In this case, Si and Sj are too far and an attractive force is exerted by Sj on Si #print("Node {} is too far from node {}, Cr({}) >= d_ij({}) and d_ij > d_th ({}): Attractive force".format(i.id, j.id, Cr, d_ij, d_th)) Fij_temp.x = (Ka * (d_ij - d_th)) * ((j.coord.x - i.coord.x) / d_ij) Fij_temp.y = (Ka * (d_ij - d_th)) * ((j.coord.y - i.coord.y) / d_ij) elif d_ij < d_th:#In this case, Si and Sj are too close and a repulsive force is exerted by Sj on Si #print("Node {} is too close from node {}, d_ij({}) < d_th ({}): Repulsive force".format(i.id, j.id, d_ij, d_th)) Fij_temp.x = (Kr * (d_th - d_ij)) * ((i.coord.x - j.coord.x) / d_ij); Fij_temp.y = (Kr * (d_th - d_ij)) * ((i.coord.y - j.coord.y) / d_ij); #If none of the previous conditions are met, the force vector is still null because no force is exerted on node i. return Fij_temp def VF_obstacles(i ,j): """This function takes 2 inputs: - i: the node on which the force is exerted - j: the obstacle (a polygon) which exerted the force It returns a vector Fij_temp""" Fiobs_temp = Vector(0,0) d_iobs = i.coord.distance(j) # Distance between point Si (i.coord) and Obsj (a polygon) if d_iobs < d_thobs and d_iobs>0:#In this case, Si is too close from the obstable and a repulsive force is exerted by the obstable. # print("Obstacle detected, d_iobs<d_thobs") pol_ext = LinearRing(j.exterior.coords) d = pol_ext.project(i.coord) closest_point = pol_ext.interpolate(d) Fiobs_temp.x = (Kr_obs * (d_thobs - d_iobs)) * ((i.coord.x - closest_point.x) / d_iobs); Fiobs_temp.y = (Kr_obs * (d_thobs - d_iobs)) * ((i.coord.y - closest_point.y) / d_iobs); #else the obstacle is too far, so no force is exerted on node i and Fiobs_temps = vector zero return Fiobs_temp def Node_translation(i, F, list_o): """This function takes 3 inputs: - i: the node to move - F: the force that moves the node - list_o: the obstacle list It returns a new node that is the result of the input node translation""" temp = i.translation(F) dist_init = i.coord.distance(temp.coord) g = F.x * 1000 h = F.y * 1000 F_temp=Vector(g,h) projection = i.translation(F_temp) line = LineString([(i.coord.x, i.coord.y),(projection.coord.x, projection.coord.y)]) dist_min = None closest_obs = None for elt in list_o: difference = line.difference(elt) if difference.geom_type == 'MultiLineString': # In this case we meet an obstacle on our way dist = list(difference.geoms)[0].length if dist_min is None or dist_min > dist: dist_min = dist closest_obs = elt if dist_min != None and dist_min < dist_init: # If dist_min is different from None, that means we meet and osbtacle and we need to reduce the translation. print("CHANGEMENT CAR distance initale {} > dist_min {}".format(dist_init, dist_min)) ratio = (dist_min * 0.9)/dist_init F.x = F.x * ratio F.y = F.y * ratio temp = i.translation(F) else: print("PAS DE CHANGEMENT CAR distance initale {} < dist_min {}".format(dist_init, dist_min)) return temp #Parameters definition global Cr #Communication range global Sr #Sensing range global L_th # Distance threshold where a node stop to move if its movement is less than this one global S_th #Time duration after what we consider a node reach its optimal position (use number of iteration, no time units) global d_th #Distance threshold (= sqrt(3)*Sr) global Ka #Attraction coefficient global Kr #Repulsion coefficient global Kr_obs #Repulsion coefficient for obstacle global d_thobs #Distance threshold (= sqrt(3)*Sr / 2) Cr=10 Sr=5 S_th=10 L_th=0.001 Ka=0.001 Kr=0.2 d_th = sqrt(3)*Sr Kr_obs = 0.8 d_thobs = d_th / 2 Max_iteration=300 iteration=0 xfield=50 yfield=50 #System definition (nodes, obstacles) n0=Node(-1,3,0) n1=Node(5,1,1) n2=Node(10,4,2) n3=Node(-4,-5,3) n4=Node(7,7,4) n5=Node(3,0,5) n6=Node(0,-4,6) n7=Node(8,-4,7) n8=Node(2,6,8) n9=Node(6,-2,9) n10=Node(1,8,10) n11=Node(2,12,11) n12=Node(-5,-2,12) n13=Node(-7,-6.5,13) #n10.mobil=False poly0 = Polygon([(1,4),(-10,0),(0,16)]) poly1 = Polygon([(8,1),(7,14),(20,3)]) poly2 = Polygon([(3,9),(25,12),(5,10)]) poly3 = Polygon([(-7,-4),(-5,-7),(-7,-8)]) list_node=[n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13] list_poly=[poly0, poly1, poly2, poly3] #Plot the initial positions on the graph and legend #xx, yy = np.meshgrid(np.arange(-25, 26), np.arange(-25,26), sparse=True) fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim(-(xfield/2), xfield/2) ax.set_ylim(-(yfield/2), yfield/2) for elt in list_node:#elt takes the value of each elements in list_node plt.scatter(elt.coord.x, elt.coord.y, color="#7f7f7f") #Plot obstacles (polygons) for elt in list_poly: patch2b = PolygonPatch(elt, fc='#ff7f7f', ec='#ff3232', alpha=1., zorder=2) ax.add_patch(patch2b) #Legend display label = "Cr={} | Sr={} | S_th={} | L_th={}\nKr={} | Ka={} | Kr_obs={}".format(Cr, Sr, S_th, L_th, Kr, Ka, Kr_obs) legend = mpatches.Patch(color='none', label=label) plt.legend(handles=[legend]) #Main loop while iteration<Max_iteration: print("Iteration n°", iteration) test=0#Testing variable, reset at each iteration for index, i in enumerate(list_node):#For each node in the system SumF_node=Vector(0,0)#Reset the force sums at each iteration SumF_obs=Vector(0,0) if i.s < S_th and i.mobil==True: # If the node isn't stable for a certain amount of time and still mobile, use VF on it. for jndex, j in enumerate(list_node):#For each node Sj in the system, calculation of the force it exertes on Si if index!=jndex:#To avoid to calculate the force exerted by Si on itself. F_node=VF_sensors(i, j) SumF_node=SumF_node.__add__(F_node) for obs in list_poly:#For each obstacle Oj in the system, calculation of the force it exertes on Si F_obs=VF_obstacles(i, obs) SumF_obs=SumF_obs.__add__(F_obs) F_tot=SumF_node.__add__(SumF_obs)#Total of the forces exerted on Si (SumF_obs + SumF_node) if i.distance(i.translation(F_tot)) < L_th:#Stable ? If the node should move more than a distance treshold: YES print("Node {} doesn't move, {}<L_th({}), since i.s={}.".format(i.id, i.distance(i.translation(F_tot)), L_th, i.s)) i.s+=1#Increment the stability timer else:#Stable ? NO, so translation print("Node {} moves, {}>L_th({}).".format(i.id, i.distance(i.translation(F_tot)), L_th)) i.s=0#Reset stability timer list_node[index]=Node_translation(list_node[index], F_tot, list_poly)#Move the node to its new position elif i.s >= S_th: # The node is stable for more than the time threshold, we don't use VF on it. It already reach its optimal position. print("Node {} is stable for {} iterations.".format(i.id, i.s)) test+=1 # Increment the testing variable else: print("Node {} is unable to move.".format(i.id)) test+=1 # Still incrementing the testing variable #Plot every points on a graph for elt in list_node:#elt takes the value of each elements in list_node plt.scatter(elt.coord.x, elt.coord.y, color="#cbcbcb") print("test =",test,"index =",index) #Test if test==index+1:#If all nodes are stable, the system is optimize so leave the loop break iteration+=1 #Plot the final positions for elt in list_node:#elt takes the value of each elements in list_node if elt.mobil == False: # use different color if node is broken circ = plt.Circle((elt.coord.x, elt.coord.y), radius=Sr, edgecolor='#FFA500', facecolor="none")#Draw a circle around the point, show the sensing range plt.scatter(elt.coord.x, elt.coord.y, color="#FFA500") ax.add_patch(circ) else: circ = plt.Circle((elt.coord.x, elt.coord.y), radius=Sr, edgecolor='b', facecolor="none")#Draw a circle around the point, show the sensing range plt.scatter(elt.coord.x, elt.coord.y, color="b") ax.add_patch(circ) plt.show()
#coding=utf-8 #遍历 字符串 ,列表,元组,字典等数据结构 #字符串遍历 mystr = "welcome to young world" for char in mystr : print char,' ', print '' #列表遍历 mylist = [1, 2, 3, 4, 5] for num in mylist : print num , print type(num) print '' #元组遍历 myturple = (1, 2, 3, 4, 5) for num in myturple : print num, print '' #字典遍历----value(值) mydict = {'name':'young','id':'100054','sex':'m'} for value in mydict.values() : print value #字典遍历---key(键) for key in mydict.keys() : print key #字典遍历---item项(元素) for item in mydict.items() : print item #字典遍历 key-value (键值对) for key,value in mydict.items() : print 'key = %s ,value = %s'%(key, value) #实现用带下标索引遍历1 i = 0 for char in mylist : print 'i = %d char = %d'%(i, char) i += 1 #实现下标索引遍历 2 for j, chr in enumerate(mylist) : print j, chr
#coding=utf-8 # # #创建对象后,python解释器默认调用__init__()方法; #当删除一个对象时,python解释器也会默认调用一个方法,这个方法为__del__()方法 import time print 'test1 析构' class animals(object) : #初始化方法,创建对象后会自动被调用 def __init__(self, name) : print '__init__方法被调用' self.__name = name #析构方法,当对象被删除时候,会自动被调用 def __del__(self) : print '__del__方法被调用' print '%s对象被删除……'%self.__name def print_test(self) : print 'test code' dog = animals('小花狗') #当有1个变量保存了对象的引用时,此对象的引用计数就会加1 #当使用del删除变量指向的对象时,如果对象的引用计数不是1, #比如3,那么此时只会让这个引用计数减1,即变为2,当再次调用del时, #变为1,如果再调用1次del,此时会真的把对象进行删除 # #所以得一个一个的删引用在del dog1 = dog #删除对象引用 del dog1 #删除对象 del dog print '还有1s后结束' time.sleep(1) print '='*40 #私有的属性,不能通过对象直接访问,但是可以通过方法访问 #私有的方法,不能通过对象直接访问 #私有的属性、方法,不会被子类继承,也不能被访问 #一般情况下,私有的属性、方法都是不对外公布的,往往用来做内部的事情,起到安全的作用 print 'test2 单继承 ' class Animal(object): def __init__(self, name='动物', color='白色'): #私有变量 self.__name = name self.color = color def __test(self): print(self.__name) print(self.color) def test(self): print(self.__name) print(self.color) class Dog(Animal): def dogTest1(self): #print(self.__name) #不能访问到父类的私有属性 print(self.color) def dogTest2(self): #self.__test() #不能访问父类中的私有方法 self.test() A = Animal() #print(A.__name) #程序出现异常,不能访问私有属性 print(A.color) #A.__test() #程序出现异常,不能访问私有方法 A.test() print("------分割线-----") D = Dog(name = "小花狗", color = "黄色") D.dogTest1() D.dogTest2() print '='*40 # python 中是可以多继承的 父类中的方法属性,子类都可以继承 class base(object): def test(self): print('----base test----') class A(base): def test(self): print('----A test----') # 定义一个父类 class B(base): def test(self): print('----B test----') # 定义一个子类,继承自A、B class C(A, B): # 会先调用 A 然后是 B 如果是class C(B, A):就先调用B pass obj_C = C() obj_C.test() #python 中有一个mro算法 先不考虑这个问题 print(C.__mro__) #可以查看C类的对象搜索方法时的先后顺序 print '='*40 #这里有一个重点,面试的时候肯定会问,就是: # 面向对象有什么特点: 封装,继承,多态 # 封装: 比如类 # 继承: 减少代码的龙于 # 多态: 定义时候知道知道传过来的同一种类型,但是执行可能是子类的对象 print 'test3 多态' class F1(object): def show(self): print 'F1.show' class S1(F1): def show(self): print 'S1.show' class S2(F1): def show(self): print 'S2.show' # 这里体现了多态性 这函数调用什么方法看传入的什么类 def Func(obj): print obj.show() s1_obj = S1() Func(s1_obj) s2_obj = S2() Func(s2_obj)
#!/usr/bin/python # -*- coding: utf-8 -*- """ Question: You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. """ """ 当1<=n<=3时,先手必胜 当n=4时,先手比输 当n=5时,先取1个,让对方处于先手4个情况。先手必胜 当n=6时,先取2个,让对方处于先手4个情况。先手必胜 当n=7时,先取3个,让对方处于先手4个情况。先手必胜 当n=8时,无论先取几个,问题都将简化为5<=n<=7时,对手先手的情况。先手必输 当n=9时,先取1个,让对方处于先手8个情况。先手必胜 ...... 可知,n能被4整除时,先手必输;否则必胜 """ class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ return n%4>0
# Ezequiel Zapata PSID: 001863257 # part 1 a program that reads words in a list and outputs the word and its frequency. Caps sensitive. words = input().split() for word in words: count = 0 for w in words: if w == word: count += 1 print(word, count)
# Ezequiel Zapata PSID: 001863257 # We will take input from the user and return date if input is in correct format, else it will ignore string. def extract_date(date): correct_date = 0 n_date = "" if date.find(",") != -1: month_day, year = date.split(',') if month_day.find(" ") != -1: month, day = month_day.split(" ") correct_date = 1 day = day.strip() month = month.strip() year = year.strip() if month == "January": n_date = "1" + "/" elif month == "February": n_date = "2" + "/" elif month == "March": n_date = "3" + "/" elif month == "April": n_date = "4" + "/" elif month == "May": n_date = "5" + "/" elif month == "June": n_date = "6" + "/" elif month == "July": n_date = "7" + "/" elif month == "August": n_date = "8" + "/" elif month == "September": n_date = "9" + "/" elif month == "October": n_date = "10" + "/" elif month == "November": n_date = "11" + "/" elif month == "December": n_date = "12" + "/" else: correct_date = 0 n_date += day + "/" n_date += year if correct_date == 1: return n_date else: return "" # opening, reading, and closing the inputDates.txt file. file = open('inputDates.txt', 'r') file_dates = file.readlines() file.close() for i in range(len(file_dates) - 1): file_dates[i] = file_dates[i][:-1] # Opening the file for writing the parsed dates file = open('parsedDates.txt', 'w') for i in file_dates: if i == "-1": break else: new_date = extract_date(i) if new_date != "": file.write(new_date + "\n") file.close() # Opening the parsedDates.txt file to see what is written in it. file = open('parsedDates.txt', 'r') file_parsed_dates = file.readlines() file.close() # Main program that inputs the inputDates.txt file into the program, which then writes it into the parsedDates.txt file # we created. print("Input file content:\n") for i in file_dates: print(i) print("\nOutput file content:\n") for i in file_parsed_dates: print(i)
# Global variable num_calls = 0 # TODO: Write the partitioning algorithm - pick the middle element as the # pivot, compare the values using two index variables l and h (low and high), # initialized to the left and right sides of the current elements being sorted, # and determine if a swap is necessary def partition(user_ids, l, h): i = (l - 1) pivot = user_ids[h] for j in range(l, h): if user_ids[j] <= pivot: i = i + 1 user_ids[i], user_ids[j] = user_ids[j], user_ids[i] user_ids[i + 1], user_ids[h] = user_ids[h], user_ids[i + 1] return (i + 1) # TODO: Write the quicksort algorithm that recursively sorts the low and # high partitions. Add 1 to num_calls each time quisksort() is called def quickSort(user_ids, l, h): global num_calls num_calls = num_calls + 1 if l < h: p = partition(lst, l, h) quickSort(lst, l, p -1) num_calls = num_calls + 1 quickSort(lst, p + 1, h) lst = [] while True: inp = input() if inp == "-1": break else: lst.append(inp) size = len(lst) quickSort(lst, 0, size - 1) print(num_calls) for i in range(size): print(lst[i])
# Online Python compiler to write code and run Python online a = input("Enter a number ") print("1",int(a)*1) print("2",int(a)*2) print("3",int(a)*3) print("4",int(a)*4) print("5",int(a)*5) print("6",int(a)*6) print("7",int(a)*7) print("8",int(a)*8) print("9",int(a)*9) print("10",int(a)*10)
# Defining and Visualizing Simple Networks (Python) # prepare for Python version 3x features and functions from __future__ import division, print_function # load package into the workspace for this program import networkx as nx import matplotlib.pyplot as plt # 2D plotting import numpy as np # ------------------------- # star (undirected network) # ------------------------- # define graph object for undirected star network # adding one link at a time for pairs of nodes star = nx.Graph() star.add_edge('Amy', 'Bob') star.add_edge('Amy', 'Dee') star.add_edge('Amy', 'Joe') star.add_edge('Amy', 'Lea') star.add_edge('Amy', 'Max') star.add_edge('Amy', 'Tia') # examine the degree of each node print(nx.degree(star)) # plot the star network and degree distribution fig = plt.figure() nx.draw_networkx(star, node_size = 2000, node_color = 'yellow') plt.show() fig = plt.figure() plt.hist(nx.degree(star).values()) plt.axis([0, 8, 0, 8]) plt.xlabel('Node Degree') plt.ylabel('Frequency') plt.show() # create an adjacency matrix object for the star network # use nodelist argument to order the rows and columns star_mat = nx.adjacency_matrix(star,\ nodelist = ['Amy', 'Bob', 'Dee', 'Joe', 'Lea', 'Max', 'Tia']) print(star_mat) # undirected networks are symmetric # determine the total number of links for the star network (n-1) print(star_mat.sum()/2) # --------------------------- # circle (undirected network) # --------------------------- # define graph object for undirected circle network # using a list of links for pairs of nodes circle = nx.Graph() circle.add_edges_from([('Abe', 'Bea'), ('Abe', 'Rob'), ('Bea', 'Dag'),\ ('Dag', 'Eve'), ('Eve', 'Jim'), ('Jim', 'Kat'), ('Kat', 'Rob')]) # examine the degree of each node print(nx.degree(circle)) # plot the circle network and degree distribution fig = plt.figure() nx.draw_networkx(circle, node_size = 2000, node_color = 'yellow') plt.show() fig = plt.figure() plt.hist(nx.degree(circle).values()) plt.axis([0, 8, 0, 8]) plt.xlabel('Node Degree') plt.ylabel('Frequency') plt.show() # create an adjacency matrix object for the circle network # use nodelist argument to order the rows and columns circle_mat = nx.adjacency_matrix(circle,\ nodelist = ['Abe', 'Bea', 'Dag', 'Eve', 'Jim', 'Kat', 'Rob']) print(circle_mat) # undirected networks are symmetric # determine the total number of links for the circle network print(circle_mat.sum()/2) # ------------------------- # line (undirected network) # ------------------------- # define graph object for undirected line network # using a list of links for pairs of nodes line = nx.Graph() line.add_edges_from([('Ali', 'Ben'), ('Ali', 'Ela'), ('Ben', 'Ian'),\ ('Ela', 'Mya'), ('Ian', 'Roy'), ('Mya', 'Zoe')]) # examine the degree of each node print(nx.degree(line)) # plot the line network and degree distribution fig = plt.figure() nx.draw_networkx(line, node_size = 2000, node_color = 'yellow') plt.show() fig = plt.figure() plt.hist(nx.degree(line).values()) plt.axis([0, 8, 0, 8]) plt.xlabel('Node Degree') plt.ylabel('Frequency') plt.show() # create an adjacency matrix object for the line network # use nodelist argument to order the rows and columns line_mat = nx.adjacency_matrix(line,\ nodelist = ['Ali', 'Ben', 'Ela', 'Ian', 'Mya', 'Roy', 'Zoe']) print(line_mat) # undirected networks are symmetric # determine the total number of links for the line network (n-1) print(line_mat.sum()/2) # --------------------------- # clique (undirected network) # --------------------------- # define graph object for undirected clique a_clique = nx.Graph() a_clique.add_edges_from([('Ada', 'Ala'), ('Ada', 'Ami'), ('Ada', 'Ana'),\ ('Ada', 'Ann'), ('Ada', 'Ara'), ('Ada', 'Ava'), ('Ala', 'Ami'),\ ('Ala', 'Ana'), ('Ala', 'Ann'), ('Ala', 'Ara'), ('Ala', 'Ava'),\ ('Ami', 'Ana'),('Ami', 'Ann'), ('Ami', 'Ara'), ('Ami', 'Ava'),\ ('Ana', 'Ann'), ('Ana', 'Ara'), ('Ana', 'Ava'),\ ('Ann', 'Ara'), ('Ann', 'Ava'), ('Ara', 'Ava')]) # examine the degree of each node print(nx.degree(a_clique)) # plot the clique and degree distribution fig = plt.figure() nx.draw_networkx(a_clique, node_size = 2000, node_color = 'yellow',\ pos = nx.circular_layout(a_clique)) plt.show() fig = plt.figure() plt.hist(nx.degree(a_clique).values()) plt.axis([0, 8, 0, 8]) plt.xlabel('Node Degree') plt.ylabel('Frequency') plt.show() # create an adjacency matrix object for the line network # use nodelist argument to order the rows and columns a_clique_mat = nx.adjacency_matrix(a_clique,\ nodelist = ['Ada', 'Ala', 'Ami', 'Ana', 'Ann', 'Ara', 'Ava']) print(a_clique_mat) # undirected networks are symmetric # determine the total number of links for the clique n(n-1)/2 print(a_clique_mat.sum()/2) # ------------------------------- # tree (directed network/digraph) # ------------------------------- # define graph object for undirected tree network # using a list of links for pairs of from-to nodes tree = nx.DiGraph() tree.add_edges_from([('Art', 'Bev'), ('Art', 'Dan'), ('Bev', 'Fay'),\ ('Bev', 'Lee'), ('Dan', 'Mia'), ('Mia', 'Sal'), ('Mia', 'Van')]) # examine the degree of each node print(nx.degree(tree)) # create an adjacency matrix object for the line network # use nodelist argument to order the rows and columns tree_mat = nx.adjacency_matrix(tree,\ nodelist = ['Art', 'Bev', 'Dan', 'Fay', 'Lee', 'Mia', 'Sal', 'Van']) print(tree_mat) # directed networks are not symmetric # determine the total number of links for the tree # upper triangle only has values print(tree_mat.sum()) # plot the degree distribution fig = plt.figure() plt.hist(nx.degree(tree).values()) plt.axis([0, 8, 0, 8]) plt.xlabel('Node Degree') plt.ylabel('Frequency') plt.show() # examine alternative layouts for plotting the tree # plot the network/graph with default layout fig = plt.figure() nx.draw_networkx(tree, node_size = 2000, node_color = 'yellow') plt.show() # spring layout fig = plt.figure() nx.draw_networkx(tree, node_size = 2000, node_color = 'yellow',\ pos = nx.spring_layout(tree)) plt.show() # circlular layout fig = plt.figure() nx.draw_networkx(tree, node_size = 2000, node_color = 'yellow',\ pos = nx.circular_layout(tree)) plt.show() # shell/concentric circles layout fig = plt.figure() nx.draw_networkx(tree, node_size = 2000, node_color = 'yellow',\ pos = nx.shell_layout(tree)) plt.show() # spectral layout fig = plt.figure() nx.draw_networkx(tree, node_size = 2000, node_color = 'yellow',\ pos = nx.spectral_layout(tree)) plt.show() # Gephi provides interactive network plots # dump the graph object in GraphML format for input to Gephi nx.write_graphml(tree,'tree_to_gephi.graphml') # Suggestions for the student: Define alternative network structures. # Use matplotlib to create their plots. Create the corresponding # adjacency matrices and compute network descriptive statistics, # beginning with degree centrality. Plot the degree distribution # for each network. Read about Gephi and try interactive plots.
class Solution: def climbStairs(self, n: int) -> int: options = [0,1,2] if n > 2: for x in range(3, n+1): options.append(options[x-1]+options[x-2]) return options[n]
# PARA IMPRIMIR CAPICUAS DE 5 DÍGITOS DE MANERA SIMPLE # @samusisto - UNRN, Ingeniería en computación # respondiendo al desafío del profe de prog I def prueba(): for i in range(10): for j in range(10): for k in range(10): print(f"{k}{j}{i}{j}{k}") if __name__ == "__main__": prueba()
#encoding:utf-8 from sys import argv script,input_file=argv#将argv赋值与script,input_file def print_all(f): print f.read() def rewind(f): f.seek(0) def print_a_line(line_count,f): print line_count,f.readline()#readline()第一次接触 current_file=open(input_file) print "First,let's print the whole file:\n" print_all(current_file)#该函数执行后,文件的IO指针已经到达文件末尾 print "\nNow ,let's rewind,kind of like a tape." rewind(current_file)#该函数执行后,文件的IO指针重头开始 print "\nLet's print three lines:" current_line=1 print_a_line(current_line,current_file) current_line+=1 print_a_line(current_line,current_file) current_line+=1 print_a_line(current_line,current_file)
#encoding:utf-8 #总共有100辆车 cars =100 #每辆车可以坐四个人 space_in_a_car=4.0 #If there are 2.8 people average in each cars,we got 2,that's a waste. #总共有30个司机 drivers=30 #目前有90个乘客待送 passengers=90 cars_not_driven=cars-drivers cars_driven=drivers carpool_capacity=cars_driven*space_in_a_car average_passengers_per_car=passengers/cars_driven print "There are ",cars,"cars available." print "There are only ",drivers," drivers available." print "There will be ",cars_not_driven," empty cars today." print "We can transport",carpool_capacity,"people today." print "We have ",passengers,"peopel to carpool today." print "We need to put",average_passengers_per_car,"people in each car." #python作为计算器 i=199 x=31 j=x*x/i-i print "We got j =",j
#encoding:utf-8 def add(a,b): print "ADDING %d+%d"%(a,b) return a+b def subtract(a,b): print "SUBTRACTING %d -%d"%(a,b) return a-b def multiply(a,b): print "MULTIPLY %d *%d"%(a,b) return a*b def divide(a,b): print "DIVDIDING %d / %d"%(a,b) return a/b print "Let's do some math with just functions!" age=add(0,30) height=subtract(78,3) weight=multiply(90,2) iq=divide(100,2) print "Age:%d,Height:%d,weight:%d,IQ:%d"%(age,height,weight,iq) #A puzzle for the extra credit,type it in anyway. print "Here is a puzzle." what=add(age,subtract(height,multiply(weight,divide(iq,2)))) print "That becomes:",what,"Can you do it by hand?"
#encoding:utf-8 print "Let's practise everything." print 'You\' d need to know \'bout escape with \\ that do \n newlines and \t tabs.' poem =""" \t The lovely world with magic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explanation \n\twhere there is none. """ print "-------------" print poem print "-------------" five=10-2+3-6 print "This should be five:%s"%five def secret_formula(started): jelly_beans=started*500 jars=jelly_beans /1000 crates=jars /100 return jelly_beans,jars,crates start_point=10000 beans,jars,crates=secret_formula(start_point) print "With a starting point of:%d"%start_point print "We'd have %d beans,%d jars,%d crates"%(beans,jars,crates) start_point=start_point /10 print "We can also do that this way:" print "We'd have %d beans,%d jars,and %d crates."%secret_formula(start_point)
Dict = {'Karthik':29, 'Karthik':'Good boy', 'Keyan':28, 'abc':0, 'Abc':'this is different key', 'xyz':11} print(Dict) print(Dict.items()) print(Dict['Keyan']) copiedDict = Dict.copy(); print(copiedDict) copiedDict.update({'a':111}) print(copiedDict) #copiedDict.add({'b':111}, {'c':111}, {'d':111} ) #print(copiedDict) for keys in Dict.keys(): print Dict[keys] for key in copiedDict.keys(): print(copiedDict[key]) print('#') for values in copiedDict.values(): print(values) sortedDict = copiedDict.keys(); sortedDict.sort() print sortedDict for s in sortedDict: print('Key: '+s+' Value: '+str(copiedDict[s])) Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} tuple1 = (50,) print "variable Type: %s" %type (tuple1) dict1 = {'a':1000, 'b':2000} dict2 = {'a':1000, 'b':2000} print(cmp(dict1, dict2)) print str(copiedDict) smallListVal = ['a', 'b', 'c','d', 'e', 'f', 'g', 'h', 'i', 'j'] bigListVal = ['A', 'B', 'C','D', 'E', 'F', 'G', 'H', 'I', 'J'] dictList = {'smallAlpha': smallListVal, 'bigAlpha': bigListVal} print dictList
import time from math import sqrt def solution2(n): answer = 0 for i in range(2, n+1): flag = True for j in range(2,i): if i%j==0: flag = False break if flag : answer = answer + 1 return answer def solution(n): #에레스토테네스의 체 list = [True] * n for i in range(2, int(sqrt(n))+1): if list[i]: for j in range(i+i, n, i): list[j] = False return len([i for i in range(n) if list[i]==True])-2 print("Start solution 1") start1 = time.time() print(solution(10000)) print("Time : " + str(time.time()-start1)) print("Start solution 2") start2 = time.time() print(solution2(10000)) print("Time : " + str(time.time()-start2))
#Queue Implementation class Queue: def __init__(self): self.item=[] def enqueue(self,item): self.item.insert(0,item) #O(N) and rest all methods are O(1) constant time def dequeue(self): if self.item: return self.item.pop() else: return None def peek(self): if self.item: return self.item[-1] else: return None def size(self): return len(self.item) def is_empty(self): return self.item==[] ob1=Queue() ob1.enqueue('Apple') ob1.enqueue('Banana') ob1.enqueue('Orange') print(ob1.dequeue()) print(ob1.is_empty()) print(ob1.peek()) print(ob1.size()) print(ob1.item)
#Composition :-creating relationship between classes and its objects. class Book: def __init__(self, title,price,author=None): self.title=title self.price=price self.author=author self.chapter=[] def addchapter(self,chapter): self.chapter.append(chapter) #def __str__(self): class Author: def __init__(self,name,rank): self.name=name self.rank=rank class chapter: def __init__(self,chaptername,noofpages): self.chaptername=chaptername self.noofpages=noofpages auth=Author('Himanshu Sahu',72) book=Book('this book',27,auth) ch1=chapter('chapter1st',9) book.addchapter(ch1) print(book.title) #play with it for composition
#Instance method and attributes class book: def __init__(self,Title,Pages,Price): self.Title=Title self.Pages=Pages self.Price=Price self.__secret='This is secret' def getprice(self): if hasattr(self, "_discount"): #hasattr important function to check attribute give attribute name in quotes return self.Price*self._discount else: return self.Price def discount(self,dis): self._discount=dis def main(): ob1=book('Road to lead',460,45.57) ob1.discount(0.1) print(ob1.getprice()) print(ob1._book__secret) #name mangling only can be access with classname print(type(ob1)) #<class '__main__.book'> print(isinstance(ob1,book)) #true no quotes required main()
#More into Self class myclass(): schoolname="St. Xaviers" Batch="A2" #Basically self is an object which refers to this particular instance def func1(self): return self.schoolname def main(): if False: print(1) elif True: print(2) elif True: print(3) else : print(4) c=myclass() #print(c.func1()) main()
# # #Revision # # x=0 # # while(x<10): # # print(x,end='') # # x+=1 # # for i in range(5,10): # # if i%2==0: # # break # # print(i,end='') # # l1=['hi','hello','bye','goodbye'] # # for i in l1: # # print(i) # # for i,v in enumerate(l1): # # print(f'index={i},value={v}') # # a=['1','h','hi','hi123','}',' '] # # for i in a: # # if i.isdecimal(): # # print('its numerical') # # elif i.isalnum(): # # print('its alphanumeric') # # else: # # print('something other') # # def fun1(): # # print('hi') # # fun1() # # print(fun1()) # # print(fun1) # # def fun2(arg1,arg2): # # print(f'{arg1},{arg2}') # # fun2(2,4) # # def fun3(*args): # # for i in args: # # print(i,end='') # # return True # # fun3(1,2,3,4,5,6) # # print(fun3(1,2)) # # class myclass: # # def func1(self): #slef refers to the object itself, this self in this function refers to the particular instance of that object which its been acted upon. # # print('Hi i am func1') # # def func2(self,var1): # # print(f'Hi i am func2,{var1}') # # obj1=myclass() # # obj1.func1() # # print(obj1.func2(5)) # # class anotherclass: # # def func3(self): # # print('calling the func1') # # myclass.func1(self) # # def func4(self,var2): # # print('Hi i am func4') # # obj2=anotherclass() # # obj2.func3() # # obj2.func4(5) # # import math # # print(f'{math.pi:0.2f}') # # print(f'{math.ceil(7.9)}') # # from datetime import datetime # # from datetime import date # # from datetime import time # # present_time=date.today() # # print(present_time.year,present_time.month,present_time.day) # # present_timestamp=datetime.now() # # print('extracting components') # # print(present_timestamp.year,present_timestamp.month,present_timestamp.day,datetime.time(present_timestamp)) # # from datetime import timedelta # # time1=timedelta(days=375,hours=3,minutes=5,seconds=45) # # print(str(datetime.now()-time1)) # # date1=date(month=4,day=1,year=2021) # # print(str(date.today()-date1)) # # f=open('newfile.txt','w+') # # for i in range(1,10): # # f.write(f'Hi i am line{i}') # # f.close() # # f=open('newfile.txt','r') # # for i in f.readlines(): # # print(i) # # f.close() # # f=open('newfile.txt','a') # # if f.mode=='a': # # print('hi') # # f.close() # # import os # # from os import path # # print(path.exists('newfile.txt')) # # print(path.isdir('newfile.txt'),path.isfile('newfile.txt')) # # print(path.realpath('newfile.txt')) # # print(path.split(path.realpath('newfile.txt'))) # # #os.rename('newfile1.txt','newfile.txt') # # #use shutil to copy the file # # #extarcting data from internet # # import urllib.request # # extract=urllib.request.urlopen('https://www.google.com') # # print(extract.read()) # # def isprime(num1): # # if num1<=1: # # return False # # else: # # for i in range(2,num1): # # if num1%i==0: # # return False # # return True # # for i in range(0,100): # # if isprime(i): # # print(i) # # def gen(start,stop): # # while(start<=stop): # # yield start # # start+=1 # # for i in gen(0,10): # # print(print(i)) # # f=open('testfile_1.txt','w+') # # for i in range(1,350000): # # f.write(f'This is line number {i} and this is created for test purpose kindly ignore the data please and hi bye goodbye heello') # # f.close() # l1=['hi','hello','bye','goodbye'] # for i,v in enumerate(l1): # print(i,v) # #to delete we use ,remove and del :- pop can delete the element taking index as arguments and returns the deleted value, del also delete the element at index and returns nothing and remove delete the element based on the value # # # l1.pop() # l1.pop(0) # del l1[0] #we can use indexing or range things here # l1.remove('bye') # print(l1) # #to insert we use insert and append method # l1.insert(0,'hi') # print(l1) # l1.append('hello') #append at the last it increase the lenght of the list by 1 its just append the object at the last # l3=['good','goodbye'] # l1.extend(l3) #in extend it iterates through all the elemetns presetn in the arguments (list) and append all those elements in the last so increase the lenthg of the list by number of elements present in the arguments # print(l1) # #indexing in list # print(l1[::-1]) #reverses a list # print(l1[1:3:1]) #output [] # print(l1[-1:-3:-1]) #ouput [goodbye,good] # #to know the lenght len is used # #to search index is used # print(l1.index('hi')) # print(':'.join(l1)) #it gives the string as output # tuple1=('hi','hello','bye') # #del tuple1[0] #it will give error # print(tuple1) # #tuple1[0]='hello' #cant assign # print(tuple1) # dict1={'morning':'breakfast','noon':'lunch','night':'dinner'} # for k,v in enumerate(dict1): # print(f'{k},{v}') # # items() to get key and value keys() to get keys values() to get values # for k in dict1.keys(): # print(k) # for v in dict1.values(): # print(v) # str1='hello my name is himanshu27' # set1=set(str1) # print(set1) #order doesn't matter has unique elements in it # class myclass: # def __init__(self,name,specialist,rating): # self._name=name # self._specialist=specialist # self._rating=rating # def getname(self): # return self._name # def getspecialist(self): # return self._specialist # def getrating(self): # return self._rating # def print1(self,o): # if isinstance(o,myclass): # print(f'{self._specialist,self._name,self._rating}') # ob1=myclass('virat','batsman',10) # ob1.getspecialist() # ob1.print1(ob1) # #str(123+'abc') # st1='hi my name is himanshu' # print(str1.upper()) # print(str1.lower()) # print(str1.title()) #all first letter is capital # print(str1.capitalize()) #only first letter # print(str1.swapcase()) # print(st1.split()) #it split with spaces # print(st1.split('h')) #character gayab # st2='xyz wvx' # print(st2.join(st1)) # def fib(): # start=0 # second=1 # print(start) # print(second) # next=0 # for i in range(0,100): # next=start+second # start=second # second=next # print(next) # fib() # def fibatindex(num1): # if num1==0 or num1==1: # return num1 # start=0 # next=1 # newval=0 # for i in range(1,num1): # #print('hi') # newval=start+next # start=next # next=newval # return newval # for i in range(0,15): # print(fibatindex(i),end=' ') import sqlite3 db=sqlite3.connect('data.db') cur=db.cursor() cur.execute('DROP TABLE IF EXISTS TEST') cur.execute('CREATE TABLE TEST (NAME VARCHAR,CLASS VARCHAR,ROLLNUMBER NUMBER PRIMARY KEY)') cur.execute("INSERT INTO TEST VALUES('HIMANSHU','12TH',1)") for row in cur.execute("Select * from test"): print(row) db.commit() db.close() print(2.0==2)
def sentence_maker(phrases): questions=("how","where","when","why","what") capitalized = phrases.title() if phrases.startswith(questions): return "{}?".format(capitalized) else: return "{}.".format(capitalized) print(sentence_maker("what are you")) total=[] final='' while True: message=input("Say Something:") if message == "\end": break else: total.append(sentence_maker(message)) continue print(" ".join(total))
# 1. Write a program which accepts a string as input to print "Yes" if the string is "yes", # "YES" or "Yes", otherwise print "No". # Hint: Use input () to get the persons input #string = input("enter a string") # if string = "yes": # print("YES") # else: # print("NO") y3= input("please enter a string:") if y3=="YES" or y3=="Yes" or y3=="yes": print("yes") else: print("no") # 2.Implement a function that takes as input three variables, and returns the largest of the three. # Do this without using the Python max () function! # The goal of this exercise is to think about some internals that Python normally takes care of for us. def max(X,Y,Z): if X> Y and X> Z: return(X) elif Y> X and Y> Z: return(Y) elif Z> X and Z> Y: return(Z) elif X==Y and X>Z: return(X) elif Y==Z and Y>X: return(Y) elif X==Z and Z>Y: return(Z) else: print("all numbers are equal") print(max(100,100,95)) # 3.Write a program that takes a list of numbers # (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and # last elements of the given list. For practice,write this code inside a function def listofnumbers(ls): newlist= ls[0], ls[-1] return newlist list1= (input("please enter a list ")) list1 = list1.split(",") extractedlist= listofnumbers(list1) print(extractedlist) # 4. Ask the user for a number. Depending on whether the number is even or odd, # print out an appropriate message to the user. Hint: how does an even / # odd number react differently when divided by 2? Extras: # 1. If the number is a multiple of 4, print out a different message Number = int(input("Enter a number")) if Number % 2== 0: print("you have entered an even number") elif Number % 2!= 0: print("You have entered an odd number") else: print("null") #5. With a given tuple (1, 2, 3, 4, 5, 6, 7, 8, 9, 10), # write a program to print the first half values in one line and the last half values in one line. tuples= (1,2,3,4,5,6,7,10,23,21) tuple1 = tuples[:5] tuple2 = tuples [5:] print(tuple1) print(tuple2) # mid=(len(tuple) + 1) / 2 # firstHalf = int(tuple[:mid]) # secondHalf = int(tuple[mid:]) # 6. Create a program whose major task is to calculate an individual’s # Net Salary by getting the inputs basic salary and benefits. Create 5 different functions which will calculate # the payee (i.e. Tax), NHIFDeductions, NSSFDeductions, grossSalary and netSalary. NB:Use KRA, # NHIF and NSSF values provided online to find the appropriate deductions brackets on an individual’s gross salary. def income(net): gross= input("please enter your gross salary") if gross >= 49057: tax= 0.3*gross net= gross- tax print(net)
# for i in range(10): # print(i+2) # for every in range(10): # print(every) # continue takes what is below it # for every in range(10): # print(every) # if every == 5: # continue # print("Jacque") # break days= ["M","T","W","T", "F"] for day in days: print(day)
#calsswork example 4 , loops from random import randrange #this is to be able to use randrange for the random number generator print("Random number guessing name ") print("Written by Franklin Araque") print("\n you get 5 guessese to guess the number between 1 and 100") #random number selector randomNumber = randrange(1,100) #this pick a random number when you run the program #setting variables Num=1 #the guessed number . e.g: "Guess #1" numberOfGuess = 1 #int(Num) #asking for input useGuess= int(input("Guess #"+str(Num) +": ")) #print(randomNumber) #checking input if useGuess != randomNumber: while Num<=5: if useGuess > randomNumber: print("Lower") #Num = Num+1 #useGuess= int(input("Guess #"+str(Num)+": ")) elif useGuess < randomNumber: print("Higher") #Num = Num+1 #useGuess= int(input("Guess #"+ str(Num) +": ")) #if the user guessed the number before reaching 5 tries elif useGuess == randomNumber: print("You guessed the Number correctly, good job!") replay = input("want to play againy? (y/n): ") #asking to play again #checking if user wnats to play again or not, if yes then asks for input again and resets "Num" number and resets the random number if replay.lower() == "y": randomNumber = randrange(1,100) #resetting the random number Num = numberOfGuess #setting "Num" back to 1, since numberOfGuess is 1 useGuess= int(input("Guess #"+str(Num) +": ")) #print(randomNumber) #checking again the new value of the input number anc comparing it to the random number if useGuess > randomNumber: print("Lower") elif useGuess < randomNumber: print("Higher") #if user types "n", program ends if replay.lower() == "n": print ("Thanks for playing!") break #user did not guess the number after 5 tries if Num ==5: #stops asking once the number of guesses reaches 5 and promps next message print("You did not guess the number, the number was " + str(randomNumber)) #number was not guessed message Num = Num+1 #adding one more to "Num" in order to stop the loop so it doersnt go in an infinite loop #since it will make "Num" be 6, thus higher than 5 making the loop end when it checks that is not equal to 5 #here it checks the user input after each try, and then promps the user for input again #*********************************************************************************************# #checking the user input, adding one more to "Num" and asking for input again if the number of questions is less than 5 elif Num<5: #check for number of guesses and to stop at guess #5 Num = Num+1 #adding one more to "Num" after each time the user is asked for a anumber useGuess= int(input("Guess #"+str(Num) +": ")) #checking the user input and asking again for input #*********************************************************************************************# #if user input matches random number, then asks if they want to play again #elif useGuess == randomNumber: # print("You guessed the Number correctly, good job!") #replay = intput("want to play againy? (y/n): ") #if replay.lower() == "y": #Num = numberOfGuess #useGuess= int(input("Guess #"+str(Num) +": ")) #elif replay.lower() == "n": #print ("Thanks for playing!") #break
def dodivision(a,b); return (a/b) # Return the quotient of a and b a = int(input("Enter a")) b = int(input("Enter b")) res=dodivision(a,b) print(res)
import random def insertion_sort(array:list, stop=0): if stop== len(array)-3: return array print(f'{stop} Iteracion = {array}') print('') for i in range(1,len(array)): if array[i]<array[i-1] : array[i], array[i-1] = array[i-1], array[i] return insertion_sort(array, stop+1) arr = [38, 15,12453, 23, 63, -523, 42, 95, 321, 1786, -323,7] print(f'Array original = {arr}') print() insertion_sort(array=arr) print(f'Array Ordenada = {arr}') """ Resultado Array original = [38, 15, 12453, 23, 63, -523, 42, 95, 321, 1786, -323, 7] 0 Iteracion = [38, 15, 12453, 23, 63, -523, 42, 95, 321, 1786, -323, 7] 1 Iteracion = [15, 38, 23, 63, -523, 42, 95, 321, 1786, -323, 7, 12453] 2 Iteracion = [15, 23, 38, -523, 42, 63, 95, 321, -323, 7, 1786, 12453] 3 Iteracion = [15, 23, -523, 38, 42, 63, 95, -323, 7, 321, 1786, 12453] 4 Iteracion = [15, -523, 23, 38, 42, 63, -323, 7, 95, 321, 1786, 12453] 5 Iteracion = [-523, 15, 23, 38, 42, -323, 7, 63, 95, 321, 1786, 12453] 6 Iteracion = [-523, 15, 23, 38, -323, 7, 42, 63, 95, 321, 1786, 12453] 7 Iteracion = [-523, 15, 23, -323, 7, 38, 42, 63, 95, 321, 1786, 12453] 8 Iteracion = [-523, 15, -323, 7, 23, 38, 42, 63, 95, 321, 1786, 12453] Array Ordenada = [-523, -323, 7, 15, 23, 38, 42, 63, 95, 321, 1786, 12453] """
A = float(input()) if ( 400>=A and A>=0): Reajuste1 = ((A/100)*15)+ A ReajusteG1 = Reajuste1 - A print ("Novo salario: %.2f" % Reajuste1) print ("Reajuste ganho: %.2f" % ReajusteG1) print ("Em percentual: 15 %") elif ( 400>A and 800>=A): Reajuste2 = ((A/100)*12)+ A ReajusteG2 = Reajuste2 - A print ("Novo salario: %.2f" % Reajuste2) print ("Reajuste ganho: %.2f" % ReajusteG2) print ("Em percentual: 12 %") elif ( 800>A and 1200>=A): Reajuste3 = ((A/100)*10)+ A ReajusteG3 = Reajuste3 - A print ("Novo salario: %.2f" % Reajuste3) print ("Reajuste ganho: %.2f" % ReajusteG3) print ("Em percentual: 10 %") elif ( 1200>A and 2000>=A): Reajuste4 = ((A/100)*7)+ A ReajusteG4 = Reajuste4 - A print ("Novo salario: %.2f" % Reajuste4) print ("Reajuste ganho: %.2f" % ReajusteG4) print ("Em percentual: 7 %") elif (A>2000): Reajuste5 = ((A/100)*4)+ A ReajusteG5 = Reajuste5 - A print ("Novo salario: %.2f" % Reajuste5) print ("Reajuste ganho: %.2f" % ReajusteG5) print ("Em percentual: 4 %")
N = int(input()) resp = N**2 Zero = 0 for i in range (1,N+1): if i%2==0 : resp = i**2 print("%d^2 = %d" %(i,resp))
""" ML lab 11-3 CNN using class CNN using Layers """ import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data class Model: """ img_x : 이미지의 가로 픽셀 사이즈 img_y : 이미지의 세로 픽셀 사이즈 label : 정답 label의 사이즈 """ def __init__(self, session, img_x, img_y, label): self.sess = session self.X = tf.placeholder(tf.float32, [None, img_x * img_y]) self.X_img = tf.reshape(self.X, [-1, img_x, img_y, 1]) self.Y = tf.placeholder(tf.float32, [None, label]) self.keep_prob = tf.placeholder(tf.float32) self.training = tf.placeholder(tf.bool) self.build_net() self.is_correct = tf.equal(tf.argmax(self.hypothesis, 1), tf.argmax(self.Y, 1)) self.accuracy = tf.reduce_mean(tf.cast(self.is_correct, tf.float32)) def build_net(self): """ W1 = tf.Variable(tf.random_normal([3, 3, 1, 32], stddev=0.01)) L1 = tf.nn.conv2d(self.X_img, W1, strides=[1, 1, 1, 1], padding='SAME') L1 = tf.nn.relu(L1) L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') L1 = tf.nn.dropout(L1, keep_prob=self.keep_prob) """ conv1 = tf.layers.conv2d(inputs=self.X_img, filters=32, kernel_size=[3, 3], padding="SAME", activation=tf.nn.relu) pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], padding="SAME", strides=2) dropout1 = tf.layers.dropout(inputs=pool1, rate=0.3, training=self.training) # conv -> (?, 28, 28, 32) # pool -> (?, 14, 14, 32) """ W2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01)) L2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME') L2 = tf.nn.relu(L2) L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') L2 = tf.nn.dropout(L2, keep_prob=self.keep_prob) """ conv2 = tf.layers.conv2d(inputs=dropout1, filters=64, kernel_size=[3, 3], padding="SAME", activation=tf.nn.relu) pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], padding="SAME", strides=2) dropout2 = tf.layers.dropout(inputs=pool2, rate=0.3, training=self.training) # conv -> (?, 14, 14, 64) # pool -> (?, 7, 7, 64) """ W3 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01)) L3 = tf.nn.conv2d(L2, W3, strides=[1, 1, 1, 1], padding='SAME') L3 = tf.nn.relu(L3) L3 = tf.nn.max_pool(L3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') L3 = tf.nn.dropout(L3, keep_prob=self.keep_prob) L3 = tf.reshape(L3, [-1, 4 * 4 * 128]) """ conv3 = tf.layers.conv2d(inputs=dropout2, filters=128, kernel_size=[3, 3], padding="SAME", activation=tf.nn.relu) pool3 = tf.layers.max_pooling2d(inputs=conv3, pool_size=[2, 2], padding="SAME", strides=2) dropout3 = tf.layers.dropout(inputs=pool3, rate=0.3, training=self.training) # conv -> (?, 7, 7, 128) # pool -> (?, 4, 4, 128) flat = tf.reshape(dropout3, [-1, 4 * 4 * 128]) """ W4 = tf.get_variable('W4', [4 * 4 * 128, 625], initializer=tf.contrib.layers.xavier_initializer()) b4 = tf.Variable(tf.random_normal([625])) L4 = tf.nn.relu(tf.matmul(L3, W4) + b4) L4 = tf.nn.dropout(L4, keep_prob=self.keep_prob) """ dense4 = tf.layers.dense(inputs=flat, units=625, activation=tf.nn.relu, kernel_initializer=tf.contrib.layers.xavier_initializer()) dropout4 = tf.layers.dropout(inputs=dense4, rate=0.3, training=self.training) W5 = tf.get_variable('W5', [625, 10], initializer=tf.contrib.layers.xavier_initializer()) b5 = tf.Variable(tf.random_normal([10])) self.hypothesis = tf.matmul(dropout4, W5) + b5 self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.hypothesis, labels=self.Y)) self.optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(self.cost) def train(self, x_data, y_data, keep_prob=0.7): return sess.run([self.cost, self.optimizer], feed_dict={self.X: x_data, self.Y: y_data, self.keep_prob: keep_prob, self.training: True}) def evaluate(self, x_data, y_data, batch_size=512): N = x_data.shape[0] acc = 0 for i in range(0, N, batch_size): batch_x = x_data[i: i + batch_size] batch_y = y_data[i: i + batch_size] N_batch = batch_x.shape[0] acc += sess.run(self.accuracy, feed_dict={self.X: batch_x, self.Y: batch_y, self.keep_prob: 1, self.training: False}) * N_batch return acc / N def get_accuracy(self, x_data, y_data): return self.evaluate(x_data, y_data) if __name__ == '__main__': print('main') mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) sess = tf.Session() model = Model(sess, 28, 28, 10) sess.run(tf.global_variables_initializer()) training_epochs = 10 batch_size = 100 for epoch in range(training_epochs): avg_cost = 0 total_batch = int(mnist.train.num_examples / batch_size) for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) c, _ = model.train(batch_xs, batch_ys, 0.7) avg_cost += c / total_batch print('Epoch:', '%04d' % (epoch + 1), 'cost = ', '{:.9f}'.format(avg_cost)) print("Accuracy: ", model.evaluate(mnist.test.images, mnist.test.labels))
""" Author: Chris Bruns Title: HW3.py Description: """ import itertools def possibleMoves(boardList, changeItems, goalState): """ Takes in the original input board. The possible moves (changeItems) is iterated through and all possible combinations are created. This is then used to compare to the indexes in the current board to determine if a move is legal or not. And the goal state is currently not being used yet... It returns a dictionary with the key the being the new board and the value being how it was altered. """ newList = [] characterList = [] combinations = [] movesList = [] testDict = {} for i, j in enumerate(boardList): if j == '*': characterList.append(i) r = 3 while r > 0: for combination in changeItems: for p in itertools.combinations(combination, r): combinations.append(p) combinationVariance = p testForSimilar = set(characterList) & set(combinationVariance) if len(testForSimilar) == 0: for part in boardList: newList.append(part) for num in combinationVariance: newList[num] = '*' newList = ''.join(newList) testDict[newList] = combinationVariance newList = [] r -= 1 return testDict def validMoves(): """ Possible moves allowed in the game returned as a list """ movesList = [] row1 = [0,1,2] row2 = [3,4,5] row3 = [6,7,8] column1 = [0,3,6] column2 = [1,4,7] column3 = [2,5,8] movesList.append(row1) movesList.append(row2) movesList.append(row3) movesList.append(column1) movesList.append(column2) movesList.append(column3) return movesList def miniMax(key, moves, goalState): """ Recursively goes through the keys and attaches a count value used to deterimine if good for max or min in the main function. """ count = 9 while key != goalState: keys = possibleMoves(key, moves, goalState) newKeys = keys.keys() newValues = keys.values() key = newKeys[0] if key == goalState: if count % 2 == 0: positionCount = count else: positionCount = -10 value = newValues[0] count -= 1 return [key, value, positionCount] def main(): board = raw_input("Enter the starting state for the board (- or *): ") if len(board) != 9: print "The input was not long enough, make sure it is 9 characters." main() else: pass for ch in board: if ch == '*': pass elif ch == '-': pass else: print "Improper values were used, please construct the board of only '-' and '*'." main() boardList = [] for ch in board: boardList.append(ch) newBoard = ''.join(boardList) goalState = ['*','*','*','*','*','*','*','*','*'] goalState = ''.join(goalState) moves = validMoves() changes = possibleMoves(newBoard, moves, goalState) changesDict = changes keys = changesDict.keys() possibilities = [] for key in keys: if key != goalState: add = miniMax(key, moves, goalState) possibilities.append(add) else: add = [goalState, changesDict[key], 10] possibilities.append(add) maxMoves = [] minMoves = [] for element in possibilities: if element[2] > 0: maxMoves.append(element) else: minMoves.append(element) maxBestMarkers = [] minBestMarkers = [] if len(maxMoves) != 0: maxBest = maxMoves.pop() maxBest = maxBest[1] for num in maxBest: maxBestMarkers.append(num+1) if len(minMoves) != 0: minBest = minMoves.pop() minBest = minBest[1] for num in minBest: minBestMarkers.append(num+1) solution = [] if len(maxBestMarkers) != 0: solution = maxBestMarkers solution.append("and you will eventually win.") else: solution = minBestMarkers solution.append("and you will eventually lose.") print "Your best option is to place marker(s) at position(s)", str(solution)[1:-1] main()
print("#하나만 출력1") print() print("#하나만 출력2","abce",sep="\n", end="\n\n") print("결과" ,end="\n\n") print(type("하나만"), type(12), type(12.5), sep='\n', end='\n\n') print("안녕하세요\n"*5) print("안녕하세요"[0]) print("안녕하세요"[1]) print("안녕하세요"[2]) print("안녕하세요"[3]) print("안녕하세요"[4]) print("안녕하세요"[-2]) print("안녕하세요"[-3]) print("안녕하세요"[-4]) print("안녕하세요"[-5]) print() print("안녕하세요"[0:4]) print("안녕하세요"[:3]) print("안녕하세요"[3:]) print() hello = "안녕하세요" print(hello) print(type(hello), hello[:2], hello, sep='\n', end='\n\n') # res = input("답정너~~~`") # print("입력한 답은", res) a = "10 11 a b 14".split(" ") print(type(a), a, sep='\n') print() x,y,z = 10, 20, 30 print(x,y,z, sep="\n") print(x, y) x, y = y, x print(x,y)
tuple_test1 = (10,20,30) # tuple_test2 = tuple(10,20,30) tuple_test2 = 10,20,30 list_test1=[1,2,3] print("tuple_test1",tuple_test1, type(tuple_test1), end='\n\n') print("tuple_test2",tuple_test2, type(tuple_test2), end='\n\n') print("list_test1",list_test1,type(list_test1),end='\n\n') # 튜플은 수정불가능, 리스트는 수정가능 list_test1[1]=10 print("list_test1",list_test1,type(list_test1),end='\n\n') [a,b] = [10,20] (c,d) = (10,20) print("a: ", a, " b: ", b , end="\n\n") print("c: ", c, " d: ", d , end="\n\n")
example_list = ["요소A","요소B","요소C"] i = 0 print("# 단순 출력") print(example_list) print() print("#enumerate()함수 적용 출력") print(enumerate(example_list)) print() print("#list() 함수로 강제 변환 출력") print(list(enumerate(example_list))) print() print("#반복분과 조합하기") for i, value in enumerate(example_list): print("{}번째 요소는 {}입니다.".format(i , value)) print() for a in example_list: print("{}번째 요소는 {}입니다.".format(i, a)) i+=1 for i in range(len(example_list)): print("{}번째 요소는 {}입니다.".format(i, example_list[i])) #변수를 선언. example_dictionary = { "키A": "값A", "키B": "값B", "키C": "값C", } print() #딕셔너리의 items() 함수 결과 출력하기 print("#딕셔너리의 items()함수") print("items():", example_dictionary.items()) print() print("#딕셔너리의 items() 함수와 반복문 조합하기") for key, element in example_dictionary.items(): print("dictionary[{}] = {}".format(key, element))
import json data = '{"name1" : "Satya", "Age": 26}' parse_data = json.loads(data) print(parse_data) print(parse_data['Age']) ''' Difference Between json.load and json.load json.loads = accepts data in string format json.load = accepts the file path inside which json data is present json.dumps = accepts data in string format and make it javascript compatible ''' data2 = { "ll" : [1,2,3,4,5], "tup" : ("somethig", 340), "isThere": False } new_data = json.dumps(data2) print(new_data) new_data = json.dumps(data2,sort_keys=True) print(new_data)
class Car: # class variables # when a class variable is changed by an object, then system creates an instance variable for that object wheels = 4 # any variable defined inside method or constructor, then it's called instance variable # constructor of the pass # Meaning of self is the object on which operations is being performed def __init__(self): print("inside constructor") # There is no concept of constructor overloading # in case of multiple constructor defined inside a class, the latest copy of the constructor gets called def __init__(self, car_color): self.car_color = car_color print("Car color is : " + self.car_color) def test(self): print("test method") # any variable defined inside method or constructor, then it's called instace variable def set_price(self, price): self.price = price def get_price(self, ): return self.price #### once the latest line of the constructor is defined then the previous line of constructor woll not work ## i.e. contructor overloading is not possible in python # How to create object of a class # c1 = Car() # c1.test() # # Class variables can be access by the object name or by the class itself but when a class varibale is changed by the # object, then system creates an instance variable for that object print(Car.wheels) print(c1.wheels) # # c1.set_price(2000) # print(c1.get_price()) c2 = Car("Red") c3 = Car("white") # How to create a blank class class BlankClass: pass p1 = BlankClass() print("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$") class Point(object): def draw(self): print("Print Point") p1 = Point() p1.draw() p1.x = 10 print(p1.x) p2 = Point() p2.draw() print(p2.x) # --> Attribute Error
# Tuple is a collection of elements of any type # But it can't be modified as it's immutable # syntax names = (1,2,3) # Tuple is order based i.e. stores data according to index names = ("java","js","python") # names[1] = ".net" --> not allowed to change print(names) #to delete the object from memory del names #print(names[1]) #Concatination t1 = (1,2,3) t2 = (4,5,6) print(t1+t2) #Repetation print(t1*4) #Slicing print(t1[1:]) # in print(6 in t2) print(5 not in t2) for i in t2: print(i) print(len(t2)) #Max Number print(max(t2)) print(min(t1)) #Here in the below case, te index having highest alphabatical word will be returned t1 = ("javazzzz","js","python") print(max(t1)) t1 = ("zjava","js","python","jz") print(max(t1)) print(min(t1)) #converting anything to tuple object print(tuple((1,2,3,4))) print(tuple([1,2,3,4])) print(tuple({1,2,3,4}))
#while count = 0 while(count<=3): print(count) count+=1; count1 = 0 while(count1<=3): print(count1) count1+=1; else: print("Reached the Number") #For Loop name = ["java","python","js"] for i in name: print(i) str = "I am loving python" for i in str: print(i) #Range --> excluding the last number #range(x) --> from o till x-1 #range(x,y) --> from x till y-1 #range(x,y,z) --> from x till y-1, skipping z chars i.e range (1,10,3) --> 1,4,7 name = ["java","python","js"] for i in range(len(name)): print(name[i]) #for loop with else name = ["java","python","js"] for i in range(len(name)): print(name[i]) else: print("end of the list") name = ["java","python","js"] for i in range(1): print(name[i]) else: print("end of the list") str1 = ["java","python","js",".net","c#","groovy"] for i in range(1,3): print(str1[i]) #Nested for loop for i in range(1,5): for j in range(2,4): print(i,j) print(str1[i],str1[j]) for i in range(1,5): for j in range(i): print(i, end="*") print() print("----------------------") for i in range(1,10,3): print(i) print("----------------------") numbers = [5,2,5,2,2] for i in numbers: print("*"*i) print("----------------------") for i in numbers: output = "" for j in range(i): output += "*" print(output)
# Global Variable i = 10 def try_a_fun(n): # if the below line is not used, then error will be thrown global i i += 1 k = 23 print(n) print(i) try_a_fun(22) ####################################################### rr = 10 def test_local_global(): # the below rr is the local scope tp the function and not global rr = 5 print(rr) test_local_global() # Since there is no global variable called k, below line line will throw error # print(k) ####################################################### # IMP --> In case global keyword is used and there is no such variable, then it'll create that variable def global_key_word(): global zz zz = 399 print(zz) def global_key_word_2(): print(zz) global_key_word() global_key_word_2()
class Employee: no_of_leaves = 8 def __init__(self, arg_name, arg_salary, arg_age): self.name = arg_name self.salary = arg_salary self.age = arg_age def print_name(self): print(f'Employee name is {self.name}, salary is {self.salary}, and age is {self.age}') # static method doesn't take any argument like class or self object @staticmethod def static_method_test(name): print(f'Hello {name}') rohan = Employee("Rohan","200","25") rohan.static_method_test("World") Employee.static_method_test("Karan")
def max(a, b): if a > b: return a return b def f(a, i, j, value, p): value += a[i][j] if (i == 0) and (j == 0): if p[i][j].find('*') == -1: p[i][j] += "*" return value if i == 0: return f(a, i, j - 1, value, p) elif j == 0: return f(a, i - 1, j, value, p) if f(a, i - 1, j, value, p) > f(a, i, j - 1, value, p): if p[i - 1][j].find('*') == -1: p[i - 1][j] += "*" return f(a, i - 1, j, value, p) else: if p[i][j - 1].find('*') == -1: p[i][j - 1] += "*" return f(a, i, j - 1, value, p) def get_max_value(board): p = [] for i in range(len(board)): p.append([]) for j in range(len(board[0])): p[i].append(str(board[i][j])) unswer = f(board, len(board) - 1, len(board[0]) - 1, 0, p) p[len(board) - 1][len(board[0]) - 1] += '*' for i in range(len(board)): for j in range(len(board[0])): print(p[i][j], end=' ') print() return unswer
import random BIN = [1, 2, 4, 8, 16, 32, 64, 124, 256, 512, 1024] def find(ar): result = [] for el in ar: if el in BIN: result.append(el) return result if __name__ == "__main__": array = [] for i in range(int(input(''))): array.append(random.randrange(1000)) print(array) print(find(array))
def sequences(lst : list, k, n): """ :param lst: підсписок перестановок :param k: елемент для вставки :param n: найбільший елемент послідовності :return: None """ if k > n: # Якщо всі елементи вже вичерпано return # Вставляємо елемент k у всі можливі позиції списку # отриманого на попередніх ітераціях for pos in range(k): lst_next = lst[:] # Копіюємо список lst_next.insert(pos, k) # вставляємо елемент sequences(lst_next, k + 1, n) # Запускаємо рекурсивно додавання наступного члена послідовності. # Головна програма if __name__ == "__main__": k = int(input()) lst = [] sequences(lst, 1, 12) print(lst) dict = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g', 8:'h', 9:'i', 10:'j', 11:'k', 12:'l'}
class Solution(object): def shortestDistance(self, words, word1, word2): """ :type words: List[str] :type word1: str :type word2: str :rtype: int """ i1, i2 = -1, -1 res = len(words) for i, w in enumerate(words): if w == word1: i1 = i if w == word2: i2 =i if i1 != -1 and i2 != -1: res = min(abs(i1-i2), res) return res
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None from heapq import * class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ h = [] dummy = ListNode(0) node = dummy [heappush(h, (n.val, n)) for n in lists if n] while len(h) != 0: (val, n) = heappop(h) node.next = ListNode(val) node = node.next if n.next: heappush(h, (n.next.val, n.next)) return dummy.next
import unittest class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ count = 0 if n == 0: return 0 while n != 0: n &= (n-1) count += 1 return count class Test(unittest.TestCase): def setUp(self): self.solution = Solution() def test_0(self): self.assertEqual(self.solution.hammingWeight(4), 1) def test_1(self): self.assertEqual(self.solution.hammingWeight(3), 2) def test_2(self): self.assertEqual(self.solution.hammingWeight(0), 0) if __name__ == '__main__': unittest.main()
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ front = 0 back = len(nums)-1 i = 0 while i <= back: if nums[i] == 0: nums[i], nums[front] = nums[front], nums[i] front += 1 if nums[i] == 2: nums[i], nums[back] = nums[back], nums[i] back -= 1 i -= 1 i += 1
import unittest class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ int_char = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" ans_str = "" while n != 0: if n % 26 != 0: ans_str = int_char[n % 26] + ans_str else: ans_str = int_char[26] + ans_str n = (n-1) // 26 return ans_str class Test(unittest.TestCase): def test_0(self): self.assertEqual(Solution().convertToTitle(26), "Z") def test_1(self): self.assertEqual(Solution().convertToTitle(27), "AA") if __name__ == '__main__': unittest.main()
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def closestValue(self, root, target): """ :type root: TreeNode :type target: float :rtype: int """ val = 0 if root.left and target < root.val: val = min( [root.val, self.closestValue(root.left, target)], key=lambda val: abs(target-val) ) elif root.right and target > root.val: val = min( [root.val, self.closestValue(root.right, target)], key=lambda val: abs(target-val) ) else: val = root.val return val
from collections import defaultdict class Solution(object): def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ dict = defaultdict(list) for str in strs: dict[''.join(sorted(str))].append(str) return [sorted(v) for v in dict.values()]
from collections import OrderedDict class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.dict = OrderedDict() self.cap = capacity def get(self, key): """ :rtype: int """ if key in self.dict: value = self.dict[key] del self.dict[key] self.dict[key] = value return self.dict[key] return -1 def set(self, key, value): """ :type key: int :type value: int :rtype: nothing """ if key in self.dict: del self.dict[key] self.dict[key] = value if len(self.dict) > self.cap: self.dict.popitem(last=False)
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ res = [] inserted = False for inter in intervals: if inserted or inter.end < newInterval.start: res.append(inter) elif not inserted and newInterval.end < inter.start: res.append(newInterval) res.append(inter) inserted = True else: newInterval.start = min(newInterval.start, inter.start) newInterval.end = max(newInterval.end, inter.end) if not inserted: res.append(newInterval) return res
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def binaryTreePathsHelper(self, root, s): """ :type root: TreeNode :rtype: List[str] """ ans = [] if root.left: ans += self.binaryTreePathsHelper(root.left, s + "->" + str(root.left.val)) if root.right: ans += self.binaryTreePathsHelper(root.right, s + "->" + str(root.right.val)) if root.left is None and root.right is None: ans = [s] return ans def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ if root is None: return [] return self.binaryTreePathsHelper(root, str(root.val))
class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ results = [] resultsSet = set() nums.sort() for i in range(0, len(nums)-2): num = nums[i] l, r = i+1, len(nums)-1 while l < r: sum3 = num + nums[l] + nums[r] if sum3 > 0: r -= 1 elif sum3 < 0: l += 1 else: if (num, nums[l], nums[r]) not in resultsSet: results.append([num, nums[l], nums[r]]) resultsSet.add((num, nums[l], nums[r])) l += 1 return results
import unittest class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ s = str(x) if s[0] == "-": if int(s[0] + s[1:][::-1]) < -2147483648: return 0 else: return int(s[0] + s[1:][::-1]) else: if int(s[::-1]) > 2147483648: return 0 else: return int(s[::-1]) class Test(unittest.TestCase): def setUp(self): self.solution = Solution() def test_0(self): self.assertEqual(self.solution.reverse(123), 321) def test_1(self): self.assertEqual(self.solution.reverse(-123), -321) if __name__ == '__main__': unittest.main()
import unittest class MinStack(object): def __init__(self): """ initialize your data structure here. """ self.stack = [] def push(self, x): """ :type x: int :rtype: nothing """ current_min = x if len(self.stack) == 0 or x < self.getMin() else self.getMin() self.stack.append((x, current_min)) def pop(self): """ :rtype: nothing """ self.stack.pop() def top(self): """ :rtype: int """ return self.stack[-1][0] def getMin(self): """ :rtype: int """ return self.stack[-1][1] class Test(unittest.TestCase): def test_0(self): s = MinStack() s.push(-3) s.push(-5) self.assertEqual(s.getMin(), -5) s.pop() self.assertEqual(s.getMin(), -3) if __name__ == '__main__': unittest.main()
class Solution(object): def walk(self, dist, r, c, rooms): row = len(rooms) col = len(rooms[0]) if not (0 <= r < row and 0 <= c < col): return if rooms[r][c] < dist: return rooms[r][c] = dist self.walk(dist+1, r-1, c, rooms) self.walk(dist+1, r+1, c, rooms) self.walk(dist+1, r, c-1, rooms) self.walk(dist+1, r, c+1, rooms) def wallsAndGates(self, rooms): """ :type rooms: List[List[int]] :rtype: void Do not return anything, modify rooms in-place instead. """ for r in range(len(rooms)): for c in range(len(rooms[0])): if rooms[r][c] == 0: self.walk(0, r, c, rooms) return
from random import * from time import * from copy import copy def swap(A, i, j): temp = A[i] A[i] = A[j] A[j] = temp def lomutoPartition(A, lo, hi): pivot = A[hi] i = lo for j in range(lo, hi): if A[j] <= pivot: swap(A, i, j) i += 1 swap(A, i, hi) return i def hoarePartition(A, lo, hi): pivot = A[lo] i = lo j = hi while True: while A[i] < pivot: i += 1 while A[j] > pivot: j -= 1 if i < j: swap(A, i, j) else: return j def quicksort_lomuto(A, lo, hi): if lo < hi: p = lomutoPartition(A, lo, hi) quicksort_lomuto(A, lo, p-1) quicksort_lomuto(A, p+1, hi) def quicksort_hoare(A, lo, hi): if lo < hi: p = hoarePartition(A, lo, hi) quicksort_hoare(A, lo, p) quicksort_hoare(A, p+1, hi) def merge(left, right): result = [] while len(left) is not 0 and len(right) is not 0: if left[0] <= right[0]: result.append(left[0]) left = left[1:] else: result.append(right[0]) right = right[1:] while len(left) is not 0: result.append(left[0]) left = left[1:] while len(right) is not 0: result.append(right[0]) right = right[1:] return result def mergesort(A): if len(A) <= 1: return A left = [] right = [] for i,x in enumerate(A): if i <= len(A) / 2 - 1: left.append(x) else: right.append(x) left = mergesort(left) right = mergesort(right) return merge(left, right) def testSort(n,k): cnt = 0 ql_a = [] qh_a = [] m_a = [] while cnt < k: x = range(n) x1 = copy(x) shuffle(x1) x2 = copy(x1) x3 = copy(x1) t0 = time() quicksort_lomuto(x1, 0, n-1) tf = time() assert(x1 == x) ql_a.append(tf - t0) t0 = time() quicksort_hoare(x2, 0, n-1) tf = time() assert(x2 == x) qh_a.append(tf - t0) t0 = time() x3 = mergesort(x3) tf = time() assert(x3 == x) m_a.append(tf - t0) cnt += 1 ql_avg = sum(ql_a) / float(k) qh_avg = sum(qh_a) / float(k) m_avg = sum(m_a) / float(k) return ql_avg, qh_avg, m_avg class HashTable(object): def __init__(self): """ """ self.table = {} def put(self, data): """ """ hashvalue = self.hashFunction(data) if self.table.has_key(hashvalue): if self.table[hashvalue] == data: print "the data '%s' is already in the hash table." % str(data) else: if type(self.table[hashvalue]) is not list: newData = [self.table[hashvalue]] newData.append(data) else: self.table[hashvalue] = data def get(self, data): """ """ hashvalue = self.hashFunction(data) if self.table.has_key(hashvalue): if self.table[hashvalue] == data: return self.table[hashvalue] else: if type(self.table[hashvalue]) is list: for d in self.table[hashvalue]: if d == data: return data print "the data '%s' is not in the hash table." % str(data) return None def hashFunction(self, data): """ """ return hash(data) def __getitem__(self, data): return self.get(data) n = 10 k = 10000 #out = testSort(n,k) #print out
from classes import lnAndDelay import classes from classes import Player def world1lev1(): lnAndDelay("INTO THE TEXT", 3) lnAndDelay("By: Caden Fischer", 3) print() lnAndDelay("A New Adventure awaits, {}!".format(Player.name), 4) lnAndDelay("You awake from a deep sleep.", 1.5) lnAndDelay("You find yourself in your tent.", 2.5) lnAndDelay("You get out of your tent and find yourself in the middle of a forest.", 5) lnAndDelay("There is one path to the north", 1.5) print() print("Basic Controls") print("Type a command when prompted.") print("n - north; e - east; s - south; w - west") print("inv - opens up your inventory") print() awaitCommand = True theInput = "" while awaitCommand: print() theInput = str(input("What do you want to do? ")).lower() print() if theInput == "n": lnAndDelay("You follow the path to the north.", 2.5) lnAndDelay("You notice it's getting darker and darker.", 3.5) lnAndDelay("You see a bag on the ground.", 1.5) lnAndDelay("You can continue on the path to the north.", 2.5) aAwaitCommand = True searchedBag = True while aAwaitCommand: print() theInput = str(input("What do you want to do? ")).lower() print() if theInput == "n": lnAndDelay("You exit the forest and enter a vast, open field", 3) lnAndDelay("You continue to walk north as it gets darker and darker", 4) lnAndDelay("As the last bit of light slips away, you see something glisten in the corner of your eye.", 6) theInput = input("Search the glistening object? (y or n) ") bAwaitCommand = True while bAwaitCommand: if theInput == "y": lnAndDelay("You search for the glistening object ...", 3) lnAndDelay("You try to make out the object ...", 3) print("You find a 'Lesser Healing Potion'!") Player.addToInventory(classes.HealthConsumable("Lesser Healing Potion", 1, 10, 2, 5)) bAwaitCommand = False elif theInput == "n": lnAndDelay("You decide to continue on the path", 3) bAwaitCommand = False else: print("That's not a yes (y) or a no (n)!") lnAndDelay("You look over a small hill and find a cave to stay in for the night.", 5) lnAndDelay("You try to find a good spot to sleep.", 3) lnAndDelay("You don't, but you sleep anyways.", 2) print() lnAndDelay("This is the end of World 1-1", 2) lnAndDelay("You earned 150 exp!", 2) Player.addExperience(150) print() return elif theInput == "e" or theInput == "w": print("Still a lot of trees.") elif theInput == "s": print("You decide not to head back to your tent.") elif theInput == "search bag" and searchedBag: lnAndDelay("You decide to search the bag ...", 5) lnAndDelay("You find 2 Gold Coins!", 2) Player.coins += 2 searchedBag = False elif theInput == "inv": Player.editInventory() else: print("{} doesn't want to do that".format(Player.name)) elif theInput == "e" or theInput == "s" or theInput == "w": print("Just a bunch of trees") elif theInput == "inv": Player.editInventory() else: print("{} doesn't want to do that".format(Player.name)) def world1lev2(): print() lnAndDelay("You wake up from a deep sleep in your cave.", 3) lnAndDelay("You walk outside and get blinded by the sunlight", 4) lnAndDelay("Your eyes adjust to the light.", 3) wolf = classes.enemy("Wolf", 2, 0, 10, classes.LootTable({0: classes.Item("Coins", 1, 3,10), 1: classes.Item("Wolf Tooth", 1, 0, 15), 2: classes.Item("exp", 1, 100, 300)}, [100, 35, 100])) lnAndDelay("You are attacked by a Wolf!", 3) if classes.battle(Player, wolf): del wolf lnAndDelay("You beat the wolf to death.", 3) else: lnAndDelay("You quickly run away from the wolf.", 3) lnAndDelay("You continue north.", 2) lnAndDelay("You see a small village.", 2) lnAndDelay("You head to the village.", 2) lnAndDelay("You enter the town, but ...", 5) lnAndDelay("No one is here.", 3) print() lnAndDelay("This is the end of World 1-2", 3.5) lnAndDelay("You earned 200 xp!", 1.5) Player.addExperience(200) print() def world1lev3(): print() lnAndDelay("You walk into the town", 3) lnAndDelay("You see 3 houses. One to the north, east, and south.", 5) lnAndDelay("You see a point of interest to the west.", 3) inTown = True while inTown: print() responce = str(input("What do you do? ")).lower() print() if responce == "n": lnAndDelay("You search the house to the north.", 3) lnAndDelay("It's an older building bulit with clay bricks.", 4) lnAndDelay("You the room you enter is dark.", 3) if Player.checkInventoryByName("Candle"): print("Lit party!!!") #Make House Inside (Battle?) else: lnAndDelay("Maybe if you had a light source you could see the room. ", 5) elif responce == "e": lnAndDelay("You approach an old house.", 2) lnAndDelay("You see through the window, a candle that has been lit.", 4) lnAndDelay("You enter the house and see it is completly empty.", 3) lnAndDelay("The only thing left is a table with a lit candle on it.", 4) lnAndDelay("You also see stairs going up to the south.", 3) lnAndDelay("The exit is to the west.", 2.5) inHouse = True candleTaken = False gemTaken = False while inHouse: print() responce = str(input("What do you want to do? ")).lower() print() if responce == "take candle" and not candleTaken: Player.addToInventory(classes.Item("Candle", 1, 8, 3)) lnAndDelay("You Took the candle off the table.", 3) candleTaken = True elif responce == "n" or responce == "e": lnAndDelay("It's a wall.", 3) elif responce == "w": inHouse = False lnAndDelay("You decide to leave the house.", 2) elif responce == "s" and not gemTaken: lnAndDelay("You walk up the stairs.", 2) lnAndDelay("You find a shinny object in the corner of the room.", 5) lnAndDelay("You found a gem!", 2) Player.gems += 1 lnAndDelay("You head back down stairs.", 3) gemTaken = True
num=0 while num<100: print(num+1) num=num+1
r=int(input("Enter no. of rows :")) r=r-1 i=0 j=0 while i<r+1: for col in range(0,2*r+1): if col in range(r-j,r+j+1): print("*",end="") else : print(" ",end="") print("\n") j=j+1 i=i+1
class Pow: def __init__(self,n=2,m=0): self.m=m self.n=n def __iter__(self): self.c=1 return self def __next__(self): if self.c<=self.m: self.c=self.c+1 r=self.n**self.c return r else: raise StopIteration("you have used all the powers") p=Pow(6,10) p=iter(p) while input("press something"): try: n=next(p) print(n) except StopIteration as e: print("error",e)
def hello(): print("first") yield 1 print("second") yield 2 print("third") yield 3 print("fourth") yield 4 print("fifth") yield 5 hello() p=hello() next(p) next(p) next(p) next(p) next(p) next(p) next(p)
x=input().split(",") l=[] for var in x: t=int(var) l.append(t) print(l)
username = input('Введите имя: ') userlast = input('Введите фамилию: ') userage = int(input('Введите год рождения: ')) userplace = input('Введите место рождения: ').capitalize() userage1 = 2018 - userage print('Hello', username, userlast, 'You are ', userage1 , 'years old. You are living in ', userplace)
a = [] user = input('Введите число : ') b = 'end' while True: if user == b: break uint = int(user) a.append(uint) markia = sum(a) user = input('Введите число: ') average = markia / len(a) print('you entered: ', a) print('Total: ', markia) print('Average: ', average)
def merge_sort(arr): if len(arr) > 1: mid = len(arr)//2 left_half = arr[:mid] right_half = arr[mid:] merge_sort(left_half) merge_sort(right_half) i = 0 j = 0 k = 0 while i < len(left_half) and j < len(right_half): if left_half[i] < right_half[j]: arr[k] = left_half[i] i += 1 elif left_half[i] > right_half[j]: arr[k] = right_half[j] j += 1 k += 1 while i < len(left_half): arr[k] = left_half[i] i += 1 k += 1 while j < len(right_half): arr[k] = right_half[j] j += 1 k += 1 print(arr) print(merge_sort([2, 4, 5, 7, 1, 3]))
#Coinflip game import random from time import sleep import math def coinflip(): heads = 0 tails = 0 flips = 0 for i in range(3): result = random.randint(0,1) flips += 1 sleep(1) if result == 0: heads += 1 print("Heads") elif result == 1: tails += 1 print("Tails") while True: if heads < 3: print("You did not get 3 heads in a row.") sleep(2) print("You try again because lives are at stake!") sleep(2) coinflip() if heads == 3: print("You have gathered enough luck to teleport to the King's liar for the final showdown!.") Magic_stick = True break
#!/usr/bin/python # Animal.py class Animal: ############################ # Helping function ############################ def __pi(self,s): return (s) ############################ # Manager function ############################ # Including a default contrutctor def __init__(self,legs): self.__legs = legs def __del__(self): pass ############################ # Access function ############################ def getName(self): return self.__legs def setName(self, legs): self.__legs = legs def isDisable(self): if(self.__legs == 0): print("Po is Disable") ############################ # Implementor function ############################ def toString(self): return ("Legs=" + str(self.__legs)) def removeLegs(self,num): self.__legs = (int(self.__legs) - num) if(int(self.__legs) < 0): print("The Value of Legs Can't be less than 0") return 0
import csv #read the csv file with open('file1.csv', 'r') as input_file: file_read = csv.DictReader(input_file) with open('file2.csv', 'wb') as file_write: # column names to be included in file columnNames = ['ParkName', 'State', 'partySize', 'RateType', 'BookingType', 'Equipment'] file_output = csv.DictWriter(file_write, fieldnames=columnNames, delimiter =',') file_output.writeheader() for line in file_read: # delete the columns not required in the file del line['Country'] del line['Adult'] del line['Child'] del line['BookingStartDate'] del line['BookingEnddate'] del line['Night'] del line['Permits'] file_output.writerow(line) print("file2 created")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Создайте списки: # моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что) my_family = ['father', 'mather', 'sister', 'brother'] # список списков приблизителного роста членов вашей семьи my_family_height = [ ['father', 180], ['mother', 165], ['sister', 164], ['brother', 166] ] # Выведите на консоль рост отца в формате # Рост отца - ХХ см print(my_family_height[0][0]) # Выведите на консоль общий рост вашей семьи как сумму ростов всех членов # Общий рост моей семьи - ХХ см sum = 0 i = 0 while i != len(my_family_height): sum = sum + my_family_height[i][1] i += 1 print(sum)
#In this assignment you will write a Python program that expands on https://www.py4e.com/code3/urllinks.py. The program will use urllib to read the HTML from the data files below, extract the href= vaues from the anchor tags, scan for a tag that is in a particular position from the top and follow that link, repeat the process a number of times, and report the last name you find. import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup url = input('Enter - ') html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html, "html.parser") count = int(input('Enter count: ')) position = int(input('Enter position: ')) - 1 tags = soup('a') url = tags[position].get('href', None) n = 0 while n < count: n = n + 1 print('Retrieving:', url) html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html, "html.parser") tags = soup('a') url = tags[position].get('href', None)
def get_answer(question, answers): return answers.get(question) myanswers = {"привет": "И тебе привет!", "как дела": "Лучше всех", "пока": "Увидимся"} #input(question) # r = get_answer("привет", myanswers) # print(r) # r = get_answer("как дела", myanswers) # print(r) q = input("Что скажешь?\n") r = get_answer(q, myanswers) print(r)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if(head==None or head.next==None): return head t = head p = head q = p.next r = q while p!=None and q!=None: if t.next != r: t.next = q p.next = q.next q.next = p t = p p = p.next if p==None or p.next==None: break q = p.next return r
import re name_age_sentence : str = ''' Jack is of age 21 and Jill is of age 18 Tom is of age 8 and Jerry is of age 4 Groot is of age 1 and Rocket is of age 2 ''' ages :dict = re.findall(r'\d{1,3}', name_age_sentence) names :dict = re.findall(r'[A-Z][a-z]*', name_age_sentence) age_dict :dict = {} x=0 for name in names: age_dict[name] = ages[x] x+=1 print(age_dict)
import sys def str(n): _str = "" _toBeAppended = "0" for x in range(1, n): _str += _toBeAppended return n n = int( sys.argv[1] ) # print n print str(n)
from typing import List class CollisionDetection: """ Parameters for how a Magnebot handles collision detection. """ def __init__(self, walls: bool = True, floor: bool = False, objects: bool = True, mass: float = 8, include_objects: List[int] = None, exclude_objects: List[int] = None, previous_was_same: bool = True): """ :param walls: If True, the Magnebot will stop when it collides with a wall. :param floor: If True, the Magnebot will stop when it collides with the floor. :param objects: If True, the Magnebot will stop when it collides collides with an object with a mass greater than the `mass` value unless the object is in the `exclude_objects`. :param mass: If `objects == True`, the Magnebot will only stop if it collides with an object with mass greater than or equal to this value. :param include_objects: The Magnebot will stop if it collides with any object in this list, *regardless* of mass, whether or not `objects == True`, or the mass of the object. Can be None. :param exclude_objects: The Magnebot will ignore a collision with any object in this list, *regardless* of whether or not `objects == True` or the mass of the object. Can be None.. :param previous_was_same: If True, the Magnebot will stop if the previous action resulted in a collision and was the [same sort of action as the current one](collision_action.md). """ """:field If True, the Magnebot will stop when it collides with a wall. """ self.walls: bool = walls """:field If True, the Magnebot will stop when it collides with the floor. """ self.floor: bool = floor """:field If True, the Magnebot will stop when it collides collides with an object with a mass greater than the `mass` value unless the object is in the `exclude_objects`. """ self.objects: bool = objects """:field If `objects == True`, the Magnebot will only stop if it collides with an object with mass greater than or equal to this value. """ self.mass: float = mass if include_objects is None: """:field The Magnebot will stop if it collides with any object in this list, *regardless* of mass, whether or not `objects == True`, or the mass of the object. Can be None. """ self.include_objects: List[int] = list() else: self.include_objects: List[int] = include_objects if exclude_objects is None: """:field The Magnebot will ignore a collision with any object in this list, *regardless* of whether or not `objects == True` or the mass of the object. Can be None. """ self.exclude_objects: List[int] = list() else: self.exclude_objects: List[int] = exclude_objects """:field If True, the Magnebot will stop if the previous action resulted in a collision and was the [same sort of action as the current one](collision_action.md). """ self.previous_was_same: bool = previous_was_same
def relative_strength_index(df, base, target, period=8): """ Function to compute Relative Strength Index (RSI) df - the data frame base - on which the indicator has to be calculated eg Close target - column name to store output period - period of the rsi """ delta = df[base].diff() up, down = delta.copy(), delta.copy() up[up < 0] = 0 down[down > 0] = 0 r_up = up.ewm(com=period - 1, adjust=False).mean() r_down = down.ewm(com=period - 1, adjust=False).mean().abs() df[target] = 100 - 100 / (1 + r_up / r_down) df[target].fillna(0, inplace=True) return df
def getRow(rowIndex): """ :type rowIndex: int :rtype: List[int] """ row = [1] for _ in range(rowIndex): a = [0] + row b = row + [0] row = [sum(x) for x in zip(a, b)] return row print (getRow(3))
def hammingWeight(n): """ :type n: int :rtype: int """ if not n: return 0 count = 0 for _ in range(32): a = n & 1 if a == 1: count += 1 n = n >> 1 return count print (hammingWeight(11))
def trailingZeroes(n): """ :type n: int :rtype: int """ res = 0 x = 5 while n >= x: res = res + n / x x = x * 5 return res print (trailingZeroes(10))
def lengthOfLastWord(s): sn = s.split() if sn: s_last = sn[-1] return len(s_last) else: return 0 s = ' ' print (lengthOfLastWord(s))
def wordPattern(pattern, str): """ :type pattern: str :type str: str :rtype: bool """ t = str.split() a = map(pattern.find, pattern) b = map(t.index, t) return a == b print (wordPattern("abba", "dog cat cat dog"))
def thirdMax(nums): """ :type nums: List[int] :rtype: int """ nums = list(set(nums)) nums.sort() if len(nums) >= 3: return nums[-3] else: return nums[-1] print (thirdMax([1, 2]))
def power1(x, y): if y == 0: return 1 if y % 2 == 0: return power1(x, y / 2) * power1(x, y / 2) else: return x * power1(x, y / 2) * power1(x, y / 2) print (power1(2, 4))
import random def strip_elem(elem): elem = elem.strip() elem = elem.strip('.,?!()') return elem def split_text(): f = open('словосочетания.csv', 'r') b = {} string = f.read() string.lower() temp = string.split() if string: for i in range(0,len(temp),2): b[strip_elem(temp[i])] = strip_elem(temp[i + 1]) f.close() return b def printing(b, key_word): print(key_word + ' ', end = ''); for elem in b[key_word]: print('.', end = '') def enigma(b): key_word = random.choice(list(b.keys())) flag = '1' while flag == '1': printing(b, key_word) flag = '2' ans = input() if ans.strip() == b[key_word]: print('Красавчик!') flag_main = input('Хотите отгадывать? Нажмите 1\nХотите закончить? Нажмите 2') else: print('Невдача :(') flag = input('Ещё раз попробовать этот же: 1\nПопробовать другой: 2\nЗакончить: 3') if flag == '2': flag_main = '1' elif flag == '3': flag_main = '2' return flag_main def game(b): flag_main = input('Хотите отгадывать? Нажмите 1\nХотите закончить? Нажмите 2') while flag_main == '1': flag_main = enigma(b) else: print('Пока!') def main(): b = split_text() game(b) main()
def split_text(d): f = open(d, 'r', encoding = 'utf-8') b = [] string = f.read() string.lower() if string: for word in string.split(): word = word.strip() b.append(word.strip('.,?!()')) f.close() return b def printing(d): for elem in d: if d[elem] > 10: print(elem, d[elem]) def freq(b): d = {} for word in b: if word in d: d[word] += 1 else: d[word] = 1 return d def main(): s = input('Введите название файла: ') b = split_text(s) d = freq(b) printing(d) main()
#codigo01 import sys nome = input ("Digite seu nome:") idade = input ("Digite sua Idade:") print ("Digite seu sexo:") sexo = sys.stdin.readline() print("Nome:" +nome +"\n" + "Sexo: %s Idade: %s" %(sexo,idade)) #Codigo teste 02 # coding:utf-8 dedos = int(input("Voçê tem quantos Anos?")) if dedos == 18: print("Você tem 18 anos") elif dedos > 18: print("Você tem mais de 18 anos") else: print("Você é menor de idade")
from board.board import Board class Game: def __init__(self, upper_player, lower_player): """Instantiate a Mancala game.""" self.board = Board() self._upper_player = upper_player self._lower_player = lower_player self._current_player = self._upper_player def play(self) -> None: """Play the game.""" while True: if self._turn(): return def _swap_players_if_needed(self) -> None: """Swap the players if the board indicates it is needed.""" self._current_player = self._upper_player if self.board.current_player == 'upper' else self._lower_player def _turn(self) -> bool: """Run the game and return whether it has ended. :return: whether the game has ended """ pit_number = self._current_player.turn(self.board) if self.board.move(pit_number): self._print_winner_or_tie() return True # self._swap_players_if_needed() return False def _print_winner_or_tie(self): """Print the side of the winner or tie if a tie occurred.""" print(self.board) winner = self.board.winner() if winner != 'tie': print(f'{winner.capitalize()} player won!') else: print('Both players have the same amount of stones, tie.')
##count = 0 ## ##while count < 10: ## if isinstance(count / 3.0, int) ## numThree += 3 ##print int in range (1-10, 3) ##i = 0 f = -3 for i in range(0, 10, 3): print i f += 3 print f
# Google spreadsheet/map of hometowns and travel routes # instructions on how to do this with Sheets instead of a CSV: https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html # note: doing the mapping part with live Google API requires giving a credit card and being charged if go over the rate limit # import libraries needed for program import gmplot import csv # open csv file of places and read in the latitudes/longitudes; placesReader is a list of lists, that is a list of paired coordinates [lat, long] placesFile = open("places.csv") placesReader = csv.reader(placesFile) # create and center map on the University of Victoria, zoom level 3 gmap = gmplot.GoogleMapPlotter(48.4634, -123.3117, 3) # create lists of latitudes and longitudes # we are looping through each list [lat, long] in placesReader for location in placesReader: gmap.marker(float(location[0]), float(location[1])) # create map, save as map.html in the working directory gmap.draw('map.html') # close the files so we don't accidentally corrupt them or crash something placesFile.close()
import re # Regular expressions used to tokenize. _WORD_SPLIT = re.compile(b"([.,!?\"':;)(])\t") _DIGIT_RE = re.compile(br"\d") _PAD = b"_PAD" _GO = b"_GO" _EOS = b"_EOS" _UNK = b"_UNK" _START_VOCAB = [_PAD, _GO, _EOS, _UNK] PAD_ID = 0 GO_ID = 1 EOS_ID = 2 UNK_ID = 3 def basic_tokenizer(sentence): """Very basic tokenizer: split the sentence into a list of tokens.""" words = [] for space_separated_fragment in sentence.strip().split(): words.extend(re.split(_WORD_SPLIT, space_separated_fragment)) return [w for w in words if w] def initialize_vocabulary(data_file, normalize_digits=True, max_vocabulary_size=100000): """Initialize vocabulary from file. We assume the vocabulary is based on most frequent words. """ with open(data_file) as f: vocab = dict() for line in f: tokens = basic_tokenizer(line) for w in tokens: word = re.sub(_DIGIT_RE, b"0", w) if normalize_digits else w if word in vocab: vocab[word] += 1 else: vocab[word] = 1 vocab_list = _START_VOCAB + sorted(vocab, key=vocab.get, reverse=True) if len(vocab_list) > max_vocabulary_size: vocab_list = vocab_list[:max_vocabulary_size] word_to_id = dict(zip(vocab_list, range(len(vocab_list)))) return word_to_id def sentence_to_token_ids(sentence, vocabulary, normalize_digits=True): """Convert a string to list of integers representing token-ids. """ words = basic_tokenizer(sentence) if not normalize_digits: return [vocabulary.get(w, UNK_ID) for w in words] return [vocabulary.get(re.sub(_DIGIT_RE, b"0", w), UNK_ID) for w in words] def initialize_a_to_z(): word_to_id = dict() word_to_id[_PAD] = PAD_ID word_to_id[_GO] = GO_ID word_to_id[_EOS] = EOS_ID word_to_id[_UNK] = UNK_ID id = UNK_ID for x in "abcdefghijklmnopqustuvwxyz ": id += 1 word_to_id[x] = id return word_to_id def string_to_token_ids(str, vocabulary): return [vocabulary.get(c, UNK_ID) for c in str]
import pandas as pd import xlsxwriter # --------------------- custom rows------------------# def getrows(num): row_sel=input('for sheet '+str(num+1)+' discrete, continuous or all rows please enter D/C/A?\n') chk2 = row_sel.lower()== 'd' chk1=row_sel.lower()=='c' chk3 = row_sel.lower()=='a' chk = chk1 or chk2 or chk3 while not chk: row_sel = input('Invalid response! please enter D/C/A?\n') chk2 = row_sel.lower() == 'd' chk3 = row_sel.lower() == 'a' chk1 = row_sel.lower() == 'c' chk = chk1 or chk2 or chk3 if chk2: print('discrete') num_of_discR = input('please enter number of rows u want:\n' ) checkpt = num_of_discR.isdigit() and not int(num_of_discR)==0 while not checkpt: num_of_discR = input('enter a non zero integer value for number of rows:\n') checkpt = num_of_discR.isdigit() and not int(num_of_discR)==0 num_of_discR = int(num_of_discR) i=0 print("enter values of discrete rows") rows = [] while i<num_of_discR: dv = input('enter next value:\n') chk=dv.isdigit() while not chk: dv=input('enter integer value:\n') chk=dv.isdigit() rows.append(str(int(dv)-1)) i+=1 print(rows) return ['d',rows,str(num_of_discR)] elif chk1: print('continuous') start_row=input('please enter number of row to start with:\n') checkpt = start_row.isdigit() while not checkpt: start_row = input('enter an integer value for number of rows:\n') checkpt = start_row.isdigit() start_row=int(start_row)-1 end_row=input('please enter number of row to end with:\n') checkpt = end_row.isdigit() and int(end_row)>start_row while not checkpt: end_row = input('enter an integer value for number of rows:\n') checkpt = end_row.isdigit() and int(end_row)>start_row end_row=int(end_row)-1 print(start_row) print(end_row) num_contr=int(end_row)-int(start_row)+1 return ['c', start_row, end_row,str(num_contr)] else: return ['a'] # ------ runs successfully------# # ------------------------ custom columns --------------------# def getcolumns(num): col_sel=input('for sheet '+str(num+1)+'discrete, continuous or all columns please enter D/C/A?\n') chk2 = col_sel.lower()== 'd' chk1=col_sel.lower()=='c' chk3 = col_sel.lower() == 'a' chk = chk1 or chk2 or chk3 while not chk: col_sel = input('Invalid response! please enter D/C/A?\n') chk2 = col_sel.lower() == 'd' chk1 = col_sel.lower() == 'c' chk3 =col_sel.lower()=='a' chk = chk1 or chk2 or chk3 if chk2: print('discrete') num_of_discC = input('please enter number of columns u want:\n') checkpt = num_of_discC.isdigit() and not int(num_of_discC)==0 while not checkpt: num_of_discC = input('enter a non zero integer value for number of columns:\n') checkpt = num_of_discC.isdigit() and not int(num_of_discC)==0 num_of_discC = int(num_of_discC) i=0 print("enter values of discrete columns") cols = [] while i<num_of_discC: dv = input('enter next value:\n') chk=dv.isdigit() while not chk: dv=input('enter integer value:\n') chk=dv.isdigit() cols.append(str(int(dv)-1)) i+=1 print(cols) return ['d',cols,str(num_of_discC)] elif chk1: print('continuous') start_col=input('please enter number of columns to start with:\n') checkpt = start_col.isdigit() while not checkpt: start_col = input('enter an integer value for number of columns:\n') checkpt = start_col.isdigit() start_col=int(start_col)-1 end_col=input('please enter number of column to end with:\n') checkpt = end_col.isdigit() and int(end_col)>start_col while not checkpt: end_col = input('enter an integer value for number of columns:\n') checkpt = end_col.isdigit() and int(end_col)>start_col end_col=int(end_col)-1 print(start_col) print(end_col) num_contC=int(end_col)-int(start_col)+1 return ['c',start_col,end_col,str(num_contC)] else: return ['a'] # ------ runs successfully------# # ----------- input excel files -------- # def get_sheets(): num_of_excel =input('input the number of sheets you want:\n') checkpt = num_of_excel.isdigit() while not checkpt: num_of_excel = input('enter an integer value for number of sheets:\n') checkpt = num_of_excel.isdigit() num_of_excel = int(num_of_excel) sheet_loc_and_name=[] i=0 while i<num_of_excel: sheet_loc=input('enter the sheet '+str(i+1)+'\'s location:\n') sheet_name=input('enter the sheet '+str(i+1)+'\'s name:\n') sheet_loc_and_name.append([sheet_loc,sheet_name]) i+=1 return sheet_loc_and_name # ------ runs successfully------# # print(get_sheets()) # print(getrows()) # print(getcolumns()) # ---------- returning sliced dataframes for 1st sheet data-----------# def make_firstdataframe(sheet_dat, rows, cols): df = pd.read_excel(sheet_dat[0][0], sheet_dat[0][1],header=None) if rows[0]=='c' and cols[0]=='c': startrow =rows[1] endrow = rows[2]+1 startcol = cols[1] endcol= cols[2]+1 df =df.iloc[startrow:endrow,startcol:endcol] elif rows[0]=='c' and cols[0]=='d': startrow = rows[1] endrow = rows[2] + 1 col=[] for value in cols[1]: col.append(int(value)) df = df.iloc[startrow:endrow,col] elif rows[0] == 'd' and cols[0] == 'c': startcol = cols[1] endcol = cols[2] + 1 row = [] for value in rows[1]: row.append(int(value)) df = df.iloc[row, startcol:endcol] elif rows[0] == 'd' and cols[0] == 'd': row = [] for value in rows[1]: row.append(int(value)) col = [] for value in cols[1]: col.append(int(value)) df = df.iloc[row,col] elif rows[0]=='a' and cols[0]=='c': startcol = cols[1] endcol = cols[2] + 1 df = df.iloc[:, startcol:endcol] elif rows[0]=='a' and cols[0]=='d': col = [] for value in cols[1]: col.append(int(value)) df = df.iloc[:, col] elif rows[0]=='d' and cols[0]=='a': row = [] for value in rows[1]: row.append(int(value)) df = df.iloc[row,:] elif rows[0]=='c' and cols[0]=='a': startrow = rows[1] endrow = rows[2] + 1 df = df.iloc[startrow:endrow,:] return df # ----------- data frames for next sheets -----------------------# def make_othrdataframes(sheet_dat, rows, cols,num): df = pd.read_excel(sheet_dat[num][0], sheet_dat[num][1],header=None) print(df) if rows[0]=='c' and cols[0]=='c': startrow =rows[1] endrow = rows[2]+1 startcol = cols[1] endcol= cols[2]+1 df =df.iloc[startrow:endrow,startcol:endcol] elif rows[0]=='c' and cols[0]=='d': startrow = rows[1] endrow = rows[2] + 1 col=[] for value in cols[1]: col.append(int(value)) print(value) df = df.iloc[startrow:endrow,col] elif rows[0] == 'd' and cols[0] == 'c': startcol = cols[1] endcol = cols[2] + 1 row = [] for value in rows[1]: row.append(int(value)) df = df.iloc[row, startcol:endcol] elif rows[0] == 'd' and cols[0] == 'd': row = [] for value in rows[1]: row.append(int(value)) col = [] for value in cols[1]: col.append(int(value)) df = df.iloc[row,col] elif rows[0] == 'a' and cols[0] == 'c': startcol = cols[1] endcol = cols[2] + 1 df = df.iloc[:, startcol:endcol] elif rows[0] == 'a' and cols[0] == 'd': col = [] for value in cols[1]: col.append(int(value)) df = df.iloc[:, col] elif rows[0] == 'd' and cols[0] == 'a': row = [] for value in rows[1]: row.append(int(value)) df = df.iloc[row, 1:] elif rows[0] == 'c' and cols[0] == 'a': startrow = rows[1] endrow = rows[2] + 1 df = df.iloc[startrow:endrow, 1:] return df #print(make_dataframes(['p67_1.xlsx','Sheet1'],['c',3,79],['d',['0','5','6']])) sheets_dat=get_sheets() print(sheets_dat) num_of_sheets=len(sheets_dat) print(num_of_sheets) # rows=getrows(1) # cols=getcolumns(1) if num_of_sheets>1: rows = getrows(0) if rows[0] is not 'a': nr=int(rows[-1]) row_type=rows[0] else: row_type='a' nr =0 columns = getcolumns(0) if columns[0]is not 'a': nc=int(columns[-1]) col_type=columns[0] else: col_type='a' df = make_firstdataframe(sheets_dat, rows, columns) row_indices = [] if nr!=0: n = 0 while n<nr: row_indices.append(n) n+=1 df.index = row_indices i=1 while i<num_of_sheets: rows = getrows(i) chk=rows[0]==row_type chkr =True while not chk and chkr: print('the row selection must match with the first sheet') rows = getrows(i) if row_type is 'd'or 'c': chkr = int(rows[-1]) != nr if chkr: print('the number of rows should be same') chk = rows[0] == row_type columns = getcolumns(i) df1 = make_othrdataframes(sheets_dat, rows, columns, i) if nr!=0: df1.index = row_indices print(df1) df=pd.concat([df,df1],axis=1) i+=1 else: rows = getrows(0) columns = getcolumns(0) df = make_firstdataframe(sheets_dat, rows, columns) dfw=df.copy() print(dfw) with pd.ExcelWriter('output.xlsx') as writer: # doctest: +SKIP dfw.to_excel(writer, sheet_name='Sheet_name_1', header = False,index = False) # print(make_othrdataframes(sheets_dat,rows,cols,2))
import sys # comment ''' multi-line comment num = raw_input('What is your fave float? ') print float(num) + 1 with open('numbers.txt', 'rb') as file: for line in file.readlines(): print line.rstrip() print('automatically prints newline') #print 'doesnt print newline because of comma', # how to do no newline with print() in python 3 print('lets print \'double quotes\'',end='\t') sys.stdout.write('no newline either') print('some more stuff') ''' with open('numbers.txt', 'a') as file: file.write('\n42')
#!/usr/bin/python __author__ = 'chukwuyem' #source: https://www.hackerrank.com/contests/countercode/challenges/campers #this worked!!! def main(): n, k = raw_input('').split(' ') m_team_id = [] #list with sniper ids and ids consecutive to sniper ids for x in raw_input('').split(' '): m_team_id.append(int(x)) m_team_id.append(int(x) + 1) if x > 1: m_team_id.append(int(x) - 1) #print m_team_id possible_team = [x for x in range(1, int(n) + 1)] #list of all possible ids for team #print possible_team #list of ids that can be picked after picking snipers possible_team_left = set(possible_team).difference(set(m_team_id)) #print possible_team_left possible_team_left = sorted(list(possible_team_left)) #go through sorted list of remaining ids, deleting the next item if it is a consecutive id it = 0 while it < len(possible_team_left) - 1: if possible_team_left[it + 1] == possible_team_left[it] + 1: del possible_team_left[it + 1] it += 1 #print possible_team_left print len(possible_team_left) + int(k) main()
from collections import Counter, defaultdict, namedtuple mylist = [1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,3] a = Counter('aaabbccccccdddddddd') # print(a['a']) # print(Counter(mylist)) letters = 'aaaaaabbbbcccccdddd' letter_class = Counter(letters) #print(letter_class.most_common(1)) # most common letter j = list(letter_class) #print(j) sentence = "Testing counter and showing how many times does each word show up in this sentence" # print(Counter(sentence.split())) d = {'a':10} #print(d['a']) e = defaultdict(lambda: 0) # get rid of error in case of key wrong value inputed e['correct'] = 100 # print(e['wrong key']) mytuple = (10,20,30) print(mytuple[0]) Dog = namedtuple('Dog', ['age', 'breed', 'name']) sammy = Dog(age=5, breed='Husky', name='Sam') print(sammy[-1])
""" 判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。 数字 1-9 在每一行只能出现一次。 数字 1-9 在每一列只能出现一次。 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-sudoku 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from collections import defaultdict class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: # 判断三个条件是否符合 # 需要一个处理,从index到3X3块儿的处理 # input-》(i,j): (i//3)*3+ (j//3) row_length = len(board) clo_length = len(board[0]) # 先将每个条件的数组搞出来 row = defaultdict(list) clo = defaultdict(list) area = defaultdict(list) for i in range(row_length): for j in range(clo_length): if board[i][j] == ".": continue row[i].append(board[i][j]) clo[j].append(board[i][j]) area[(i//3)*3+(j//3)].append(board[i][j]) # judge for i in range(row_length): for j in range(clo_length): if board[i][j]==".": continue # judge row if sum(1 for item in row[i] if board[i][j]==item) > 1: return False # clo if sum(1 for item in clo[j] if board[i][j]==item) > 1: return False # area if sum(1 for item in area[(i//3)*3+(j//3)] if board[i][j]==item) > 1: return False return True
# 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。 # # # # 说明: # # # 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。 # 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 # # # # # 示例: # # 输入: # nums1 = [1,2,3,0,0,0], m = 3 # nums2 = [2,5,6], n = 3 # # 输出: [1,2,2,3,5,6] # Related Topics 数组 双指针 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ # O(nlog(n)) time O(1) space if not nums2: return None ''' # 第一种方法:赋值后直接排序 nums1[m:] = nums2 nums1.sort() # 有一个疑问是进行切片赋值的过程中,有没有过多内存的消耗? ''' # 第二种方法,使用三指针法 i = m - 1 # nums1 pointer j = n - 1 # nums2 pointer k = m + n - 1 # right value place while i >= 0 and j >= 0: if nums1[i] > nums2[j]: nums1[k] = nums1[i] i -= 1 else: nums1[k] = nums2[j] j -= 1 k -= 1 nums1[:j + 1] = nums2[:j + 1] # leetcode submit region end(Prohibit modification and deletion)