blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
0b9176f78627950116865fb300d1afd9b4cce96d
tommymag/CodeGuild
/python/case_con.py
709
4.46875
4
# # Lab: Case Conversion # Write a program that prompts the user for a word. # Print out either `snake_case` or `CamelCase` depending case convention it is!. # ##### Instructions # Use substring membership with the `in` operator # 1. [PEP8](https://www.python.org/dev/peps/pep-0008/) # 1. [Stack Overflow](http://stackoverflow.com/questions/159720/what-is-the-naming-convention-in-python-for-variable-and-function-names) # - Python social conventions for variable and function naming case = input("What word would you like checked?: ") for stuff in case: if stuff.isupper(): print("This is CamelCase!") break elif stuff == "_": print("This is snake case") break
b21b15a431e19cf02d91426257c67a5e2b01710c
seanybaggins/MatrixAlgebra
/book/sources/15-Diagonalization_in-class-assignment.py
14,234
3.796875
4
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.10.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # # # # 15 In-Class Assignment: Diagonalization # # <img alt="Classig equation for diagonalizing a matrix. Will be discussed in class" src="https://wikimedia.org/api/rest_v1/media/math/render/svg/62ab0ef52ecb1e1452efe6acf096923035c75f62" width="50%"> # # Image from: [https://en.wikipedia.org/wiki/Diagonalizable_matrix](https://en.wikipedia.org/wiki/Diagonalizable_matrix) # # # ### Agenda for today's class (80 minutes) # # 1. [(20 minutes) Pre-class Assignment Review](#Pre-class_Assignment_Review) # 1. [(20 minutes) Diagonalization](#Diagonalization) # 1. [(20 minutes) The Power of a Matrix](#The_Power_of_a_Matrix) # # %matplotlib inline import matplotlib.pylab as plt import numpy as np import sympy as sym sym.init_printing() # --- # <a name="Pre-class_Assignment_Review"></a> # ## 1. Pre-class Assignment Review # * [15--Diagonalization_pre-class-assignment.ipynb](15--Diagonalization_pre-class-assignment.ipynb) # ---- # <a name="Diagonalization"></a> # ## 2. Diagonalization # **_Reminder_**: The eigenvalues of triangular (upper and lower) and diagonal matrices are easy: # # * The eigenvalues for triangular matrices are the diagonal elements. # * The eigenvalues for the diagonal matrices are the diagonal elements. # ### Diagonalization # # # **Definition**: A square matrix $A$ is said to be *diagonalizable* if there exist a matrix $C$ such that $D=C^{-1}AC$ is a diagonal matrix. # # **Definition**: $B$ is a *similar matrix* of $A$ if we can find $C$ such that $B=C^{-1}AC$. # # # Given an $n\times n$ matrix $A$, can we find another $n \times n$ invertable matrix $C$ such that when $D=C^{-1}AC$ is diagonal, i.e., $A$ is diagonalizable? # * Because $C$ is inveritble, we have # $$C^{-1}AC=D \\ CC^{-1}AC = CD\\ AC = CD $$ # # # * Generate $C$ as the columns of $n$ linearly independent vectors $(x_1...x_n)$ We can compute $AC=CD$ as follows: # $$ A\begin{bmatrix} \vdots & \vdots & \vdots & \vdots \\ \vdots & \vdots & \vdots & \vdots \\ { x }_{ 1 } & { x }_{ 2 } & \dots & { x }_{ n } \\ \vdots & \vdots & \vdots & \vdots \end{bmatrix}=AC=CD=\begin{bmatrix} \vdots & \vdots & \vdots & \vdots \\ \vdots & \vdots & \vdots & \vdots \\ { x }_{ 1 } & { x }_{ 2 } & \dots & { x }_{ n } \\ \vdots & \vdots & \vdots & \vdots \end{bmatrix}\begin{bmatrix} { \lambda }_{ 1 } & 0 & 0 & 0 \\ 0 & { \lambda }_{ 2 } & 0 & 0 \\ \vdots & \vdots & { \dots } & \vdots \\ 0 & 0 & 0 & { \lambda }_{ n } \end{bmatrix}$$ # * Then we check the corresponding columns of the both sides. We have # $$Ax_1 = \lambda_1x_1\\\vdots\\Ax_n=\lambda x_n$$ # # * $A$ has $n$ linear independent eigenvectors. # # * $A$ is saied to be *similar* to the diagonal matrix $D$, and the transformation of $A$ into $D$ is called a *similarity transformation*. # ### A simple example # # Consider the following: # $$ A = \begin{bmatrix}7& -10\\3& -4\end{bmatrix},\quad C = \begin{bmatrix}2& 5\\1& 3\end{bmatrix}$$ # &#9989; **<font color=red>Do this:</font>** Find the similar matrix $D = C^{-1}AC$ of $A$. # + #Put your answer to the above question here. # + nbgrader={"grade": true, "grade_id": "cell-3cdb9915439d45fe", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.matrix(D, '8313fe0f529090d6a8cdb36248cfdd6c'); # - # &#9989; **<font color=red>Do this:</font>** Find the eigenvalues and eigenvectors of $A$. Set variables ```e1``` and ```vec1``` to be the smallest eigenvalue and its associated eigenvector and ```e2, vec2``` to represent the largest. # + #Put your answer to the above question here. # + nbgrader={"grade": true, "grade_id": "cell-f4fda102502f50f9", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.float(e1, "e4c2e8edac362acab7123654b9e73432"); # + nbgrader={"grade": true, "grade_id": "cell-88300f29b8aec498", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.float(e2, "d1bd83a33f1a841ab7fda32449746cc4"); # + nbgrader={"grade": true, "grade_id": "cell-f26e2f5a3e41bdd8", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.eq_vector(vec1, "d28f0a721eedb3d5a4c714744883932e", decimal_accuracy = 4) # + nbgrader={"grade": true, "grade_id": "cell-a0ef501c592a3fcc", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.eq_vector(vec2, "09d9df5806bc8ef975074779da1f1023", decimal_accuracy = 4) # - # **Theorem:** Similar matrices have the same eigenvalues. # # **Proof:** Assume $B=C^{-1}AC$ is a similar matrix of $A$, and $\lambda$ is an eigenvalue of $A$ with corresponding eigenvector $x$. That is, $$Ax=\lambda x$$ # Then we have $$B(C^{-1}x) = C^{-1}AC(C^{-1}x) = C^{-1}Ax = C^{-1}(\lambda x)= \lambda (C^{-1}x).$$ # That is $C^{-1}x$ is an eigenvector of $B$ with eigenvalue $\lambda$. # ### A second example # # &#9989; **<font color=red>Do this:</font>** Consider # $$ A = \begin{bmatrix}-4& -6\\3& 5\end{bmatrix}.$$ # Find a matrix $C$ such that $C^{-1}AC$ is diagonal. (Hint, use the function `diagonalize` in `sympy`.) # + #Put your answer to the above question here. # + nbgrader={"grade": true, "grade_id": "cell-d9c7ff4aa895199e", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} #Check the output type assert(type(C)==sym.Matrix) # + nbgrader={"grade": true, "grade_id": "cell-2c06b41f80b7a258", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.matrix(C,'ba963b7fef354b4a7ddd880ca4bac071') # - # ### The third example # # &#9989; **<font color=red>Do this:</font>** Consider # $$ A = \begin{bmatrix}5& -3\\3& -1\end{bmatrix}.$$ # Can we find a matrix $C$ such that $C^{-1}AC$ is diagonal? (Hint: find eigenvalues and eigenvectors using `sympy`) # + nbgrader={"grade": true, "grade_id": "cell-8eb9fd1f4a5a6136", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false} #Put your answer to the above question here. # - # ### Dimensions of eigenspaces and diagonalization # # **Definition**: The set of all eigenvectors of a $n\times n$ matrix corresponding to a eigenvalue $\lambda$, together with the zero vector, is a subspace of $R^n$. This subspace spaces is called *eigenspace*. # # * For the third example, we have that the characteristic equation $(\lambda-2)^2=0$. # * Eigenvalue $\lambda=2$ has multiplicity 2, but the eigenspace has dimension 1, since we can not find two lineare independent eigenvector for $\lambda =2$. # # > The dimension of an eigenspace of a matrix is less than or equal to the multiplicity of the corresponding eigenvalue as a root of the characteristic equation. # # > A matrix is diagonalizable if and only if the dimension of every eigenspace is equal to the multiplicity of the corresponding eigenvalue as a root of the characteristic equation. # ### The fourth example # # &#9989; **<font color=red>Do this:</font>** Consider # $$ A = \begin{bmatrix}2& -1\\1& 2\end{bmatrix}.$$ # Can we find a matrix $C$ such that $C^{-1}AC$ is diagonal? # + nbgrader={"grade": true, "grade_id": "cell-3bc59d8f51537cae", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false} #Put your answer to the above question here. # - # --- # # <a name="The_Power_of_a_Matrix"></a> # ## 3. The Power of a Matrix # # * For a diagonalizable matrix $A$, we have $C^{-1}AC=D$. Then we have # $$A = C D C^{-1}$$ # * We have # $$A^2 = C D C^{-1} C D C^{-1} = C D^2 C^{-1}$$ # $$A^n = C D C^{-1} \dots C D C^{-1} = C D^n C^{-1}$$ # * Because the columns of $C$ are eigenvectors, so we can say that the eigenvectors for $A$ and $A^n$ are the same if $A$ is diagonalizable. # * If $x$ is an eigenvector of $A$ with the corresponding eigenvalue $\lambda$, then $x$ is also an eigenvector of $A^n$ with the corresponding eigenvalue $\lambda^n$. # Here are some libraries you may need to use # %matplotlib inline import numpy as np import sympy as sym import networkx as nx import matplotlib.pyplot as plt sym.init_printing(use_unicode=True) # ### Graph Random Walk # # * Define the following matrices: # * $I$ is the identity matrix # * $A$ is the adjacency matrix # * $D$ is diagonal matrix of degrees (number of edges connected to each node) # # $$W=\frac{1}{2}(I + AD^{-1})$$ # # * The **lazy random walk matrix**, $W$, takes a distribution vector of *stuff*, $p_{t}$, and diffuses it to its neighbors: # # $$p_{t+1}=Wp_{t}$$ # # * For some initial distribution of *stuff*, $p_{0}$, we can compute how much of it would be at each node at time, $t$, by powering $W$ as follows: # # $$p_{t}=W^{t}p_{0}$$ # # * Plugging in the above expression yields: # # $$p_{t}=\left( \frac{1}{2}(I+AD^{-1}) \right)^t p_{0}$$ # **<font color=red>DO THIS</font>**: Using matrix algebra, show that $\frac{1}{2}(I + AD^{-1})$ is **similar** to $I-\frac{1}{2}N$, where $N=D^{-\frac{1}{2}}(D-A)D^{-\frac{1}{2}}$ is the normalized graph Laplacian. # + [markdown] nbgrader={"grade": true, "grade_id": "cell-1a93e034adef3eb1", "locked": false, "points": 0, "schema_version": 3, "solution": true, "task": false} # **Your answer goes here** (follow along after attempting) # - # ### Random Walk on Barbell Graph # # To generate the barbell graph, run the following cell. # + n = 60 # number of nodes B = nx.Graph() # initialize graph ## initialize empty edge lists edge_list_complete_1 = [] edge_list_complete_2 = [] edge_list_path = [] ## generate node lists node_list_complete_1 = np.arange(int(n/3)) node_list_complete_2 = np.arange(int(2*n/3),n) node_list_path = np.arange(int(n/3)-1,int(2*n/3)) ## generate edge sets for barbell graph for u in node_list_complete_1: for v in np.arange(u+1,int(n/3)): edge_list_complete_1.append((u,v)) for u in node_list_complete_2: for v in np.arange(u+1,n): edge_list_complete_2.append((u,v)) for u in node_list_path: edge_list_path.append((u,u+1)) # G.remove_edges_from([(3,0),(5,7),(0,7),(3,5)]) ## add edges B.add_edges_from(edge_list_complete_1) B.add_edges_from(edge_list_complete_2) B.add_edges_from(edge_list_path) ## draw graph pos=nx.spring_layout(B) # positions for all nodes ### nodes nx.draw_networkx_nodes(B,pos, nodelist=list(node_list_complete_1), node_color='c', node_size=400, alpha=0.8) nx.draw_networkx_nodes(B,pos, nodelist=list(node_list_path), node_color='g', node_size=200, alpha=0.8) nx.draw_networkx_nodes(B,pos, nodelist=list(node_list_complete_2), node_color='b', node_size=400, alpha=0.8) ### edges nx.draw_networkx_edges(B,pos, edgelist=edge_list_complete_1, width=2,alpha=0.5,edge_color='c') nx.draw_networkx_edges(B,pos, edgelist=edge_list_path, width=3,alpha=0.5,edge_color='g') nx.draw_networkx_edges(B,pos, edgelist=edge_list_complete_2, width=2,alpha=0.5,edge_color='b') plt.axis('off') plt.show() # display # - # &#9989; **<font color=red>Do this</font>:** Generate the lazy random walk matrix, $W$, for the above graph. # + A = nx.adjacency_matrix(B) A = A.todense() d = np.sum(A,0) # Make a vector of the sums. D = np.diag(np.asarray(d)[0]) # + #Put your answer to the above question here. # + nbgrader={"grade": true, "grade_id": "cell-fb79da016761443e", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false} from answercheck import checkanswer checkanswer.matrix(W, "7af4a5b11892da6e1a605c8239b62093") # - # &#9989; **<font color=red>Do this</font>:** Compute the eigenvalues and eigenvectors of $W$. Make a diagonal matrix $J$ with the eigenvalues on the diagonal. Name the matrix of eigenvectors $V$ (each column is an eigenvector). # + #Put your answer to the above question here. # - # Now we make sure we constructed $V$ and $A$ correctly by double checking that $W = VJV^{-1}$ np.allclose(W, V*J*np.linalg.inv(V)) # &#9989; **<font color=red>Do this</font>:** Let your $p_{0}=[1,0,0,\ldots,0]$. Compute $p_{t}$ for $t=1,2,\ldots,100$, and plot $||v_{1}-p_{t}||_{1}$ versus $t$, where $v_{1}$ is the eigenvector associated with the largest eigenvalue $\lambda_{1}=1$ and whose sum equals 1. (**Note**: $||\cdot||_{1}$ may be computed using ```np.linalg.norm(v_1-p_t, 1)```.) # + nbgrader={"grade": true, "grade_id": "cell-9e691ac811c35e4d", "locked": false, "points": 5, "schema_version": 3, "solution": true, "task": false} #Put your answer to the above question here. # - # #### Compare to Complete Graph # # If you complete the above, do the same for a complete graph on the same number of nodes. # # &#9989; **<font color=red>Question</font>:** What do you notice about the graph that is different from that above? # + [markdown] nbgrader={"grade": true, "grade_id": "cell-9cadbdd3014757bc", "locked": false, "points": 5, "schema_version": 3, "solution": true, "task": false} # Put your answer to the above question here. # - # ---- # Written by Dr. Dirk Colbry, Michigan State University # <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-nc/4.0/88x31.png" /></a><br />This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International License</a>. # #
b8f16b221e2b4ae36c45ebf244e44fd11f0becdd
bgoldstone/Computer_Science_I
/Labs/9_movingCircle.py
4,975
3.90625
4
# 9_movingCircle.py - for CSI-102 Lab 9: More practice with Pygame # Adds colors and user interaction # # Name: Ben Goldstone # Date: 10/20/2020 #INITIALIZE: import pygame pygame.init() # Constants WIDTH = 800 HEIGHT = 600 BOX_SIZE = 100 HALF_BOX = BOX_SIZE // 2 SPEED = 5 # Color Constants RED = (255, 0, 0) GREEN = (0,255,0) BLUE = (0,0,255) CYAN = (0,255,255) MAGENTA = (255, 0, 255) YELLOW = (255,255,0) BLACK = (0,0,0) WHITE = (255,255,255) #BG Colors BG_COLOR = (200, 200, 200) def main() : #DISPLAY: screen = pygame.display.set_mode( (WIDTH, HEIGHT) ) pygame.display.set_caption("Ben Goldstone") #ENTITIES: # A solid color background background = pygame.Surface(screen.get_size()) background = background.convert() background.fill( BG_COLOR ) # A surface on which to draw our shape box = pygame.Surface( (BOX_SIZE, BOX_SIZE) ) # Size of box in pixels box = box.convert() box.fill( BG_COLOR ) # Draw a magenta circle on the box pygame.draw.circle(box, MAGENTA, (HALF_BOX, HALF_BOX), HALF_BOX, 10) #ACTION: #ASSIGN: clock = pygame.time.Clock() keepGoing = True # Set up initial box location and motion boxLeft = 0 boxTop = 200 dx = SPEED dy = 0 #LOOP: while keepGoing: # The Game Loop #TIME: clock.tick(30) # refresh screen this many times per second #EVENTS: for event in pygame.event.get(): if event.type == pygame.QUIT: # User closed the window keepGoing = False # On KEYDOWN, determine which key was pressed: elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q or event.key == pygame.K_ESCAPE: keepGoing = False elif event.key == pygame.K_r: pygame.draw.circle(box, RED, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_g: pygame.draw.circle(box, GREEN, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_b: pygame.draw.circle(box, BLUE, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_c: pygame.draw.circle(box, CYAN, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_m: pygame.draw.circle(box, MAGENTA, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_y: pygame.draw.circle(box, YELLOW, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_k: pygame.draw.circle(box, BLACK, (HALF_BOX, HALF_BOX), HALF_BOX, 10) elif event.key == pygame.K_w: pygame.draw.circle(box, WHITE, (HALF_BOX, HALF_BOX), HALF_BOX, 10) # Respond to arrow keys: elif event.key == pygame.K_RIGHT: # add speed rightwards dx += SPEED elif event.key == pygame.K_LEFT: # add speed leftwards dx -= SPEED elif event.key == pygame.K_UP: # add speed upwards dy -= SPEED elif event.key == pygame.K_DOWN: # add speed downwards dy += SPEED #if (dx !=0 or dy != 0) and event.type == pygame.MOUSEBUTTONDOWN and boxLeft < pygame.mouse.get_pos()[0] < boxLeft + BOX_SIZE and boxTop < pygame.mouse.get_pos()[1] < boxTop - BOX_SIZE: #print("Cprrect") elif event.type == pygame.MOUSEBUTTONDOWN: # Stop the box motion dx = 0 dy = 0 # Move box by changing its location based on current values of dx and dy boxLeft += dx boxTop += dy # Check to see if the box has exceeded any boundaries; if so, wrap around if boxLeft >= screen.get_width(): # If box has exceeded the right edge, boxLeft = -BOX_SIZE # move it back to just beyond the left edge elif boxLeft + BOX_SIZE <= 0: # If box has exceeded the left edge, boxLeft = screen.get_width() # move it back to just beyond the right edge if boxTop >= screen.get_height(): # If box has exceeded the right edge, boxTop = -BOX_SIZE # move it back to just beyond the left edge elif boxTop + BOX_SIZE <= 0: # If box has exceeded the left edge, boxTop = screen.get_height() # move it back to just beyond the right edge #REFRESH SCREEN: screen.blit(background, (0, 0)) # redraw the clean background to erase the old box position screen.blit(box, (boxLeft, boxTop)) # 'blit' the box at its new position pygame.display.flip() # swap the double-buffered screen # Start it running main() # Clean up after main() finishes pygame.quit()
6ea8200cd3d4cbb6003578e2dc0ffa8504e03a86
Jollyhrothgar/insight_interview_prep_2016a
/sql/data_sets/autos_regression/create_database.py
5,908
3.59375
4
#!/usr/bin/env python # This allows us to create a database engine, which is the layer # which talks to the database from sqlalchemy import create_engine # These tools let us check if a database exists, given an engine, or # create a database if no database exists, given an engine from sqlalchemy_utils import database_exists, create_database, drop_database # Here, we use sqlalchemy's built in types, which map to various database # types. from sqlalchemy import Column, Integer, String, Float # Used for deriving classes from the declarative_base class for ORM management. from sqlalchemy.ext.declarative import declarative_base # This actually lets us talk to, and update the database. from sqlalchemy.orm import sessionmaker import sys # Declaring A Mapping To an Object Representing the Table we are creating. # This is an otherwise normal python class, but it inherits attributes from # the declarative_base baseclass, which allow for automatic generation of # table schema for any relational database. Base = declarative_base() class Car(Base): __tablename__ = 'auto_mpg' # Note that String types do not need a length in PostgreSQL and SQLite # but we have to specify for MySQL car_id = Column(Integer,primary_key = True) # a unique integer, with 1:1 mapping to car_name mpg = Column(Float) cylinders = Column(Integer) displacement = Column(Float) horsepower = Column(Float) weight = Column(Float) acceleration = Column(Float) model_year = Column(Float) origin = Column(Integer) car_name = Column(String) def __repr__(self): return "<User(car_id='%s', mpg='%s', cylinders='%s',displacement='%s',horsepower='%s',weight='%s',acceleration='%s',model_year='%s',origin='%s',car_name='%s')>" % (self.car_id, self.mpg, self.cylinders, self.displacement, self.horsepower, self.weight, self.acceleration, self.model_year, self.origin, self.car_name) def load_data(filename): ''' Loads car values into a list of SQL Alchemy Car-type objects 1. mpg: continuous 2. cylinders: multi-valued discrete 3. displacement: continuous 4. horsepower: continuous 5. weight: continuous 6. acceleration: continuous 7. model year: multi-valued discrete 8. origin: multi-valued discrete 9. car name: string (unique for each instance) ''' sql_object_list = [] with open(filename,'r') as f: counter = 0 for line in f.readlines(): autos = {} tokens = line.split() car_instance = Car() car_instance.car_id = counter car_instance.mpg = tokens[0] car_instance.cylinders = int(tokens[1]) car_instance.displacement = float(tokens[2]) try: car_instance.horsepower = float(tokens[3]) except: car_instance.horsepower = None car_instance.weight = float(tokens[4]) car_instance.acceleration = float(tokens[5]) car_instance.model_year = int(tokens[6]) car_instance.origin = int(tokens[7]) car_instance.car_name = ' '.join(tokens[8:]) counter += 1 sql_object_list.append(car_instance) print 'loaded',len(sql_object_list),'entries' return sql_object_list def create_db(username,dbname,dbpassword): ''' Returns a tuple (<bool>,database_engine_handle), such that the user can check to see if the database was created sucessfully, and if so, then access th sql_alchemy engine via the database_engine_handle ''' # Here, we're using postgres, but sqlalchemy can connect to other things too. engine = create_engine('postgres://%s:%s@localhost/%s'%(username,dbpassword,dbname)) print "Connecting to",engine.url if not database_exists(engine.url): create_database(engine.url) else: drop_database(engine.url) create_database(engine.url) database_exists_check = database_exists(engine.url) print "Database created successfully?:",database_exists_check return (database_exists_check,engine) def main(): print 'loading data' this_name = sys.argv[0] args = sys.argv[1:] if len(args) != 2: print "usage is:",this_name,"--read_file <filename>" sys.exit(1) elif args[0] != '--read_file' : print "usage is:",this_name,"--read_file <filename>" sys.exit(1) in_file = args[1] engine_tuple = create_db('postgres','auto_mpg','simple') if engine_tuple[0] == False: print 'Database was not created successfully, so no data will be loaded.' sys.exit(1) # Okay, if we made it to here, we now have an active database engine, which # is a layer between the ORM (SQLAlchemy) and the database. We can now use # the table meta-data which is programmed into the declarative class, to # actually create the database. engine = engine_tuple[1] # Create a table Base.metadata.create_all(engine) # Load the data into the derived sql object class data = load_data(in_file) # Create the session object Session = sessionmaker() # attach the session object to our engine Session.configure(bind=engine) # create a handle for the configured session session = Session() # add the new or updated data to the session (we can do a lot more # with a session besides adding and deleting data). For example, session # is a local instance of data, which can be maniuplated and queried without # actually talking to the database. session.add_all(data) # Now, once we've made changes or done our analysis, and if we want these # changes to be reflected in the SQL database, we can commit these changes # to the database. session.commit() if __name__ == '__main__': main()
6f2aa5b377fda5306fb6105d6c1430a615fd243c
NetSecLife/Random-Code
/abc-news-scraper.py
1,333
3.71875
4
from bs4 import BeautifulSoup import urllib.request def scrape_headlines(soup): #Constrains to the headline section headlines = soup.find("ol") #For loop through headlines for heading in headlines: #Get rid of whitespace, then collect the data if heading == "\n": continue headline = heading.find("a").getText() description = heading.find("p").getText() for z in heading.find_all('a', href=True): url = (z['href']) #Pretty output Headline = "Headline: " + headline + "." Description = "Description: " + description URL = "URL: http://www.abc.net.au" + url print(Headline) print(Description) print(URL + "\n") def main(): #Open website and assign the source code to html with urllib.request.urlopen('http://www.abc.net.au/news/') as response: html = response.read() #Setup soup variable for harvesting soup = BeautifulSoup(html, 'html.parser') scrape_headlines(soup) if __name__ == '__main__': main() #Logic flow. #Open site with urllib #Assign site code to html variable #Soup the html #Constrain soup to the first <ol> tags #For loop #Gather the headline #Gather the description #Gather the url #Add global abc site url to url variable #Put together and output
ddc6a5e89b4af2f7557b18037549cdf56b4bf979
reashiny/python.
/Python_hunter/Employees.py
1,823
3.921875
4
import time import sys #f name #l name #age #emp id #mail id em_list = [] class employee: def __init__(self,f_name,l_name,age,Emp_id): self.Attendance = True self.First_name = f_name self.Last_name = l_name self.Name = self.First_name + self.Last_name self.Age = age self.Employee_id = Emp_id self.mail_id = self.First_name + self.Last_name + "@company.com" def Create_Employee(): f_name = input("Enter First Name:") l_name = input("Enter Last Name:") age = input("Enter Age:") Employee_code = input("Enter Employee code:") emp_obj = employee(f_name,l_name,age,Employee_code) return emp_obj def View_Employee_Details(): emp_code = input("Enter Your Employee Code:") for obj in em_list: if emp_code == obj.Employee_id: print("Employee Name: {}".format(obj.Name)) print("Employee Age : {}".format(obj.Age)) def Attendance_Details(): emp_code = input("Enter Your Employee Code:") for obj in em_list: if emp_code == obj.Employee_id: if obj.Attendance: print("Employee Name : {}".format(obj.Name)) print("In-Time :" + time.ctime()) obj.Attendance = False else: print("Employee Name : {}".format(obj.Name)) print("Out-Time :" + time.ctime()) obj.Attendance = True while True: print("Enter 1 For New Employee Details:") print("Enter 2 To View Employee Details:") print("Enter 3 For Attendance:") option = int(input()) if option == 1: em_list.append(Create_Employee()) elif option == 2: View_Employee_Details() elif option == 3: Attendance_Details() else: print("Invalid Input!")
7dfdde783072cdfc64ebb9b5bfe13549e43e0dc7
esracelik/openstack-review-dashboard
/reviewSearcher/nonalnumops/convertHex.py
879
3.578125
4
def convertNonAlNumtoHex(line): cline = "" if not line.isalnum(): i = 0 while i < len(line): c = line[i] cp = line[i-1] if i > 0 else None if not c.isalnum(): if c == ' ': # SPACE cline += "+" elif c.encode("hex").upper() == "0A": # NEW LINE None # do nothing elif c == '-': cline += c elif c == '&': cline += c elif c == '\\': None # do nothing elif c == '=' and cp is not None and cp == '\\': cline += c else: cline += "%"+c.encode("hex").upper() else: cline += c i += 1 else: cline = line return cline
616f9c7c30e32b71a963efaf84552fd835f707f1
nikhilbansal064/pyvengers
/word_counter.py
1,620
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 3 22:13:45 2018 @author: Nikhil Bansal Here we are going to create a word counter. * steps - 1. We are gointn to screap a web page to get words. """ import requests from bs4 import BeautifulSoup import re import operator # This method is going to give us word list def get_words(url): word_list = [] # get whole html code in text format in source_code source_code = requests.get(url).text soup = BeautifulSoup(source_code, "lxml") # find all titles in source code for line in soup.findAll("a", {"class" : "cellMainLink"}): # strip html code form line title = line.string # used re(regex) module to split title with multiple delimeters. # use escape character with "." words = re.split('-|\.', title.lower()) word_list.extend(words) return word_list # This method will take word list and return dictionary with words and their frequency. def calculate_freq(words): freq_table = {} #check if word is already in dictonary for word in words: if word in freq_table: freq_table[word] += 1 else: freq_table[word] = 1 #sort dictonary according to key sorted_table = sorted(freq_table.items(),key=operator.itemgetter(0)) return sorted_table url = "https://kickass.unblocked.lat/tv/" word_count = calculate_freq(get_words(url)) #display word count for key, value in word_count: print(key, value)
f90400793c2c502a8cd21c2dc90a3cce8c8d3dd3
Frankiee/leetcode
/dp/2d/562_longest_line_of_consecutive_one_in_matrix.py
1,676
3.6875
4
# [2D-DP] # https://leetcode.com/problems/longest-line-of-consecutive-one-in-matrix/ # 562. Longest Line of Consecutive One in Matrix # History: # Google # 1. # Mar 26, 2020 # Given a 01 matrix M, find the longest line of consecutive one in the matrix. The line could be # horizontal, vertical, diagonal or anti-diagonal. # Example: # Input: # [[0,1,1,0], # [0,1,1,0], # [0,0,0,1]] # Output: 3 # Hint: The number of elements in the given matrix will not exceed 10,000. class Solution(object): def longestLine(self, M): """ :type M: List[List[int]] :rtype: int """ if not M or not M[0]: return 0 # horizontal, vertical, diagonal or anti-diagonal dp = [[[0] * 4 for _ in range(len(M[0]))] for _ in range(len(M))] ret = 0 for r in range(len(M)): for c in range(len(M[0])): if M[r][c] == 1: if c == 0: dp[r][c][0] = 1 else: dp[r][c][0] = dp[r][c - 1][0] + 1 if r == 0: dp[r][c][1] = 1 else: dp[r][c][1] = dp[r - 1][c][1] + 1 if r > 0 and c > 0: dp[r][c][2] = dp[r - 1][c - 1][2] + 1 else: dp[r][c][2] = 1 if r > 0 and c < len(M[0]) - 1: dp[r][c][3] = dp[r - 1][c + 1][3] + 1 else: dp[r][c][3] = 1 ret = max(ret, dp[r][c][0], dp[r][c][1], dp[r][c][2], dp[r][c][3]) return ret
03b1881a6b2d6b3cc9bf0ef654d1895ef4fee0a5
FlackoJodye1/thvisa
/py_learning/demo_oo_with_context_interhited.py
1,971
3.640625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 13 18:34:45 2019 @author: thomas why context managers? see https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/ TL;DR: "Essentially, any object that needs to have close called on it after use is (or should be) a context manager." this defaults init works: https://stackoverflow.com/questions/8073726/python-inheritance-and-default-values-in-init this defaults init format didn't: https://scikit-rf.readthedocs.io/en/latest/_modules/skrf/vi/vna/keysight_pna.html """ class dummyc(object): # to be overwritten by children firstnamedef="" lastnamedef="" def __init__(self, firstname=firstnamedef, lastname=lastnamedef): print("aa") self.firstname=firstname self.lastname=lastname self.report("created") def __del__(self): self.report("delete called, session ended") #return def __enter__(self): self.report("with-context entered") return self # unless this happens, tanya dies before reporting "locked and loaded" def __exit__(self, exc_type, exc_value, tb): self.report("with-context exited") self.__del__() # unless this happens, session doesn't get exited #return def report(self, st): print("{} {} reports: {}".format(self.firstname, self.lastname, st)) def be_silly(self): raise Exception("pink fluffy unicorns riding on rainbows") class herbert(dummyc): firstnamedef="Herbert" lastnamedef="Dummyuser" def __init__(self, firstname=firstnamedef, lastname=lastnamedef): super(herbert, self).__init__(firstname="Herbert", lastname="Dummyuser") # call parent init ### module test ### if __name__ == '__main__': # test if called as executable, not as library #demo(herbfail=1) with herbert() as herb: herb.report("bananaa")
c24ffd63f9670686ee8441f960f0761d8b329d9d
MartinaLima/Python
/exercicios_python_brasil/estrutura_repeticao/40_acidentes_transito.py
1,824
3.828125
4
print('\033[1m * ACIDENTES DE TRÂNSITO - 1999 *\033[m') tot_cidades = 0 soma_acidentes = 0 cidades_peq = 0 soma_veiculos = 0 for tot_cidades in range(5): tot_cidades += 1 codigo = int(input(f'Código cidade {tot_cidades}: ')) while codigo <= 0: print('CÓDIGO INVÁLIDO!!!') codigo = int(input(f'Código cidade {tot_cidades}: ')) veiculos = int(input('Veículos de passeio: ')) acidentes = int(input('Acidentes com vítimas: ')) print('-'*35) if veiculos <= 2000: soma_acidentes += acidentes cidades_peq += 1 if tot_cidades == 1: mais_acidentes = acidentes cidade_mais = codigo menos_acidentes = acidentes cidade_menos = codigo else: if acidentes > mais_acidentes: mais_acidentes = acidentes cidade_mais = codigo elif acidentes == mais_acidentes: cidade_mais = 'há mais de uma cidade com o maior índice de acidentes!' if acidentes < menos_acidentes: menos_acidentes = acidentes cidade_menos = codigo elif acidentes == menos_acidentes: cidade_menos = 'há mais de uma cidade com o menor índice de acidentes!' soma_veiculos += veiculos media_veiculos = soma_veiculos/tot_cidades media_acidentes = soma_acidentes / cidades_peq print('{:^35}'.format('RESULTADOS DA PESQUISA')) print('-' * 35) print(f'MÉDIA GERAL DE VEÍCULOS: {media_veiculos:.2f}') print('MAIOR ÍNDICE DE ACIDENTES:') print(f'* Cidade: {cidade_mais}') print(f'* Acidentes: {mais_acidentes}') print('MENOR ÍNDICE DE ACIDENTES:') print(f'* Cidade: {cidade_menos}') print(f'* Acidentes: {menos_acidentes}') print('MÉDIA ACIDENTES:') print(f'* Cidades com até 2000 veículos: {media_acidentes:.2f}')
038b8f3cfa851a2b081b3573be0a345acdab5f49
padalor/ReadAndWrite
/debugReadWriteDrillsV1.py
2,066
4.15625
4
''' The following functions have problems that keep them from completing the task that they have to do. All the problems are either Logical or Syntactical errors with READ/WRITE. Focus on the reading and writing and find the problems with the READ/WRITE. The number of errors are as follows: readSingle: 3 readAll: 3 writeStuff: 3 writeDouble: 3 writeAppend: 3 ''' ''' This function takes a fileName and reads then prints the first line of the file. ''' def readSingle(fileName): f = open("fileName", 'r') string = f.readline() #Prints the read data return string print(string.strip()) readSingle("fileOne.txt") f.close() ''' This function takes a fileName and reads and prints ALL of the lines of the file. ''' def readAll(fileName): file = open(fileName, 'r') stringList = fileName.readline() fileName.close() #Prints all the read data x = 0 while(x < len(stringList)): print(stringList[x].strip()) x += 1 return stringList readAll("fileOne.txt") ''' This function takes a fileName and some content and writes the content on the file. ''' def writeStuff(fileName, content): f = open("file", 'r') f.write(content) f.close() print("DONE") return writeStuff("fileTwo.txt", "This is for the third function.") ''' This function takes a fileName and two pieces of content and writes them in the file. ''' def writeDouble(fileName, content, contentTwo): f.close("fileName", 'w') f.wrte(content) f.write(contentTwo) print("DONE") return fileName.writeDouble("fileThree.txt", "This is for the forth function.", "This is the second sentence.") ''' This function takes a fileName and content and appends the content to the end of the file. ''' def writeAppend(fileName, append): f = open(fileName, '') f.write(append) f.close() print("DONE") return writeAppend("fileThree.txt", "This should be appended to the end.")
65cb2cd10efe8959462e1e86361584d060147c3d
bhupendrabhoir/PYTHON-3
/12. GUI/CALCULATOR.py
997
3.6875
4
from tkinter import * def add(): num1=int(e1.get()) num2=int(e2.get()) result=num1+num2 l3["text"]=result def sub(): num1=int(e1.get()) num2=int(e2.get()) result=num1-num2 l3["text"]=result def mul(): num1=int(e1.get()) num2=int(e2.get()) result=num1*num2 l3["text"]=result def div(): num1=int(e1.get()) num2=int(e2.get()) result=num1/num2 l3["text"]=result app = Tk() app.geometry("1000x500") l1=Label(app,text="Num1") l2=Label(app,text="Num2") l3=Label(app) e1=Entry(app) e2=Entry(app) b1=Button(app,text="ADD",command=add) b2=Button(app,text="SUB",command=sub) b3=Button(app,text="MUL",command=mul) b4=Button(app,text="DIV",command=div) l1.place(x=40,y=40) l2.place(x=40,y=70) e1.place(x=120,y=40,width=200) e2.place(x=120,y=70,width=200) b1.place(x=40,y=110) b2.place(x=120,y=110) b3.place(x=200,y=110) b4.place(x=280,y=110) l3.place(x=50,y=150) app.mainloop()
e79fadf2e7e56e7bacefcdf582aaad4e019a495e
liulxin/python3-demos
/micr/14.func.py
334
4.125
4
first_name = input('enter your first name: ') last_name = input('enter your last name: ') def initial_name(name, force_uppercase = True): if force_uppercase: initial = name[0:1].upper() else: initial = name[0:1] return initial print(f'Your initials are: {initial_name(first_name)} {initial_name(last_name)}')
4a6c0462f88a7e6bc558b269bca1950babbcabf7
Harsh2705/bankaccount
/bank1.py
780
4
4
def account(): print("Details of user") print('Name:','Harsh Rana') print('Account_Number:','300084176114566') print('Aaadhar_Number:','78480884777') print('Phone_Number:','9027097675') print('Category:','General') def total_amount(): balance=17000 print("The total balance of your account is:",balance) def deposit_withdrw(): balance=17000 amount=input("Enter the amount when you deposit:") total=balance+amount print("After deposit the",amount,"your total balane is:",total) amount=input("How many amount you withdrw:") if total>=amount: total-=amount print('After withdrw you total balance is:',total) else: print("you have not money") account() total_amount() deposit_withdrw()
b15c3f65c3226546ccfa75c7a518d00a0a04e2ba
jameswmccarty/CryptoToyUtils
/HMAC_Timing_Attack_Client.py
1,977
3.53125
4
#!/usr/bin/python import urllib import time """ There is a server with a timing leak. We want to submit a valid input (filename, signature), but we don't know the signature. i.e. http://localhost:8080/?filename=foo&signature=46b4ec586117154dacd49d664e5d63fdc88efb51 Goal: Determine a valid signature for a given filename by exploiting the timing leak. Server returns 'HTTP 500' for an invalid signature. Server returns 'HTTP 200' for a valid signature. Keys that are more correct take longer to compare. Start with a base key. Try combinations for the first byte. See which one took the longest. Add that value to our key. Repeat until HTTP 200 is recieved from server. Update: Perform several successive tests with each key value, and sum the results. We expect that the timing difference will be very small, so take repeat samples to magnify the error. """ servername = 'localhost' port = "8080" protocol = 'http' def build_url(filename, usig): out = protocol + '://' out += servername if port != "80": out += ':' + port out += '/' out += '?filename=' + filename out += '&signature=' + usig return out def pad(string): return string + "0" * (40 - len(string)) def solve_sig(filename): sig = '' valid = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] best_time = 0.00 MAXTRIALS = 10 # multiple tests (since timing error is small) while True: best = '' for char in valid: trial = sig + char print "Testing sig: " + pad(trial) delta = 0.0 for i in xrange(MAXTRIALS): start = time.time() status = urllib.urlopen(build_url(filename,pad(trial))) stop = time.time() delta += stop-start #print delta code = status.getcode() if code == None: print "Unknown Server Error." exit() if code == 200: return trial if code == 500: if delta >= best_time: best_time = delta best = char sig += best if __name__ == "__main__": print solve_sig("foo")
3e0412bffb30e428b954a6598f0af58af461f7af
Maltimore/Reinforcement_Learning_BCCN
/testfuncs.py
2,696
3.640625
4
import matplotlib.pyplot as plt import numpy as np def is_between(a, b, c): a[0], a[1] = round(a[0], 3), round(a[1], 3) b[0], b[1] = round(b[0], 3), round(b[1], 3) c[0], c[1] = round(c[0], 3), round(c[1], 3) print("the three dots given to is_between are: ") print(a) print(b) print(c) print((b[0] - a[0]) * (c[1] - a[1])) print((c[0] - a[0]) * (b[1] - a[1])) print((np.isclose((b[0] - a[0]) * (c[1] - a[1]), (c[0] - a[0]) * (b[1] - a[1]))), \ (((a[0] <= c[0]) and (b[0] >= c[0])) or ((a[0] >= c[0]) and (b[0] <= c[0]))), \ (((a[1] <= c[1]) and (b[1] >= c[1])) or ((a[1] >= c[1]) and (b[1] <= c[1])))) return (np.isclose((b[0] - a[0]) * (c[1] - a[1]), (c[0] - a[0]) * (b[1] - a[1]), .001, .001) and (((a[0] <= c[0]) and (b[0] >= c[0])) or ((a[0] >= c[0]) and (b[0] <= c[0]))) and (((a[1] <= c[1]) and (b[1] >= c[1])) or ((a[1] >= c[1]) and (b[1] <= c[1])))) # initialize values q0 = [ 59.209, 0.209] q1 = [ 62.774, 0.208] def intersection(q0, q1, p0, p1): dy = q0[1] - p0[1] dx = q0[0] - p0[0] lhs0 = [-dy, dx] rhs0 = p0[1] * dx - dy * p0[0] dy = q1[1] - p1[1] dx = q1[0] - p1[0] lhs1 = [-dy, dx] rhs1 = p1[1] * dx - dy * p1[0] a = np.array([lhs0, lhs1]) b = np.array([rhs0, rhs1]) try: px = np.linalg.solve(a, b) except: px = np.array([np.nan, np.nan]) return px startpoints = np.array([[0, 60], [0, 50], [60, 50], [50, 0], [0, 50], [50, 0], [60, 0], [110, 50]]) endpoints = np.array([[110, 60], [50, 50], [110, 50], [60, 0], [0, 60], [50, 50], [60, 50], [110, 60]]) for i in np.arange(8): plt.plot([startpoints[i,0], endpoints[i,0]],[startpoints[i,1], endpoints[i,1]], label="nr " + str(i)) px = intersection(startpoints[i,:], q0, endpoints[i,:], q1) print("index is: " + str(i)) if is_between(startpoints[i,:], endpoints[i,:], px) and is_between(q0, q1, px): print("The line sected is number " + str(i)) plt.scatter(px[0], px[1]) plt.plot([q0[0], q1[0]],[q0[1],q1[1]]) plt.xlim([-10, 150]) plt.ylim([-10, 70]) plt.legend() vector_a = np.array([7,7], dtype=float) vector_b = np.array([.5,.5], dtype=float) #vector_a /= np.linalg.norm(vector_a) #vector_b /= np.linalg.norm(vector_b) print(np.dot(vector_a, vector_b))
0be210aba3242187e9406502697423d95edb1051
epmskorenkyi/python-training
/lesson04/task06.py
472
3.53125
4
""" Task06 Module ============= Updates a current date and time in a file's first line (stored in the first 50 characters). A file shall be specified as a first argument. Other file content than first 50 characters shall not be modified. """ import time, sys from time import strftime if len(sys.argv) > 1: file = open(sys.argv[1], 'r+') time_str = strftime('%d %b %Y %H:%M:%S', time.localtime(time.time())) file.write(time_str.ljust(50)) file.close()
1b16df03bfb5d515c31ae62ddfa3e7184190e3a3
lminervino18/HangmanGame
/Hangman Game/player.py
1,612
3.609375
4
from constants import LIVES, WINNING_POINTS class Player: def __init__(self, name): self.name = name self.rounds_won = 0 self.letters_tried = 0 self.lives = LIVES self.actual_word = [] self.points = 0 def get_points(self): #Return the actual points return self.points def win_point(self): #Increase the points self.points += 1 def get_if_player_won(self): #Return if the player has 3 points return self.points == WINNING_POINTS def restart_actual_word(self): #Restart the actual word self.actual_word = [] def add_letter(self, letter): #Add a letter in the actual word self.actual_word.append(letter) def pop_letter(self): #Pop the last letter in the actual word self.actual_word.pop() def get_actual_word(self): #Return an string for the actual word return "".join(self.actual_word) def get_lives(self): #Return the actual lives return self.lives def restart_lives(self): #Restart the lives to the initial status self.lives = 5 def lose_live(self): #Decrease the lives if self.lives >0: self.lives -= 1 def is_alive(self): #Return if the player is alive return self.lives > 0 def set_name(self, name): #Set the name of the player self.name = name def __str__(self): #Return the name return f'{self.name.upper()}'
36bf0194b5201de3fe38630cef4d2f3f860e8c59
prueba-entreeinement/hola-mundo
/sqlZAAU.py
1,512
3.59375
4
import sqlite3 as sq #trigger clausula when. #condiciona la aparicion del trigger, sin necesidad del uso de select case. conexion = sq.connect("bd.db") cur = conexion.cursor() cur.executescript(""" drop table if exists usuarios; drop table if exists clavesanteriores; create table usuarios( nombre text primary key, clave text ); create table clavesanteriores( nombre text, clave text ); """) #notese el condicionador con when en el disparador. cur.executescript(""" drop trigger if exists disparador_claves_anteriores; create trigger disparador_claves_anteriores before update on usuarios when new.clave<>old.clave begin insert into clavesanteriores values(old.nombre, old.clave); end; """) conexion.commit() def imprimir(sql_ins): cursor = cur.execute(sql_ins) for fila in cursor.fetchall(): print(fila) print("\nInsertamos a un usuario:") cur.execute("insert into usuarios values ('Pepe', 'UruguayChilli25')") conexion.commit() def ver_tablas(): print("\nUsuarios:") imprimir("select * from usuarios") print("\nClaves Anteriores:") imprimir("select * from clavesanteriores") ver_tablas() print("\nActualizamos la clave:") cur.execute("update usuarios set clave='UUEEchojo34' where nombre='Pepe'") ver_tablas() print("\nActualizamos la clave, con el mismo valor que tenía:") cur.execute("update usuarios set clave='UUEEchojo34' where nombre='Pepe'") ver_tablas() print("\nNotese que la inserción no se realizo, ya que la clave nueva es igual a la vieja.") conexion.close()
72c6bc9ad791e405d19e2e04d356055e5313051d
ccnelson/Python
/tkinter/clock_tick.py
647
3.578125
4
## this calls itself recursivly ## that is BAD import tkinter as tk import time root = tk.Tk() time1 = '' clock = tk.Label(root, font=('times', 20, 'bold'), bg='green') clock.pack(fill=tk.BOTH, expand=1) def tick(): global time1 # get the current local time from the PC time2 = time.strftime('%H:%M:%S') # if time string has changed, update it if time2 != time1: time1 = time2 clock.config(text=time2) # calls itself every 200 milliseconds # to update the time display as needed # could use >200 ms, but display gets jerky clock.after(200, tick) tick() root.mainloop()
20edf597c6271bc125ac27ef5d0d947f3472a5d5
noorulameenkm/DataStructuresAlgorithms
/LeetCode/30-day-challenge/June/june 8th - june 14th/isSubSequence.py
421
3.609375
4
class Solution: def isSubsequence(self, s, t): if len(s) > len(t): return False if len(s) == 0: return True if s[0] == t[0]: return self.isSubsequence(s[1:], t[1:]) return self.isSubsequence(s, t[1:]) print(f'Is subsequence {Solution().isSubsequence("axc","ahbgdc")}') print(f'Is subsequence {Solution().isSubsequence("abc","ahbgdc")}')
42dee6c19e990ee77a6622c17fc73d647983fadc
alexei89/Python3
/ex12_remove_selected elemetns_list.py
388
3.921875
4
#23 feb 2017 #Write a Python program to print a specified list after removing the # 0th, 2nd, 4th and 5th elements. lista = ['red', 'green', 'white', 'black', 'pink', 'yellow'] def remove_elements(mylist): editedlist = [] for i in range(0,len(mylist)-1): if i not in (0,4,5): editedlist.append(mylist[i]) return editedlist print(remove_elements(lista))
9a2c67938efba1d4ab0c353577d4bc15b91bcc5f
niphadkarneha/SummerCamp
/Python Scripts/Intro to prob.py
1,386
3.875
4
# import numpy as np total_tosses = 30 num_heads = 24 prob_head = 0.5 #0 is tail. 1 is heads. Generate one experiment experiment = np.random.randint(0,2,total_tosses) print ("Data of the Experiment:", experiment) #Find the number of heads print ("Heads in the Experiment:", experiment[experiment==1]) #This will give all the heads in the array head_count = experiment[experiment==1].shape[0] #This will get the count of heads in the array print ("Number of heads in the experiment:", head_count) #Now, the above experiment needs to be repeated 100 times. Let's write a function and put the above code in a loop def coin_toss_experiment(times_to_repeat): head_count = np.empty([times_to_repeat,1], dtype=int) for times in np.arange(times_to_repeat): experiment = np.random.randint(0,2,total_tosses) head_count[times] = experiment[experiment==1].shape[0] return head_count head_count = coin_toss_experiment(100) head_count[:10] print ("Dimensions:", head_count.shape, "\n","Type of object:", type(head_count)) #Number of times the experiment returned 24 heads. head_count[head_count>=24] print ("No of times experiment returned 24 heads or more:", head_count[head_count>=24].shape[0]) print ("% of times with 24 or more heads: ", head_count[head_count>=24].shape[0]/float(head_count.shape[0])*100)
0bd9c0926157bd1de0eeed5f15a31883ddf69f90
jmetzz/algorithms-challenges-lab-python
/src/challenges/problems/dynamic_prog/checkerboard.py
3,899
4.15625
4
"""Consider a checkerboard with n × n squares and a cost function c(i, j) which returns a cost associated with square (i,j) (i being the row, j being the column). Let us say there was a checker that could start at any square on the first rank (i.e., row) and you wanted to know the shortest path (the sum of the minimum costs at each visited rank) to get to the last rank; assuming the checker could move only diagonally left forward, diagonally right forward, or straight forward. That is, a checker on (1,3) can move to (2,2), (2,3) or (2,4). For instance (on a 5 × 5 checkerboard), | 6 7 4 7 8 | | 7 6 1 1 4 | | 3 5 7 8 2 | | – 6 7 0 – | | – – *5* – – | This problem is expressed by the following recursion: for j < 1 or j > n: q(i, j) = ∞ for i = 1: q(i, j) = c(i, j) otherwise: q(i, j) = min( minCost(i-1, j-1), minCost(i-1, j), minCost(i-1, j+1) ) + c(i, j) """ import numpy as np INF = 999 cost_table_recursive = np.full((5, 5), 0) def checker_cost_recursive(n, costs, i, j): """Recursively computes the path cost. Like the naive implementation of the Fibonacci method, this method is horribly slow because it too exhibits the overlapping sub-problems attribute. That is, it recomputes the same path costs over and over. The actual path is not formed in this method. """ if j < 0 or j >= n: return INF if i == n - 1: return costs[i][j] else: value = ( min( checker_cost_recursive(n, costs, i + 1, j - 1), checker_cost_recursive(n, costs, i + 1, j), checker_cost_recursive(n, costs, i + 1, j + 1), ) + costs[i][j] ) cost_table_recursive[i, j] = value return value def checker_cost_dp(costs): n, m = costs.shape cost_table = np.full( (n, m + 2), INF ) # two extra columns to handle the borders of matrix costs path_table = np.full((n, m), -1, dtype=int) # The acummulated cost for all elements # in the first row of costs is its own cost for i in range(m): cost_table[0, i + 1] = costs[0, i] for l in range(1, n): for c in range(1, m + 1): values = [ cost_table[l - 1, c - 1], cost_table[l - 1, c], cost_table[l - 1, c + 1], ] best = np.argmin(values) cost_table[l, c] = values[best] + costs[l, c - 1] path_table[l, c - 1] = c - 1 + best - 1 # drop the extra columns in the cost_table array cost_table = cost_table[:, 1:-1] return cost_table, path_table, np.argmin(cost_table[n - 1]) def build_path(path_table, row, column): if row == 1: return f"{path_table[row, column]}" else: predecessor = build_path(path_table, row - 1, path_table[row, column]) return f"{predecessor} -> {path_table[row, column]}" def solution_path(table, row, column): predecessor = build_path(table, row, column) return f"{predecessor} -> {column}" if __name__ == "__main__": n = 5 costs = np.array( [ [INF, INF, 5, INF, INF], [INF, 6, 7, 0, INF], [3, 5, 7, 8, 2], [7, 6, 1, 1, 4], [6, 7, 4, 7, 8], ] ) print("Recursive solution") print(f"Minimum cost: {checker_cost_recursive(costs.shape[0], costs, 0, 2)}") print("Cummulative costs:") print(cost_table_recursive) print("\n----------------------------") print("Dynamic programming solution\n") table, paths, solution = checker_cost_dp(np.array(costs)) path = solution_path(paths, table.shape[0] - 1, solution) print(f"Minumum cost: {table[-1][solution]}") print(f"Solution: {path}") print("Cummulative costs:") print(table) print("Paths table:") print(paths)
01ea26b9e1f850687fb06a01bc661ed19f9d2a55
juandp333/mi_primer_programa
/Calculadora.py
903
4.25
4
# Calculadora debe preguntar al usuario que operacion deseas realizar y dos numeros a calcular primer_numero = int(input("Hola, ¿Cual es el primer numero a calcular?")) print("ok sera {}".format(primer_numero)) operacion_realizar = input("¿Que operacion deseas ralizar? (Sumar, Restar, Multiplicacion o Dividir)").upper() print(operacion_realizar) segundo_numero = int(input("Cual es el segundo numero a calcular?")) print("Esta bien {}".format(segundo_numero)) if operacion_realizar == "SUMAR": print("El resultado es {}".format(primer_numero + segundo_numero)) elif operacion_realizar == "RESTAR": print("El resultado es {}".format(primer_numero - segundo_numero)) elif operacion_realizar == "MULTIPLICAR": print("El resultado es {}".format(primer_numero * segundo_numero)) elif operacion_realizar == "DIVIDIR": print("El resultado es {}".format(primer_numero / segundo_numero))
c911884fdb9f42cc9ce379c01b4999a62c5b8691
Sean-McGinty/ECS_32A
/HW2/divide.py
456
4.375
4
#divide.py #ECS32A # #Integer Division Calculator Dividend=int(input("Enter a number:")) #User inputs Dividend and Saves as a Variable Divisor=int(input("Enter a number to divide that by:")) #User inputs Divisor and Saves as a Variable quotient=Dividend//Divisor #Performs Floored Division of Dividend/Divisor remainder=Dividend%Divisor #Calculatates Remainder after Division print(Dividend,"divided by",Divisor,"is",quotient,"with",remainder,"remaining")
d0be52bef7506093b0d0d08b7dc9837a8a1d6793
yadubhushanreddy/Python-Programs
/second_largest_number.py
572
4.15625
4
no_of_elements = int(input("Enter no of elements : ")) input_list = [] max_number, second_max_number = 0, 0 for number in range(no_of_elements): input_list.append(int(input("Enter any number : "))) for element in range(0, len(input_list)): #12 3 24 32 25 if max_number < input_list[element]: second_max_number = max_number max_number = input_list[element] elif second_max_number < input_list[element]: second_max_number = input_list[element] print("Maximum number = ", max_number) print("Second maximum number = ", second_max_number)
e13baf963e3501d402f7280514b8a4b7e8203224
xueyc1f/kube
/utils/utils.py
737
3.546875
4
def check_key(key, data, default=None): """ 验证data.keys()是否包含key,如果是则返回data[key],否则返回None or default :param key: string or int ... :param data: dict or list ... :param default: mixed :return: mixed """ if isinstance(data, dict): if key in data.keys(): return data[key] else: return (None, default)[default is not None] return None def check_key_raise(key, data): if isinstance(data, dict): if key in data.keys(): return data[key] else: raise Exception("'" + data.__str__() + "'object has no attribute'" + key + "'") raise Exception("'" + data.__str__ + "'object is not dict")
d940d4a29914cd32c891e187186aa9f12aa8caac
BishwasWagle/PythonAdvanced
/RegEX/regexp.py
418
3.765625
4
import re import argparse def Main(): line = "Regular expressions are awesome!!" matchResult = re.match('are', line , re.R|re.I) if matchResult: print("Match found:" +matchresult.group()) else: print("No match found") searchResult = re.search('are', line , re.R|re.I) if searchResult: print("Search found:" +searchResult.group()) else: print("Nothing was found") if __name__ == "__main__": Main()
01cb3ae6e2604579121af2ec3852917a51fc9339
jskim1124kr/Gradient_Descents
/GradientDescent.py
1,009
3.59375
4
from numpy import * from matplotlib import pyplot as plt data = genfromtxt('data.csv',delimiter=',') m = len(data) def load_data(data): x_data = [] y_data = [] for i in range(m): x = data[i,0] y = data[i,1] x_data.append(x) y_data.append(y) return x_data, y_data def plot_line(y, data_points): x_values = [i for i in range(int(min(data_points))-1, int(max(data_points))+2)] y_values = [y(x) for x in x_values] plt.plot(x_values, y_values, 'r') x,y = load_data(data) learning_late = 0.01 steps = 1000 W = 0 b = 0 H = lambda x : (W*x) + b def cost_function(x,y): for i in range(m): theta0 = 0 theta1 = 0 theta0 += H(x[i]) - y[i] theta1 += (H(x[i]) - y[i]) * x[i] return theta0/m , theta1/m for i in range(steps): c1,c2 = cost_function(x,y) W = W - (learning_late * c1) b = b - (learning_late * c2) print('W : {} / b : {}'.format(W, b)) plot_line(H, x) plt.plot(x, y, 'bo') plt.show()
616a02a9bdb9df8642ab057e6e2865a9926f2dd1
pandyakavi/Algorithms
/MergeSort.py
484
3.875
4
def MergeSort(arr): if len(arr) > 1: mid = len(arr)//2 left = arr[:mid] right = arr[mid:] MergeSort(left) MergeSort(right) i=0;j=0;k=0 while i < len(left) and j < len(right): if left[i] < right[j]: arr[k] = left[i] i+=1 else: arr[k] = right[j] j+=1 k+=1 while i < len(left): arr[k]=left[i] i+=1;k+=1 while j < len(right): arr[k]=right[j] j+=1;k+=1 arr = map(int, raw_input().split(" ")) MergeSort(arr) print arr
a2faef46e4eb487b70ad4bb5e1c7ead5331eecc6
Nebual/rimsky
/combat.py
2,671
4.0625
4
import random, actor def populate(encounterList): """ Gets an encounter from a list of possible encounters and creates up to 3 monster objects. """ selection = encounterList[random.randint(0, len(encounterList)-1)] monsters = [] for name in selection: monsters.append(actor.Monster(name)) #append a monster object to a list 'monsters' num = 1 #assigns a number to each monster for targeting purposes for monster in monsters: monster.combatNumber = num num += 1 return monsters def playerTurn(player, monsters): #make sure to pass the monster list, not just one monster while True: playerMove = raw_input("fight, item, or flee? ") print if playerMove == "fight": target = pickTar(monsters) dmg = player.attack(target) if target.hp == 0: print "You did", dmg, "damage to", target.name, "!", target.name, "died!" else: print "You did", dmg, "damage to", target.name, "! It has", target.hp, "hp left." return playerMove elif playerMove == "item": player.hp += 20 print "Potion heals you for 20 hp! You have", player.hp, "hp left!" return playerMove elif playerMove == "flee": return playerMove else: print "Sorry, I didn't understand that. Please try again" print def pickTar(monsters): while True: choice = input("Attack which monster? (enter 1, 2, or 3) ") print for monster in monsters: #finds monster with that number (assigned in populate()) if monster.combatNumber == choice and monster.hp !=0: return monster print "Sorry, that's not a valid monster. Please try again." print def monsterTurn(player, monster): #just pass the current monster here, not the list dmg = monster.attack(player) print monster.name, "attacks you for", dmg, "damage! You have", player.hp, "hp left." def outcome(player, playerMove): """determines if player won, lost, or fled""" if playerMove == "flee": return "You fled the battle!" elif player.hp > 0: return "You win!" else: return "You lose!" def main(): player = actor.Player() #eventually can pass player obj to this module encounterList = [['orc', 'orc', 'goblin'], ['goblin', 'goblin'], ['dragon']] monsters = populate(encounterList) deadMonsters = 0 print "You are fighting", len(monsters), "monsters:" for monster in monsters: print monster.name while True: print playerMove = playerTurn(player, monsters) if playerMove == "flee": break print for monster in monsters: if monster.hp != 0: monsterTurn(player, monster) else: deadMonsters += 1 if deadMonsters == len(monsters): break deadMonsters = 0 print print outcome(player, playerMove)
b44ee0a7e0992cfa971ab27f0c9f50170ea49df1
signalwolf/Leetcode_by_type
/MS Leetcode喜提/37. Sudoku Solver.py
1,286
3.546875
4
class Solution(object): def validation(self, board, x, y): base = board[x][y] for i in xrange(9): if i == x: continue if board[i][y] == base: return False for j in xrange(9): if j == y: continue if board[x][j] == base: return False for i in xrange(x / 3 * 3, (x / 3 + 1) * 3): for j in xrange(y / 3 * 3, (y / 3 + 1) * 3): if i == x and j == y: continue if board[i][j] == base: return False return True def helper(self, board, x): for i in xrange(x, 9): for j in xrange(9): if board[i][j] == '.': for k in xrange(1, 10): board[i][j] = str(k) if self.validation(board, i, j) and self.helper(board, i): return True else: board[i][j] = '.' return False return True def solveSudoku(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ self.helper(board, 0)
2fc5c7dab35b1be37b178cb23afa27a93827f2d6
VladimirRudenko/-Python
/1.py
525
3.890625
4
s = 25 print("this is integer ->" ,s) lst = [7, "f", "ds", "ds"] print ("this is list ->" + str(lst) ) print ("this is String -> string") r1 = {'model': '4451', 'ios': '15.4'} print("this is dictinary-> " + str(r1)) set = (11, 22, 44, 33) print("this is set -> " + str(set)) tuple1 = ("bla", "bla2", "bla3") print ("this is tuple -> " + str(tuple1)) boolean = True print("this is boole ->", boolean) float = 0.8 print("this is float -> " + str(float)) lst = ["f", "f", "ds", "ds"] print ("this is list ->", str(lst))
d7afc2217de549b36dd4a1e721fcd686ce43fe5b
CallumShepherd/ICTPRG-Python
/W9/Resources/files4.py
837
3.65625
4
with open ( 'data.txt', 'w') as f1: while True: product_id=input('Product ID: ') if product_id == '': break print(product_id) name = input ('Item Name: ') print(name) price = input('Price: ') print(f'${price.strip("$")}') f1.write(product_id + '\n') f1.write(name + '\n') f1.write(price.strip('$') + '\n') with open('data.txt','r') as f2: items=f2.readlines() print(items) sum = 0 for i in range(1, len(items) + 1): # picking up the third item in the array. The range is changed to use the code i%3 #since index starts with 0 if i % 3 ==0: price=float(items[i-1]) print(f'The index is {i - 1}.') print(f'The price is ${price}.') sum = sum + price print (f'The sum of the prices is ${sum}.')
8829a2ab67570fd830e8cf75127d80dde81f7a05
glouno/Courseworks
/PRP Programming Practice/PRPweek2.py
308
3.921875
4
stack=[] stack.append('apple') stack.extend(['pear', 'banana', 'tomato']) print (stack) print(stack.pop(1)) letters = ['a', 'b', 'c', 'd'] new_list_1 = letters new_list_2 = letters[:] letters[2] = 'e' print(new_list_1) print(new_list_2) x = [1, 2] y = [1, 2] print(x == y) print(x is y) x=y print(x is y)
9d3c7959a1a2fc133242046bc23499deaf2de513
Payne3/Voting-Financial-Analysis
/PyPoll/Resources/main.py
2,173
3.75
4
import os # Module for reading CSV files import csv csvpath = os.path.join('..', 'Resources', 'election_data.csv') total_votes = 0 kahn_votes =[] correy_votes = [] otooley_votes = [] Li_votes = [] K_percentage = 0 O_percentage = 0 L_percentage = 0 C_percentage = 0 with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: total_votes += 1 # places strings with indicated name into a list if row[2] == "Khan": kahn_votes.append(row[2]) if row[2] == "Correy": correy_votes.append(row[2]) if row[2] == "O'Tooley": otooley_votes.append(row[2]) if row[2] == "Li": Li_votes.append(row[2]) # calculate percentage of votes for each candidate K_percentage = ((len(kahn_votes)/total_votes))*100 O_percentage = ((len(otooley_votes)/total_votes))*100 L_percentage = ((len(Li_votes)/total_votes))*100 C_percentage = ((len(correy_votes)/total_votes))*100 print(f"Total Votes: ({total_votes})") print(f'Khan : {(round(K_percentage,4))} % ({len(kahn_votes)})') print(f"O'Tooley : {(round(O_percentage,4))} % ({len(otooley_votes)})") print(f'Li : {(round(L_percentage,4))} % ({len(Li_votes)})') print(f'Correy : {(round(C_percentage,4))} % ({len(correy_votes)})') output_path = os.path.join("poll.txt") # Open the file using "write" mode. Specify the variable to hold the contents with open(output_path, 'w', newline='') as text_file: # Initialize csv.writer writer = csv.writer(text_file, delimiter=',') # Write the first row (column headers) writer.writerow([(f"Total Votes: ({total_votes})")]) # Write the second row writer.writerow([f'Khan : {(round(K_percentage,4))} % ({len(kahn_votes)})']) writer.writerow([f"O'Tooley : {(round(O_percentage,4))} % ({len(otooley_votes)})"]) writer.writerow([f'Li : {(round(L_percentage,4))} % ({len(Li_votes)})']) writer.writerow([f'Correy : {(round(C_percentage,4))} % ({len(correy_votes)})']) writer.writerow(['Winner: Khan'])
6a55530de5c6f8c8716ca503e83b53f04eccef89
M10309105/pythonProject
/lesson/7/7.1.py
1,616
4.21875
4
#/usr/bin/python3 # #output print("=" * 100) print("7.1 output") print("=" * 100) year = 2021 month = '07' v = 3.1415926 #(formatted string literals) #https://docs.python.org/zh-tw/3/tutorial/inputoutput.html#tut-f-strings print(f'This is format output {year:-10d}, {month:10}, v={v:.3f}') #'!a' 會套用 ascii(),'!s' 會套用 str(),'!r' 會套用 repr(): #str() vs repr() print("=" * 100) print("7.1.1 Formatted String Literals") print("=" * 100) import math print(math.pi) print(f'{math.pi:.3f}') table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} for name, phone in table.items(): print(f'{name:10} ==> {phone:10} ==> 123') #pad right for name, phone in table.items(): print(f'{name:>10} ==> {phone:<10} ==> 123') print("=" * 100) print("7.1.2 format method") print("=" * 100) print('We are the {} who say "{}!"'.format('knights', 'Ni')) print('We are the {1} who say "{0}!"'.format('knights', 'Ni')) print('We are the {var1} who say "{var2}!"'.format(var2 = 'knights', var1 = 'Ni')) table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} #if dict print('jack:{0[Jack]}'.format(table)) #or can ** to let table be pass by key word print('jack: {Jack:d}'.format(**table)) print("=" * 100) print("7.1.3 format method") print("=" * 100) for x in range(1, 11): print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) #format to right print('This is apple'.rjust(30)) print('This is apple'.ljust(30)) print('This is apple'.center(30)) print('This is apple'.zfill(30)) print("=" * 100) print("7.1.4 old format") print("=" * 100) #% will be replaced print('The value pi : %5.3f' % math.pi)
c695246f9306955bc1e25523aff02b27fe4dffd0
nirajandata/iwbootcamp_assignments
/asg_22.py
91
3.78125
4
x=[1,2,3,12,3,4,1] dup=set() for i in x: if i not in dup: dup.add(i) print(dup)
24da18d6078b6ba76a9513062a019bd8d4648b22
thippeswamydm/python
/3 - Types/3.3 - InbuiltTypes-DictionarySetArray/11-dictions-methods-setdefault-usage.py
364
4.21875
4
# Describes the assigning, working, and method usages of dictionaries # String variable message = 'It was a bright cold day in April, and the clocks were striking thirteen.' # Creating a empty diction obj = {} # Adding default keys and values for keyitem in message: obj.setdefault(keyitem, 0) obj[keyitem] = obj[keyitem] + 1 # Print object print(obj)
020e2a249ffdc957adbdb253e198741d8fc1d7dc
grglzrv/python_exercises_and_exams
/exam_july/05. Fan Shop.py
614
3.75
4
budget = int(input()) n = int(input()) total_amount = 0 for item in range(0, n): input_item = input() if input_item == 'hoodie': total_amount += 30 elif input_item == 'keychain': total_amount += 4 elif input_item == 'T-shirt': total_amount += 20 elif input_item == 'flag': total_amount += 15 elif input_item == 'sticker': total_amount += 1 diff = abs(total_amount - budget) if budget >= total_amount: print(f'You bought {n} items and left with {diff} lv.') else: print(f'Not enough money, you need {diff} more lv.')
deb9cf8794fb1560ce400ce18f839fcceb7b0954
kitarvind01/PythonProgram
/FileHandlingProject/AddOfMultipleNumber.py
177
3.84375
4
import sys def sum(a,*b): c=a for i in b: c=c+b[i] print(c) a=int(input("Enter the first number")) b= input("ENter the second number") sum(a,tuple(list(b)))
abe0dc856b388305674987238eb0bca0cd859aa8
ActonMartin/leetcode
/414.第三大的数.py
2,224
3.6875
4
# # @lc app=leetcode.cn id=414 lang=python3 # # [414] 第三大的数 # # https://leetcode-cn.com/problems/third-maximum-number/description/ # # algorithms # Easy (35.28%) # Likes: 155 # Dislikes: 0 # Total Accepted: 32.6K # Total Submissions: 92.2K # Testcase Example: '[3,2,1]' # # 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。 # # 示例 1: # # # 输入: [3, 2, 1] # # 输出: 1 # # 解释: 第三大的数是 1. # # # 示例 2: # # # 输入: [1, 2] # # 输出: 2 # # 解释: 第三大的数不存在, 所以返回最大的数 2 . # # # 示例 3: # # # 输入: [2, 2, 3, 1] # # 输出: 1 # # 解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。 # 存在两个值为2的数,它们都排第二。 # # # # @lc code=start from collections import defaultdict, OrderedDict class Solution1: def thirdMax(self, nums: List[int]) -> int: count_dict = defaultdict(int) for i in nums: count_dict[i] += 1 sorted_dic = sorted(count_dict.items(), key= lambda x: x[0], reverse= True) if len(sorted_dic) < 3: return sorted_dic[0][0] else: return sorted_dic[2][0] class Solution2: def thirdMax(self, nums: List[int]) -> int: # 限定条件一:返回数组中第三大的数 # 限定条件二:不存在第三大则返回最大的数 # 限定条件三:算法时间复杂度 O(n) nums_set = set(nums) if len(nums_set)<3: return max(nums_set) else: nums_set.remove(max(nums_set)) nums_set.remove(max(nums_set)) return max(nums_set) from math import isinf class Solution: def thirdMax(self, nums: List[int]) -> int: nums = list(set(nums)) a = b = c = float('-inf') for num in nums: if num > a: c = b b = a a = num elif num > b: c = b b = num elif num > c: c = num return a if isinf(c) else c # @lc code=end
eec2e6f547891512718f7c5e26d325672b6f6384
mabbott2011/PythonCrash
/stringFunctions.py
875
4.375
4
# String Functions myStr='Hello World' print(myStr.capitalize()) #Swap case print(myStr.swapcase()) # Length print(len(myStr)) # Replace print(myStr.replace('World', 'Everyone')) # Number of occurances within String, case sensative sub = 'H' print(myStr.count(sub)) # l -> 3 # h -> 0 # H -> 1 # Starts with or ends with print(myStr.startswith('Hello')) # True print(myStr.endswith('!')) # True print(myStr.startswith('ello')) # False # Split string into Lists print(myStr.split()) # ['Hello', 'World!'] # FIND print(myStr.find('World')) # 6 # found by 6th character # INDEX - Similar to FIND but throws error if item isn't found print(myStr.index('W')) # 6 #print(myStr.index('9')) # ValueError: substring not found # Is all aphanumeric? print(myStr.isalnum()) # False # Is all alphabetic print(myStr, 'is alphabetric?', myStr.isalpha()) # False, has a space
edf86e5dad03cc284d4aa803f170b7c7168282db
cbragg3136/python-challenge
/PyBank/main.py
4,832
4.03125
4
# import modules for os and for reading csv file import os # module for reading csv file and path for reading csv file & writing text file import csv budget_data_csv = os.path.join('Resources', 'budget_data.csv') budget_data_text = os.path.join('analysis', 'results.txt') # defined a function to read the file into a list, to prevent having to reset the readerobj # Cite: Johnny Bragg, personal communication, September 15, 2020 def get_data(readerobj): dataset = [] for item in readerobj: dataset.append(item) return dataset # defined a function of the budget data. For loop to return the list of dates (to use for date_count) def date_count(budget_data): dates = [] for item in budget_data: dates.append(item[0]) #for each row get the column at the index position 0 return dates # defined a function of the budget data. For loop to return for list of profit/losses (to use for profit_sum) def profit_sum(budget_data): profits = [] for item in budget_data: profits.append(int(item[1])) return profits # open the file for reading (csv reader) and splits the data at comma with open(budget_data_csv, 'r') as budget_data_open: with open(budget_data_text, 'w') as budget_data_output: csvreader = csv.reader(budget_data_open, delimiter=',') # read the header row csv_header = next(csvreader) # store the list from get_data function inside variable called rows # Cite: Johnny Bragg, personal communication, September 15, 2020 rows = get_data(csvreader) # print statements to terminal and write to text file. Note '\n' is new line print("FINANCIAL ANALYSIS\n----------------------------") budget_data_output.write("FINANCIAL ANALYSIS\n----------------------------\n") # variables holding date_count and profit_sum lists (pulled from the defined functions) resultdates = date_count(rows) resultprofits = profit_sum(rows) # assumed the dates are unique and counted (len) the number of entries in list (resultdates) to get the total number of months (set as variable total_months). print to terminal and write result to text file. total_months = len(resultdates) print(f"Total Months: {total_months}") budget_data_output.write(f"Total Months: {total_months}\n") # Summed the resultprofits list to pull Net Total Profit net = sum(resultprofits) print(f"Net Total Profit: {net}") budget_data_output.write(f"Net Total Profit: {net}\n") # Cite for lines 69-95: Hetal. (2017, October 27). Python - How can I find difference between two rows of same column using loop in CSV file?. Stack Overflow. https://stackoverflow.com/questions/46965192/python-how-can-i-find-difference-between-two-rows-of-same-column-using-loop-in # create list (change_profits) of differences from a position i in a range minus one from that position. example [cell2 - cell1, cell3 - cell2, cell 4 - cell3] until end of rows/range change_profits = [] for i in range(1,len(resultprofits)): change_profits.append((int(resultprofits[i])) - (int(resultprofits[i-1]))) # add the items within the list of change_profits and divide by the length of the list for the average change in profits avg_change = sum(change_profits)/len(change_profits) # for generating the greatest increase and decrease in profits: # find the max and min values from the change_profits list max_profit_change = max(change_profits) min_profit_change = min(change_profits) # for pulling the dates of greatest increase and decrease in profits: # pull the index at the 'max and min values' of the change_profits list within the list of months (result_dates) # add one to the index (to pull the 2nd date) max_profit_change_date = str(resultdates[change_profits.index(max(change_profits))+1]) min_profit_change_date = str(resultdates[change_profits.index(min(change_profits))+1]) # use variables from greatest increase and decrease (see lines 73-85) in profits to print statements and write to text file print("Average Profit Change: $", round(avg_change,2)) budget_data_output.write(f"Average Profit Change: ${round(avg_change,2)}\n") print("Greatest Increase in Profits:", max_profit_change_date,"($", max_profit_change,")") budget_data_output.write(f"Greatest Increase in Profits: {max_profit_change_date} (${max_profit_change})\n") print("Greatest Decrease in Profits:", min_profit_change_date,"($", min_profit_change,")") budget_data_output.write(f"Greatest Decrease in Profits: {min_profit_change_date} (${min_profit_change})\n")
107e05b90a0664f3eabc5d84a6918745f62f01e3
wjj800712/python-11
/chengxiangzheng/week5/Q1.py
145
3.5625
4
#打乱一个排好序的列表alist,random模块中的shuffle(洗牌函数) import random alist=[1,2,3,4,5] random.shuffle(alist) print(alist)
19ad83907513a8ce36fb6f3b42c80bce6febc3ca
kyuchung-max/pyworks
/ch07/inherit_class/upcalculator.py
320
3.8125
4
from ch07.myclass.calculator import Calculator class MoreCalculator(Calculator): def pow(self): return self.x ** self.y def div(self): if self.y==0: return 0 else: return self.x/self.y cal=MoreCalculator(3,0) print(cal.add()) print(cal.div()) print( cal.pow())
ec87ac378d8a4b782b63dd4b1096f3c59c281d9e
quanhuynh/DailyProgrammer
/easy/172-pbm-image/172-pbm-image.py
1,419
4
4
""" [7/21/2014] Challenge #172 [Easy] ■■□□□▦■□ https://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_easy/ Given a string, output a pbm format that displays the string through 0s and 1s (or any characters desired) *Only supports all-caps text. Lowercase text can be added, but I'm lazy. """ import string ## Initial Set up: ### Reading font.txt ### Turning the font.txt information into a easier-to-read dictionary uppercases = string.ascii_uppercase font_file = open('font.txt', 'r').read() font_dict = {} for i in range(len(font_file)): if font_file[i] in uppercases: #if character is a letter, make it a key font_dict[font_file[i]] = [] for j in range(7): font_dict[font_file[i]].append(font_file[(i + 2 + 10*j):(i + 11 + 10 * j)].replace(' ', '').replace('0', ' ').replace('1', '█')) font_dict[' '] = [' ', ' ', ' ', ' ', ' ', ' ', ' '] #space between words ## This produces: ## font_dict = {'A': ['00100', '01010', '10001', '11111', '10001', '10001', '10001'], ## 'B': ['11110', '10001', '10001', '11110', '10001', '10001', '11110'], ## .... } ## with 1's replaced with '█' and 0's with '' for readability ## Printing output def pbm(string): # This function prints a pbm format of the given string print("P1") print(len(string)*9, 7) for i in range(7): for char in string: print(font_dict[char][i], end=' ') print() #empty space
0236e9f3fd9b2a80f4ebf1f189e8135fc0035d5d
JShad30/practice-python-scripts
/juicy.py
1,232
4.15625
4
fruits = ["an apple", "a banana", "a strawberry", "broccoli", "cabbage", "grapes", "pomegranite", "an avocado", "pineapple", "melon", "grapefruit", "watermelon", "Dragon Fruit", "lettuce", "a pepper", "a kiwi fruit", "some summer fruits", "mango", "an orange", "a tangerine", "a tomato"] def fruit_and_veg(): score = 0 for fruit in fruits: print("have you eaten {} today?".format(fruit)) has_fruit_been_eaten = input("Type y for yes or n for no: ") if has_fruit_been_eaten == "y": score += 1 first_name = input("Type your first name: ") last_name = input("Type your last name: ") f = open("fruitnames.txt", "a") if score >= 5: print("Well done {}. You've eaten {} fruits today which is very good! Well done keep it up!".format(first_name, str(score))) f.write("\n" + first_name + " " + last_name + ": " + str(score) + " fruits eaten today. Very good!") else: print("Sorry {}, you've only eaten {} fruits today. That's not your 5 a day... very naughty!".format(first_name, str(score))) f.write("\n" + first_name + " " + last_name + ": " + str(score) + " fruits eaten today. Keep an eye on them!!") fruit_and_veg()
fc0717e4d8c71d8a3163cf37709f205a76309cc4
gmdmgithub/python_patterns
/json_csv.py
3,068
3.515625
4
import json from urllib.request import urlopen import sys def main_first(): #prints a list of arguments - may be used later on argument_list = sys.argv for arg in argument_list: print(arg) with urlopen("https://free.currencyconverterapi.com/api/v6/currencies") as response: source = response.read() print('SOURCE TYPE',type(source)) data = json.loads(source) # loads read to string - convert print('DATA TYPE', type(data)) #print(json.dumps(data, indent=2)) # dump and dumps - outputs to string (JSON) for item in data['results']: # print(item) name = data['results'][item]['currencyName'] symbol = 'NOT EXISTS' if 'currencySymbol' in data['results'][item]: symbol = data['results'][item]['currencySymbol'] id = data['results'][item]['id'] print(name, symbol, id) #### second - better with exhange historical data print('\n#### exchangeratesapi ###') # https://api.exchangeratesapi.io/2010-01-12 # https://api.exchangeratesapi.io/latest?base=USD # similar to open (file) #with open('exhange.json',encoding='utf-8') as response: with urlopen("https://api.exchangeratesapi.io/latest") as response: source = response.read() data = json.loads(source) # loads from a string print(json.dumps(data, indent=2)) # dump and dumps - outputs to string (JSON) with open('exhange.json','w',encoding='utf-8') as f: f.write(json.dumps(data)) print('\n#### PRINTING exchangeratesapi ###') print(data['base'], data['date']) for item in data['rates']: print(item, data['rates'][item]) print('#### JSON ###') print(dir(json)) ##############################CSV import csv print(5*'#### CSV ###') with open('sample.csv',encoding='utf-8') as c: content = csv.reader(c) header = next(content) data = [line for line in content] print(header) for d in data: print('csv-line',d) def bart(): with open('./bartosz.json') as f: data = json.loads(f.read()) # print(dir(data['products'])) check_amount = 1500.0 check_period = 5 min = 100 providerId ='' for el in data['products']: for val in el['interests']: print(check_amount, el['providerId'], val['apr'], val['loanAmountMax'], val['loanAmountMin'], val['loanTenureMin'], val['loanTenureMax']) if check_amount <= val['loanAmountMax'] and \ check_amount >= val['loanAmountMin'] and \ check_period >= val['loanTenureMin'] and \ check_period <= val['loanTenureMax'] and \ val['apr'] <= min: min = val['apr'] providerId = el['providerId'] print(f'Minimal interest rate {min} is for provider: {providerId} for the period {check_period} and amount {check_amount}') for arg in sys.argv: print(arg) if __name__ == "__main__": bart()
1b70051b09fa932abc8a02071366e48879901488
fitifit/pythonintask
/src/task_2_0.py
667
3.5
4
# Задача 2. Вариант 0. # Напишите программу, которая будет выводить на экран наиболее понравившееся вам высказывание, автором которого является Ф.М.Достоевский. Не забудьте о том, что автор должен быть упомянут на отдельной строке. # Krasnikov A. S. # 01.02.2016 print("Жизнь, везде жизнь, жизнь в нас самих, а не во внешнем.") print("\n\t\t\t\t\tФ.М.Достоевский") input("\n\nНажмите Enter для выхода.")
153c421222777aa5dce27b0d9e2242dd78616bdd
riccardosirchia/unit_testing_python
/test_name_function.py
543
3.625
4
import unittest from name_functions import get_formated_name class NameTestClass (unittest.TestCase): '''tests for name_function.py''' def test_first_last_name(self): '''test for just a firs and last name ''' formatted_name = get_formated_name('jannis', 'botha') self.assertEqual(formatted_name, 'Jannis Botha') def test_first_middle_last_name(self): ''' test to see if a full name with middle name works ''' formatted_name = get_formated_name('james', 'hunt', 'william') self.assertEqual(formatted_name, 'James William Hunt') unittest.main()
a97fc3788ee7bdf573236ae12ba54089bcafb188
borisbarath/registermachinecoding
/num_coding.py
1,881
3.5
4
def enc_pair(x, y): # Encode <<x, y>> return (2 ** x * (2 * y + 1)) def dec_pair(code): # Decode <<x, y>> x = 0 y = 0 if code % 2 == 1: x = 1 else: while code % 2 == 0: code = code // 2 x += 1 y = (code - 1) / 2 return(x, y) def enc_pair_alt(x, y): # Encode <x, y> return (2 ** x * (2 * y + 1) - 1) def dec_pair_alt(code): # Decode <x, y> return dec_pair(code + 1) def enc_list(l): if l == []: return 0 else: return enc_pair( l[0], enc_list(l[1:]) ) def dec_list(code): res = [] while code != 0: (item, tail) = dec_pair(code) code = tail res.append(item) return res def dec_instr(code): res = [] if code == 0: return res (i, j) = dec_pair(code) if i % 2 == 0: res.append(i // 2) res.append(j) else: res.append((i - 1) // 2) (k, l) = dec_pair_alt(j) res.append(k) res.append(l) return res def enc_instr(instr): # Representations: # HALT = [] # Ri + -> Rj = [i, j] # Ri - -> Rj, Rk = [i, j, k] if len(instr) == 0: return 0 elif len(instr) == 2: return enc_pair(2 * instr[0], instr[1]) goto = enc_pair_alt(instr[1], instr[2]) return enc_pair(2 * instr[0] + 1, goto) def enc_rm(machine): # Encode register machine instruction by instruction res = [] for instr in machine: res.append(enc_instr(instr)) return enc_list(res) def dec_rm(code): res = [] instrs = dec_list(code) for instr in instrs: res.append(dec_instr(instr)) return res def print_rm(rm): for instr in rm: if len(instr) == 0: print("HALT") elif len(instr) == 2: print("R" + str(instr[0]) + " + -> R" + str(instr[1])) else: print("R" + str(instr[0]) + " - -> R" + str(instr[1]) \ + ", " + str(instr[2])) print(enc_pair(3, 0)) print(enc_pair(1, 8)) print(dec_pair(276)) print("") print(enc_list([2,1,3])) print(dec_list(276)) print(dec_pair_alt(27)) print("") print(enc_instr([1,1,2])) print(dec_instr(152))
6c366d78ab924cb8d62771cba554fabf70a892cf
sunsgneckq/CS-88
/Lab/lab03/lab03.py
6,464
4.34375
4
## Data Abstraction ## def make_city(name, lat, lon): """ >>> city = make_city('Berkeley', 0, 1) >>> get_name(city) 'Berkeley' >>> get_lat(city) 0 >>> get_lon(city) 1 """ return [name, lat, lon] def get_name(city): """ >>> city = make_city('Berkeley', 0, 1) >>> get_name(city) 'Berkeley' """ return city[0] def get_lat(city): """ >>> city = make_city('Berkeley', 0, 1) >>> get_lat(city) 0 """ return city[1] def get_lon(city): """ >>> city = make_city('Berkeley', 0, 1) >>> get_lon(city) 1 """ return city[2] from math import sqrt def distance(city_1, city_2): """ >>> city1 = make_city('city1', 0, 1) >>> city2 = make_city('city2', 0, 2) >>> distance(city1, city2) 1.0 """ lat_1, lon_1 = get_lat(city_1), get_lon(city_1) lat_2, lon_2 = get_lat(city_2), get_lon(city_2) return sqrt((lat_1 - lat_2)**2 + (lon_1 - lon_2)**2) def closer_city(lat, lon, city1, city2): """ Returns the name of either city1 or city2, whichever is closest to coordinate (lat, lon). >>> berkeley = make_city('Berkeley', 37.87, 112.26) >>> stanford = make_city('Stanford', 34.05, 118.25) >>> closer_city(38.33, 121.44, berkeley, stanford) 'Stanford' >>> bucharest = make_city('Bucharest', 44.43, 26.10) >>> vienna = make_city('Vienna', 48.20, 16.37) >>> closer_city(41.29, 174.78, bucharest, vienna) 'Bucharest' """ new_city = make_city('name', lat, lon) distanced1 = distance(city1, new_city) distanced2 = distance(city2, new_city) if distanced1 < distanced2: return get_name(city1) return get_name(city2) ## ADT: Trees ## def tree(root, branches=[]): for branch in branches: assert is_tree(branch), 'branches must be trees' return [root] + list(branches) def root(tree): return tree[0] def branches(tree): return tree[1:] def is_tree(tree): if type(tree) != list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True def is_leaf(tree): return not branches(tree) numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])]) def print_tree(t, indent=0): """Print a representation of this tree in which each node is indented by two spaces times its depth from the root. >>> print_tree(tree(1)) 1 >>> print_tree(tree(1, [tree(2)])) 1 2 >>> print_tree(numbers) 1 2 3 4 5 6 7 """ print(' ' * indent + str(root(t))) for branch in branches(t): print_tree(branch, indent + 1) def tree_map(fn, t): """Maps the function fn over the entries of tree and returns the result in a new tree. >>> numbers = tree(1, ... [tree(2, ... [tree(3), ... tree(4)]), ... tree(5, ... [tree(6, ... [tree(7)]), ... tree(8)])]) >>> print_tree(tree_map(lambda x: 2**x, numbers)) 2 4 8 16 32 64 128 256 """ return tree(fn(root(t)), [tree_map(fn, t) for t in branches(t)]) ## ADT: Rational Numbers ## def make_rat(num, den): """Creates a rational number, given a numerator and denominator. """ return lambda x, y: [lambda: den + x, lambda: num + y] def num(rat): """Extracts the numerator from a rational number.""" return rat(2, 3)[1]() - 3 def den(rat): """Extracts the denominator from a rational number.""" return rat(8, 5)[0]() - 8 def add_rat(a, b): """Adds two rational numbers A and B. For example, (3 / 4) + (5 / 3) = (29 / 12) >>> a, b = make_rat(3, 4), make_rat(5, 3) >>> c = add_rat(a, b) >>> num(c) 29 >>> den(c) 12 """ return make_rat(num(a) * den(b) + num(b) * den(a), den(a) * den(b)) def sub_rat(a, b): """Subtracts two rational numbers A and B. For example, (3 / 4) - (5 / 3) = (-11 / 12) >>> a, b = make_rat(3, 4), make_rat(5, 3) >>> c = sub_rat(a, b) >>> num(c) -11 >>> den(c) 12 """ return make_rat(num(a) * den(b) - num(b) * den(a), den(a) * den(b)) def mul_rat(a, b): """Multiplies two rational numbers A and B. For example, (3 / 4) * (5 / 3) = (15 / 12) >>> a, b = make_rat(3, 4), make_rat(5, 3) >>> c = mul_rat(a, b) >>> num(c) 15 >>> den(c) 12 """ return make_rat(num(a)*num(b),den(a)*den(b)) def div_rat(a, b): """Divides two rational numbers A and B. Keep in mind that A / B is equivalent to A * (1 / B). For example, (3 / 4) / (5 / 3) = (9 / 20) >>> a, b = make_rat(3, 4), make_rat(5, 3) >>> c = div_rat(a, b) >>> num(c) 9 >>> den(c) 20 """ return make_rat(num(a)*den(b),den(a)*num(b)) def eq_rat(a, b): """Returns True if two rational numbers A and B are equal. For example, (2 / 3) = (6 / 9), so eq_rat would return True. >>> a, b = make_rat(2, 3), make_rat(6, 9) >>> eq_rat(a, b) True >>> c, d = make_rat(1, 4), make_rat(1, 2) >>> eq_rat(c, d) False """ return num(a) * den(b) == num(b) * den(a) ## Challenge Question ## def depth(t, v): """Returns the depth of value v in tree t if v is contained in t. If v is not in t, return None. >>> test_tree = tree(1, ... (tree(2, ... (tree(3, ... (tree(4), ... tree(5))), ... tree(6, ... (tree(7), ... tree(8))))), ... (tree(9, ... (tree(10, ... (tree(11), ... tree(12))), ... tree(13, ... (tree(14), ... tree(15)))))))) >>> depth(test_tree, 1) 0 >>> depth(test_tree, 42) # Returns None >>> depth(test_tree, 6) 2 >>> depth(test_tree, 15) 3 """ "*** YOUR CODE HERE ***"
f1b63d9bb0032381b9ee5409be7f80efa9d021e8
metacall/core
/source/scripts/python/ducktype/source/ducktype.py
947
3.890625
4
#!/usr/bin/env python3 def multiply(left, right): result = left * right print(left, ' * ', right, ' = ', result) return result def divide(left, right): if right != 0.0: result = left / right print(left, ' / ', right, ' = ', result) else: print('Invalid right operand: ', right) return result def sum(left, right): result = left + right print(left, ' + ', right, ' = ', result) return result def hello(): print('Hello World from Python!!') return def strcat(left, right): result = left + right print(left, ' + ', right, ' = ', result) return result def old_style(left: int, right: int) -> int: result = left + right print(left, ' + ', right, ' = ', result) return result def mixed_style(left, right: int) -> int: result = left + right print(left, ' + ', right, ' = ', result) return result def mixed_style_noreturn(left, right: int): result = left + right print(left, ' + ', right, ' = ', result) return result
e494631d46fec3683464912a26d5aed0108598fe
oumaymabg/holbertonschool-higher_level_programming
/0x03-python-data_structures/6-print_matrix_integer.py
325
4.15625
4
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): for n in range(len(matrix)): for i in range(len(matrix[n])): if i < len(matrix[n]) - 1: print("{:d}".format(matrix[n][i]), end=" ") else: print("{:d}".format(matrix[n][i]), end="") print("")
d3fc1b46afd57391a08a295202ac325fe460da3f
alexandradev/brain-workout
/palindrometest.py
208
3.921875
4
word = input("Write a word:") a = len(word) error = 0 for i in range(a//2): if word[i] != word[-1 - i]: error = 1 break if error == 1: print("It's not a palindrome") else: print("It's a palindrome") print()
2adc4c2dfae910028616fcb235f7a9a77cd7e6c1
maha2620/testrepo
/pyif.py
287
3.75
4
x=10 if x % 2 == 0: print(x, " is even number") else: print(x, " is odd number") print(type(x)) print(id(x)) print(x) a=1000 b=34.56 c=3+4j d=True e='python' print(type(a)) print(a) print(type(b)) print(b) print(type(c)) print(c) print(type(d)) print(d) print(type(e)) print(e)
1840eee571b09a5da4b169ae828720141662602e
sumaneshm/Code
/Python/Pluralsight/PythonFundamentals/Previous/Collections/ListCollection.py
1,575
4.15625
4
# list can be created by calling split as well theList = "This is a very cool feature of Python".split() print(theList) # or initialized using square brackets theList = [0, 1, 2, 3, 4, 5] print(theList) # two ways to access elements by index # positive => lef to right print(theList[0]) # negative => right to left print(theList[-1]) # we can slice a part of the list as shown below print(theList[1:3]) # reverse slicing is also possible print(theList[-3:-1]) # slice from middle till the end print(theList[2:]) # slice from the beginnning till the middle print(theList[:2]) # split the list into two lists print(theList[:2], ' after', theList[2:]) # copying the list # Method 1 newList1 = theList[:] print(newList1 == theList) # newList is equal to list print(newList1 is theList) # newList reference is not equal to list # Method 2 newList2 = theList.copy() print(newList2 == theList) print(newList2 is theList) # Method 3 newList3 = list(theList) print(newList3 == theList) print(newList3 is theList) family = ["Sumanesh", "Saveetha", "Aadhavan", "Aghilan", "Aadhavan"] # index will find the index of the searched string (if not found, it will throw an exception) print(family.index('Sumanesh')) # count function will find the number of occurrence of the word (case sensitive match) print(family.count('Aadhavan')) # you can delete any element using the position del family[-1] print(family) # delete using the element name family += ["Nila", "Nila"] # this will remove only the first match, not all the matches family.remove("Nila") print(family)
88426134d90b41e58f5005a68ef6d1fa5b5f25bf
VettiEbinyjar/py-learning
/1-basics/4-format-str.py
824
4.09375
4
age = 25 print('My age is ' + str(age) + ' years') # replacement filed print('My age is {0} years'.format(age)) print('There are {0} days in {1}, {2}'.format(31, 'Jan', 'Mar')) # reusing data print('''Jan:{2}, Feb:{0}, Mar:{2}, Apr:{1}'''.format(28, 30, 31)) print() print('My age is %d years' % age) print('My age is %d %s, %d %s' % (age, 'years', 6, 'month')) print() # formatting for i in range(1, 12): print('%2d squared is %4d, cubed is %4d' % (i, i ** 2, i ** 3)) print() # formatting for i in range(1, 12): print('{0:2} squared is {1:4}, cubed is {2:<4}'.format(i, i ** 2, i ** 3)) print() print('PI is approx %12f' % (22 / 7)) print('PI is approx %12.50f' % (22 / 7)) print('PI is approx {0:12.50f}'.format(22 / 7)) print() # auto assignment print('auto {} setting with formatting {:4}'.format(1, 2))
ecf9b7dd7e7b01d6313dbd1aa41e56f1a989d919
nathrichCSUF/Connect4AI
/slot.py
932
3.75
4
""" FALL 2019 CPSC 481 Artificial Intelligence Project File Description: slot.py Class representing a slot in the Connect Four Game Grid Authors: Nathaniel Richards Yash Bhambani Matthew Camarena Dustin Vuong """ import pygame class Slot: def __init__(self, screen): self.screen = screen self.state = "black" # String holding state of coin, is it red, yellow, or black(empty) self.image = pygame.image.load("black.png") self.rect = self.image.get_rect() def change_state(self, color): # Change color of coin self.state = color self.image = pygame.image.load(self.state + ".png") def reset(self): self.state = "black" #print(self.state) def set_slot_position(self, x, y): # Set position of slot within the grid self.rect.x = x self.rect.y = y # Blit Coin to Screen def blit(self): self.screen.blit(self.image, self.rect)
df86e18aa118aa33e47a8f31b0c501946df0c58d
febimudiyanto/mysql-python
/connection.py
2,086
3.5625
4
# IP address dari server ''' untuk terkoneksi dengan mysql secara remote, bisa digunakan command berikut: mysql -u python-user -h <ip> -P <port> -p > masukkan passwordnya * insert INSERT INTO table_name VALUES (column1_value, column2_value, column3_value, ...); INSERT INTO logins(username, password) VALUES('administrator', 'adm1n_p@ss'); INSERT INTO logins(username, password) VALUES ('john', 'john123!'), ('tom', 'tom123!'); * ALTER ALTER TABLE logins ADD newColumn INT; ALTER TABLE logins RENAME COLUMN newColumn TO oldColumn; ALTER TABLE logins MODIFY oldColumn DATE; ALTER TABLE logins DROP oldColumn; * Update UPDATE table_name SET column1=newvalue1, column2=newvalue2, ... WHERE <condition>; UPDATE logins SET password = 'change_password' WHERE id > 1; ''' HOST = "192.168.122.176" DATABASE = "data_db" USER = "python-user" PASSWORD = "inirahasia" # Cek koneksi database db_connect = mysql.connect(host=HOST, user=USER, passwd = PASSWORD) if db_connect: print("koneksi sukses") else: print("koneksi gagal") # Inisialisasi cursor() mycursor = db_connect.cursor() # Menampilkan database mycursor.execute("Show databases") #print(type(mycursor)) nama_db=DATABASE lst=[] for db in mycursor: #mendapatkan list dari database lst.append(db[0]) print(db[0]) # cek dan buat database if nama_db in lst: print("database",nama_db,"sudah ada") else: print(">database tidak ada") mycursor.execute("create database if not exists "+nama_db) print(" >>>database",nama_db,"sudah dibuat") mycursor.execute("use "+nama_db) for db in mycursor: print(db[0])
caadf640706febc1f913cef4cf1c926a3caacd56
dmitryzykovArtis/education
/44.py
890
3.546875
4
"""Топологическая сортировка""" n, m = map(int, input().split(" ")) G = [[] for i in range(n)] for i in range(m): k, v = map(int, input().split(" ")) G[k].append(v) def dfs(G, start, path, circle_check): neibours_count = len(G[start]) circle_check.append(start) for i in range(neibours_count): v = G[start][i] if v in path: continue; if v in circle_check: return True res = dfs(G,v, path, circle_check) if res: return True path.append(start) return False def topologic(G): n = len(G) path = [] for i in range(n): if i not in path: circle_check = [] res = dfs(G, i, path, circle_check) if res: print("NO") return print(" ".join(map(str,path[::-1]))) topologic(G)
8e8605216fefcc40be79259a007eca21a3ee554c
bazunaka/geekbrains_python
/python_start/homework1/2. time.py
306
4.15625
4
#Просим ввести количество секунд seconds = int(input("Введите количество секунд: ")) #Приводим вывод input к int hours = seconds//3600 minutes = seconds%3600//60 second = seconds%3600%60 print("{0}:{1}:{2}".format(hours, minutes, second))
f7645df887992fbffd4838e2ce6765c8e0d50ba4
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/capacityToShipWithInDDays.py
3,103
4.1875
4
""" A conveyor belt has packages that must be shipped from one port to another within D days. The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within D days. Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], D = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], D = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], D = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 Note: 1 <= D <= weights.length <= 50000 1 <= weights[i] <= 500 """ """ The intuition for this problem, stems from the fact that a) Without considering the limiting limiting days D, if we are to solve, the answer is simply max(a) b) If max(a) is the answer, we can still spend O(n) time and greedily find out how many partitions it will result in. [1,2,3,4,5,6,7,8,9,10], D = 5 For this example, assuming the answer is max(a) = 10, disregarding D, we can get the following number of days: [1,2,3,4] [5] [6] [7] [8] [9] [10] So by minimizing the cacpacity shipped on a day, we end up with 7 days, by greedily chosing the packages for a day limited by 10. To get to exactly D days and minimize the max sum of any partition, we do binary search in the sum space which is bounded by [max(a), sum(a)] Binary Search Update: One thing to note in Binary Search for this problem, is even if we end up finding a weight, that gets us to D partitions, we still want to continue the space on the minimum side, because, there could be a better minimum sum that still passes <= D paritions. Time complexity: O(n * logSIZE), where SIZE is the size of the search space (sum of weights - max weight). Space complexity: O(1). """ class Solution: def shipWithinDays(self, weights: List[int], D: int) -> int: low, high = max(weights), sum(weights) # if we send everything in one day, it requires sum of all weights. If we send the heaviest by itself, the lowest is maximum of weights while low < high: mid = (low + high)//2 total, res = 0, 1 for weight in weights: if total + weight > mid: res += 1 total = weight else: total += weight if res <= D: high = mid else: low = mid+1 return low
751c56ef12ace6d4012ff9928863a8b14aa1af82
johnnystefan/personalProject
/prueba2.py
3,908
3.734375
4
import os import time import collections def clean(): """ Funcion para limpiar pantalla """ os.system('cls') def sumNode(i): """ Funcion para determinar la Sumatoria por cada nodo """ global groupColor value = 0 view = {i} # deque >>> es un contenedor de elemnetos # collections >>> El módulo integrado de colecciones que pertenece al standar library de python container = collections.deque([(i, {groupColor[i]})]) while container: node, colors = container.popleft() value += len(colors) for edge in edges[node]: if edge not in view: view.add(edge) container.append((edge, colors | {groupColor[edge]})) return value def assignNodes(): """ Funcion para asignar el numero de nodos """ global nodes try: nodes = int(input('Intruduzca el numero de nodos del arbol: ')) if nodes > 0 and nodes < 10**5: pass else: print('...........') print('ERROR. El numero de nodos debe ser mayor a 0 y, menor o igual a 10^5') print('...........') time.sleep(3) clean() assignNodes() print('\n Has Creado un arbol de {} nodos'.format(nodes)) time.sleep(2) except ValueError: print('...........') print('ERROR. Debe introducir un numero entero') print('...........') time.sleep(3) clean() assignNodes() def assignColor(): """ Funcion para asignar los colores del primer al ultimo nodo """ global groupColor print('NOTA:') print(' .- Asigna un color a cada nodo separados por espacios ""') print(' .- EJEMPLO: 1 2 3 4 5 6') print('Tenemos << {} >> nodos.'.format(nodes)) groupColor = input('Asigne el grupo de colores: ').split(' ') try: results = list(map(int, groupColor)) n = len(results) for x in range(0, n): if results[x] > 0 and results[x] < 10**5: continue else: print('...........') print('ERROR. Debe introducir una operacion mas el numero') print('...........') time.sleep(3) clean() assignColor() print('\n Correcto!') time.sleep(1) except ValueError as e: print(e) print('...........') print('ERROR. Debe introducir un numero Entero') print('...........') time.sleep(3) clean() assignColor() def assignEdges(): """ Funcion para asignar los enlaces """ global nodes global edges edges = {i: [] for i in range(nodes)} try: for i in range(nodes - 1): print('NOTA:') print(' .-Asigna los enlaces separados por un espacio') print(' .-EJEMPLO: Para indicar que el nodo 1 esta conectado con 2') print(' Asi: 1 2') print(' .-Puedes asignar solo {} enlaces'.format(nodes-1)) first, second = [ int(i) - 1 for i in input('Ingresa el {} th enlace: '.format(i+1)).split(' ')] edges[first].append(second) edges[second].append(first) clean() print('\n Correcto!') time.sleep(1) except ValueError: print('...........') print('ERROR. Debe introducir un numero Entero') print('...........') time.sleep(3) clean() assignEdges() if __name__ == '__main__': """ EJECUCION PRINCIPAL DEL PROGRAMA """ nodes = 0 groupColor = [] edges = {} clean() assignNodes() clean() assignColor() clean() assignEdges() clean() for i in range(nodes): print('\nSumatoria del {} th nodo: {}'.format(nodes+1, sumNode(i)))
8b349b785e182f6453c0999b41377988273e8244
deadstrobe5/IA-Project
/IA1920Proj2alunosv01/ruagomesfreiregame2sol.py
3,063
3.515625
4
# Afonso Ribeiro 89400 ; Guilherme Palma 89438 ; Grupo 23 import random import numpy DISCOUNT = 0.9 L_RATE = 0.9 EXPLORE = 0.1 # LearningAgent to implement # no knowledeg about the environment can be used # the code should work even with another environment class LearningAgent: # init # nS maximum number of states # nA maximum number of action per state def __init__(self,nS,nA): self.nS = nS self.nA = nA self.q_matrix = [[None for i in range(nA)] for j in range(nS)] # Select one action, used when learning # st - is the current state # aa - is the set of possible actions # for a given state they are always given in the same order # returns # a - the index to the action in aa def selectactiontolearn(self,st,aa): lista = [] #print(self.q_matrix[st][0:len(aa)]) for i in range(0,len(aa)): q = self.q_matrix[st][i] if(q is None): self.q_matrix[st][i] = 1 q = 1 lista.append(q) qmax = numpy.max(lista) if random.random() < EXPLORE: a = random.randrange(0, len(lista)) else: a = lista.index(qmax) return a # Select one action, used when evaluating # st - is the current state # aa - is the set of possible actions # for a given state they are always given in the same order # returns # a - the index to the action in aa def selectactiontoexecute(self,st,aa): lista = [] for i in range(0,len(aa)): q = self.q_matrix[st][i] if(q is None): q = 1 lista.append(q) qmax = numpy.max(lista) a = lista.index(qmax) return a # this function is called after every action # st - original state # nst - next state # a - the index to the action taken # r - reward obtained def learn(self,ost,nst,a,r): lista = [] #print(self.q_matrix[nst]) for i in range(0,self.nA): q = self.q_matrix[nst][i] if (q is None): break lista.append(q) if (len(lista) != 0): max_b = numpy.max(lista) else: max_b = 1 original_q = self.q_matrix[ost][a] new_q = (1-L_RATE)*original_q + L_RATE*(r + DISCOUNT * max_b) self.q_matrix[ost][a] = new_q return
971c1279ac8068ea8b458cfcfd176da9b059a9b2
inno-asiimwe/primes
/test_primes.py
1,842
4.28125
4
import unittest from primes import list_primes, is_int, is_greater_than_two class PrimeNumberTest(unittest.TestCase): """Test for the list_primes function""" def setUp(self): self.primes = list_primes(100) def test_is_int_interger(self): """Testing whether is_int returns true with an Interger """ test_value = is_int(4) self.assertTrue(test_value) def test_is_int_non_interger(self): """Testing whether is_int returns false with non Interger an interger""" test_value = is_int('two') self.assertFalse(test_value) def test_input_greater_than_2(self): """Method tests whether is_greater_than_two returns True with 2 or a number greater than 2""" self.assertTrue(is_greater_than_two(4)) def test_input_less_than_2(self): """Method tests whether is_greater_thsn_two returns Falls with a number less than 2""" self.assertFalse(is_greater_than_two(1)) def test_non_interger_input(self): """method tests whether is_greater_than_two raise a type Error with a non numeric value""" self.assertRaises(TypeError, is_greater_than_two,'four') def test_list_primes_for_prime(self): """Method tests if a given prime is in a list of prime numbers returned by list_primes""" my_primes = list_primes(100) self.assertIn(7, my_primes) def test_list_primes_for_non_prime(self): """Method tests if a non prime is present in a list of primes""" my_primes = list_primes(100) self.assertNotIn(6, my_primes) def test_output_for_upperlimit_if_prime(self): """Method tests if the given number is included in the list of primes if it is prime""" my_primes = list_primes(5) self.assertEqual(my_primes, [2,3,5])
24b384a4c5a59f6d2b4e54cd6a5077ab2c31f9cb
yosifnandrov/softuni-stuff
/list,advanced/Moving Target.py
949
3.65625
4
targets = input().split() targets = [int(i) for i in targets] command = input() while not command == "End": action, index, value = command.split() index = int(index) value = int(value) if action == "Shoot": if 0 <= index < len(targets): targets[index] -= value else: command = input() continue if targets[index] <= 0: targets.pop(index) elif action == "Add": if index >= len(targets) or index < 0: print(f"Invalid placement!") else: targets.insert(index, value) elif action == "Strike": if len(targets) < index + value or index < value: print(f"Strike missed!") command = input() continue else: del targets[index-value:index+value+1] command = input() targets = [str(i) for i in targets] targets_as_str = "|".join(targets) print(targets_as_str)
25a474b01ea6066fe345abc117d7407972ba217f
1218muskan/MarchCode
/Day 22/day22.py
216
3.84375
4
# "To Find the maximum and minimum number in an array" n = list(map(int,input().split())) max = max(n) min = min(n) print(f"The minimum no. in the array is {min}") print(f"The maximum no. in the array is {max}")
801d3a0f6252cc20fe7977520f5b99dfe42a8005
BlueBookBar/SchoolProjects
/Projects/PythonProjects/Project3.py
9,092
3.65625
4
import sys class Node: #Initialize def __init__(self, letter = "" , row = None, column = None, left = None, right = None, up = None, down = None, distance= None): self.distance = 0 self.letter = letter self.left = left self.right = right self.up = up self.down = down self.row = row self.column= column #get methods def getDistance(self): return self.distance def getColumn(self): return self.column def getRow(self): return self.row def getLetter(self): return self.letter def getLeft(self): return self.left def getRight(self): return self.right def getUp(self): return self.up def getDown(self): return self.down #set methods def setDistance(self, a): self.distance = a def setRow(self, a): self.row = a def setColumn(self, a): self.column = a def setLetter(self,a): self.letter = a def setLeft(self,a): self.left = a def setRight(self,a): self.right = a def setUp(self,a): self.up = a def setDown(self,a): self.down = a class LinkedList: def __init__(self, row, column): self.dummyNode = Node("Uncounted", 1, -1) self.row = row self.column = column self.numberNodes = 0 self.WORD= "" def changeRow(self, r):#changes row number but also adds dummy nodes for each row if int(r) < 1: raise ValueError("Row parameter is not valid: "+ r) else: self.row= r currentNode = self.dummyNode for i in range(1, int(self.row)): newDummy = Node("Uncounted", i, -1) currentNode.setDown(newDummy) newDummy.setUp(currentNode) currentNode= newDummy def changeColumn(self, c):#changes column number if int(c) > 50: raise ValueError("Column parameter is not valid: "+ c) else: self.column= c def changeWord(self, a): self.WORD= a def getWord(self): return self.WORD def getRow(self): return self.row def getColumn(self): return self.column #Adds a node to the LinkedList def addNode(self, letter, Xcoor, Ycoor): TempNode= Node(letter, Xcoor, Ycoor) if self.numberNodes == 0:#if it is a new LinkedList then add the first node self.dummyNode.setRight(TempNode) TempNode.setLeft(self.dummyNode) self.numberNodes+=1 else: currentNode=self.dummyNode.getRight() if Xcoor is 1:#if on the first row, just add it on the line while currentNode.getRight() is not None: currentNode= currentNode.getRight() currentNode.setRight(TempNode) TempNode.setLeft(currentNode) self.numberNodes+=1 else: currentNode= self.dummyNode for i in range(1,Xcoor): currentNode= currentNode.getDown() if currentNode.getRight() is not None: while currentNode.getRight() is not None: currentNode = currentNode.getRight() currentNode.setRight(TempNode) TempNode.setLeft(currentNode) self.numberNodes+=1 else: currentNode.setRight(TempNode) TempNode.setLeft(currentNode) self.numberNodes+=1 #Prints the list def printlist(self): if self.numberNodes==0: return currentNode=self.dummyNode currentDummy = self.dummyNode for i in range(1,int(self.row)+1): currentNode=currentDummy.getRight() outWord = "" while currentNode.getRight() is not None: outWord += currentNode.getLetter() currentNode= currentNode.getRight() outWord += currentNode.getLetter()+"\n" print(outWord ) currentDummy = currentDummy.getDown() #Connects up and down channels for Nodes so that they can be used def upDownConnector(self): if self.dummyNode.getDown() is None: return topDummy= self.dummyNode bottomDummy= self.dummyNode.getDown() topCurrent =topDummy bottomCurrent = bottomDummy while bottomDummy.getDown() is not None: topCurrent = topDummy bottomCurrent = bottomDummy while (topCurrent.getRight() is not None) and (bottomCurrent.getRight() is not None): topCurrent.setDown(bottomCurrent) bottomCurrent.setUp(topCurrent) topCurrent= topCurrent.getRight() bottomCurrent = bottomCurrent.getRight() temp = bottomDummy.getDown() topDummy = bottomDummy bottomDummy = temp topCurrent =topDummy bottomCurrent = bottomDummy while (topCurrent.getRight() is not None) and (bottomCurrent.getRight() is not None): topCurrent.setDown(bottomCurrent) bottomCurrent.setUp(topCurrent) topCurrent= topCurrent.getRight() bottomCurrent = bottomCurrent.getRight() def searchNextPoint(self, startNode, searchLetter): currentNode=self.dummyNode currentDummy = self.dummyNode newDistance = self.numberNodes+1 tempX=0 tempY=0 endNode = self.dummyNode #REMEMBER TO ADD FOR WHEN THERE IS ONLY ONE ROW if self.row==1: currentNode=currentDummy.getRight() while currentNode.getRight() is not None: if currentNode.getLetter() == searchLetter:#here find the right letter tempX = abs(startNode.getRow() - currentNode.getRow()) tempY = abs(startNode.getColumn() - currentNode.getColumn()) if newDistance > (tempX+tempY): newDistance= tempX+tempY endNode = currentNode endNode.setDistance(newDistance) currentNode= currentNode.getRight() endNode.setDistance(newDistance+1) return endNode else: for i in range(1,int(self.row)+1): currentNode=currentDummy.getRight() while currentNode.getRight() is not None: if currentNode.getLetter() == searchLetter:#here find the right letter tempX = abs(startNode.getRow() - currentNode.getRow()) tempY = abs(startNode.getColumn() - currentNode.getColumn()) if newDistance > (tempX+tempY): newDistance= tempX+tempY endNode = currentNode endNode.setDistance(newDistance) currentNode= currentNode.getRight() currentDummy = currentDummy.getDown() endNode.setDistance(newDistance+1) return endNode def runVirtualKeyboard(self): statement = self.getWord() newNode = self.dummyNode TotalDistance=0 for i in range(0,len(statement)): TempNode= self.searchNextPoint(newNode, statement[i]) TotalDistance +=TempNode.getDistance()#Add one for pressing button newNode=TempNode TempNode= self.searchNextPoint(newNode, "*") TotalDistance +=TempNode.getDistance()#Add one for pressing button newNode=TempNode return (TotalDistance) #Checks if the variable is a number(whether in string format or not) def is_number(s): try: float(s) return True except ValueError: return False #Takes the input file and makes a linkedlist for the keyboard def initKeyboard(file): a="" lineNumber=0 previousLine= None LL= LinkedList(-1, -1) with open(file,'r') as infile: for line in infile: if not previousLine== None: tempString = previousLine for i in range(len(previousLine)): a= tempString[i] if is_number(a): if LL.getRow()==-1: LL.changeRow(a) elif LL.getColumn()==-1: LL.changeColumn(a) elif a is not " ":#addNode LL.addNode(tempString[i], lineNumber, i) lineNumber+=1 previousLine= line LL.changeWord(previousLine) LL.upDownConnector() return LL #Main function #Read file is hardcoded as input.txt #Write file is hardcoded as output.txt if __name__ == "__main__": a = initKeyboard("input.txt") temp = str(a.runVirtualKeyboard()) outfile = open('output.txt', 'w') outfile.write(temp) outfile.close()
e477577bb990e364f265f36fa3d3be201bf9455a
Researching-Algorithms-For-Us/4.Implementation
/baekjoon/python/17478.py
1,046
3.875
4
def set_input(): number = int(input()) return number def main(): number = set_input() def answer(m): step = "_" * 4 * (number-m) print(step + '"재귀함수가 뭔가요?"') if m == 0: print(step + '"재귀함수는 자기 자신을 호출하는 함수라네"') print(step + '라고 답변하였지.') return print(step + '"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.') print(step + '마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.') print(step + '그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어."') answer(m-1) print(step + '라고 답변하였지.') print('어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.') answer(number) if __name__ == '__main__': main()
a1874a1895b2128fd99216b4711c9045c6434bc0
cdngnoob/playground
/python/3.1.2/aufgabe312.py
368
3.5
4
from turtle import * def Weihnachtsbaum(x, y): up() goto(x,y) down() setheading(90) forward(40) left(90) forward(60) right(120) forward(120) right(120) forward(120) right(120) forward(60) #Weihnachtsbaum(50, 100) def Weihnachtswald(): for i in range(-200,200,45): Weihnachtsbaum(i,0) Weihnachtswald()
8cf569857f1f7d8c4f259a63a2040781cc43927a
kavin-lee/AI
/DS/day06/03_vec.py
413
3.84375
4
#!/usr/bin/python3 # !coding=utf-8 ''' 函数矢量化 ''' import numpy as np import math as m def foo(x, y): return np.sqrt(x ** 2 + y ** 2) a, b = 3, 4 a = np.arange(3, 9).reshape(2, 3) b = np.arange(4, 10).reshape(2, 3) print('a:', a) print('b:', b) print('foo:', foo(a, b)) # 矢量化处理函数foo函数,使之可以处理矢量数据 foo_vec = np.vectorize(foo) print("foo_vec:", foo_vec(a, 6))
ecf5cda180204ab60c9ddcf1eea66f7332831eb4
wenjuanchendora/Python_Study
/2017-12/2017-12-12.py
1,430
3.96875
4
# 阿姆斯特朗数 # number = int(input("Please enter number: ")) # length = len(str(number)) # sum = 0 # for x in range(length): # sum += int(str(number)[x])**length # if sum == number: # print("%d is an AMSTL number" % number) # else: # print("%d is not an AMSTL number" % number) # minnum = int(input("Please enter min number: ")) # maxnum = int(input("Please enter max number: ")) # print("AMSTL numbers between %d ~ %d: " % (minnum, maxnum)) # for number in range(minnum, maxnum + 1): # sum = 0 # length = len(str(number)) # for x in range(length): # sum += int(str(number)[x])**length # if sum == number: # print(number, end=" ") # number = int(input("Please enter number: ")) # length = len(str(number)) # sum = 0 # var = number # while var > 0: # digit = var % 10 # sum += digit ** length # var //= 10 # if sum == number: # print("%d is an AMSTL number" % number) # else: # print("%d is not an AMSTL number" % number) # minnum = int(input("Please enter min number: ")) # maxnum = int(input("Please enter max number: ")) # print("AMSTL numbers between %d ~ %d: " % (minnum, maxnum)) # for number in range(minnum, maxnum + 1): # sum = 0 # length = len(str(number)) # var = number # while var > 0: # digit = var % 10 # sum += digit ** length # var //= 10 # if sum == number: # print(number, end=" ")
c9c870321e1c8896a730b66f6e3101896d1eb6d6
danielsimonebeira/prova_n1
/atividade3.py
442
4
4
# 3 - Faça um programa que peça uma nota, entre zero e dez. Mostre uma mensagem # caso o valor seja inválido e continue pedindo até que o usuário informe um valor # válido.(2,0) nota = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] contador = 1 while True: valor = int(input("Digite de 1 a 10: ")) for i in nota: if i == valor: print("valor {} Digitado corretamente".format(valor)) exit() contador += 1
0c20bf4e9a4ee8846063d4bbe06b353b66e10063
paiqu/Online-Discussion-Forum
/client.py
7,728
3.53125
4
# Python 3 # Usage: python3 client.py server_IP server_port import sys import socket import json import os import select import threading import time server_IP = sys.argv[1] server_port = int(sys.argv[2]) # boolean to record if the server is down server_is_down = False def handle_connection(connection): global server_is_down global client_socket while not server_is_down: data = connection.sendall(b"check") try: reply = connection.recv(1024) except ConnectionResetError: break if not reply: server_is_down = True # client_socket.close() break time.sleep(0.2) print("\nGoodbye. Server shutting down") connection.close() os._exit(0) # create a socket client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to the server client_socket.connect((server_IP, server_port)) c_socket.connect((server_IP, server_port+1000)) # start a thread to track server's status c_thread = threading.Thread(target=handle_connection, args=(c_socket,)) c_thread.daemon = True c_thread.start() while not server_is_down: # get input from the user username = input("Enter username: ") while not username: print("username can't be empty") username = input("Enter username: ") client_socket.sendall(username.encode()) reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) reply_type = reply.get('type') if reply_type == "True": # username exists password = input("Enter password: ") while not password: print("password can't be empty") password = input("Enter password: ") client_socket.sendall(password.encode()) elif reply_type == "Waiting": # username dose not exist -> create a new account password = input('Enter new password for ' + username + ': ') while not password: print("password can't be empty") password = input('Enter new password for ' + username + ': ') client_socket.sendall(password.encode()) elif reply_type == "False": print(f"{username} has already logged in") continue reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) reply_type = reply.get('type') if reply_type != 'True': print(reply.get('message')) continue print(reply.get('message')) print('Welcome to the forum') while not server_is_down: # print(f"bool now is {server_is_down}") # ask the user for command and then send it to the server # command = input("Enter one of the following commands: CRT, MSG, DLT, EDT, LST, RDT, UPD, DWN, RMV, XIT, SHT: ") while True: print( "Enter one of the following commands: CRT, MSG, DLT, EDT, LST, RDT, UPD, DWN, RMV, XIT, SHT: ", end='', flush=True ) # if c_socket not in select.select([], [c_socket], [])[1]: # server_is_down = True # break command = sys.stdin.readline().strip() # command = input("Enter one of the following commands: CRT, MSG, DLT, EDT, LST, RDT, UPD, DWN, RMV, XIT, SHT: ") if not command: print("Command can't be empty") continue break command_type = command.split()[0] # if UPD -> upload the file to the server if command_type == "UPD": if len(command.split()) != 3: print(f"Incorrect syntax for {command_type}") continue filename = command.split()[2] if not os.path.exists(filename): print(f"The file {filename} does not exist") continue # send the full command to the server client_socket.sendall(command.encode()) # receive the result of checking thread title reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) if reply.get('type') == "False": print(reply.get('message')) continue client_socket.sendall(b"checking filename") # Receive the result of checking filename reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) if reply.get('type') == "False": print(reply.get('message')) continue # transfer the file filesize = str(os.path.getsize(filename)) # send the actual file size to the server first client_socket.sendall(filesize.encode()) with open(filename, 'rb') as f: data = f.read(1024) while data: client_socket.sendall(data) data = f.read(1024) reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) print(reply.get('message')) continue elif command_type == "DWN": if len(command.split()) != 3: print(f"Incorrect syntax for {command_type}") continue # send the full command to the server client_socket.sendall(command.encode()) # receive the result of checking thread title reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) if reply.get('type') == "False": print(reply.get('message')) continue client_socket.sendall(b"checking filename") # Receive the result of checking filename reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) if reply.get('type') == "False": print(reply.get('message')) continue client_socket.sendall(b"getting file size") filename = command.split()[2] # 1. receive the filesize filesize = int(client_socket.recv(1024).decode()) client_socket.sendall(b"downloading the file") # 2. receive the file with open(filename, 'wb') as f: data = client_socket.recv(1204) total = len(data) while data: f.write(data) if total != filesize: data = client_socket.recv(1204) total += len(data) else: break print(f"{filename} successfully downloaded") client_socket.sendall(b"True") continue # send the command to the server client_socket.sendall(command.encode()) # receive the reply from the server reply = client_socket.recv(1024).decode("utf-8") reply = json.loads(reply) if reply.get('type') == "False": # command is invalid print(reply.get('message')) else: # command is valid print(reply.get('message')) if command_type == 'XIT' or command_type == 'SHT': # client_socket.shutdown(socket.SHUT_RDWR) print("closing the socket") # client_socket.shutdown(socket.SHUT_RDWR) client_socket.close() if command_type == 'SHT': server_is_down = True # client_socket.close() sys.exit(0)
d494c29af7c833479b4e794873ba9685c200d727
daniel-reich/ubiquitous-fiesta
/kmruefq3dhdqxtLeM_5.py
321
3.765625
4
def sum_digits(a, b): new = [] while a <= b: new += [a] a += 1 digits = [] for x in new: while x > 0: digits += [x % 10] x //= 10 total = 0 for x in digits: total += x return total ​ def sum_digits(a, b): return eval('+'.join('+'.join(i for i in str(j)) for j in range(a, b + 1)))
749f21aeee336c443a2060424c0dae6fab471b38
Jayasree-Repalla/Innomatics_Internship_APR_21
/Python Task Day4/String Validators.py
967
3.53125
4
if __name__ == '__main__': s = input() l,m,n,o,p=0,0,0,0,0 for i in s: if (i.isalnum()): print("True") break else: l=l+1 if l==len(s): print("False") for i in s: if (i.isalpha()): print("True") break else: m=m+1 if m==len(s): print("False") for i in s: if (i.isdigit()): print("True") break else: n=n+1 if n==len(s): print("False") for i in s: if (i.islower()): print("True") break else: o=o+1 if o==len(s): print("False") for i in s: if (i.isupper()): print("True") break else: p=p+1 if p==len(s): print("False")
cefdffeffbf47be40b65ef3e646f50a2243f4bf4
edybahia/python2018
/code_curso/mes_de_nascimento.py
1,217
4.4375
4
#criando a tupla # Lista, tem a possibilidade de ser mudada os seus valores que estão guardados, # neste caso estes ela e mutada, sendo assim posso alocar qualquer conteudo lá dentro # Já as TUPLAs, são valores fixos sem possibilidade de mudanças. # Comando Len checa quantos caracter tem dentro de um TUPLA print(len(mes)) mes = ('Janeiro','Fevereiro','março','abrir','maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro') #neste ponto e solicitado um pedido para o usuário digitar a data de nascimento no formato. lembrando que Python, associa este # tipo de comando como resposta INPUT. logo no padrão é um string que posso manipular, isso que eu faço a seguir ano = input('Digite o ano do seu nascimento DD-MM-AAAA: ') # comando ano[3:5], pega extamente o valor entre - - no caso o mês # Em seguida tenho que associar este valor como inteiro, para que possa ser interpretado pelo comando seguinte e "visitar" a lista # mes( variavel) como está sendo númerico então ele vai buscar na LISTA mes o valor do mês # Porém a lista começa de 0 - 11, então preciso diminuir (-1) para acertar sempre o mês print('Voce nasceu no mês de ', mes[int(ano[3:5])-1])
bd312ef4abc9614a4f6a088b0400b59947045a34
kjeffreys/pythonKit
/dataLoadingStorageAndFileFormats/dataIOwithPandas/delimitedFormats/myDialect.py
566
3.78125
4
''' CSV files can have a variety of formatting flavors. To define a new format with a different: 1) delimiter, 2) string quoting convention, or 3) line terminator, define a subclass of csv.Dialect ''' import csv import pandas as pd f = 'csvFiles/example.csv' class myDialect(csv.Dialect): lineterminator = '\n' delimiter = ';' quotechar = '"' quoting = csv.QUOTE_MINIMAL if __name__ == "__main__": reader1 = csv.reader(f, delimiter="|") print(reader1) reader2 = csv.reader(f, dialect=myDialect) print(reader2)
d5dd23ba77169c7cd1336d3706e3f8d3cd377929
ssoso27/Smoothie2
/pythAlgo/programmers/level2/find_prime_number.py
1,237
3.78125
4
prime_number = [] result = set() def make_prime_number(l): global prime_number N = 10 ** l prime_number = [True for _ in range(N)] prime_number[0] = False prime_number[1] = False for i in range(2, int(N**0.5)+1): if prime_number[i]: m = 2 while True: if i*m >= N: break prime_number[i*m] = False m += 1 return prime_number def is_prime_number(num): return prime_number[num] def permutation(idx, selected, maken, numbers): if maken != "" and is_prime_number(int(maken)): result.add(int(maken)) if idx == len(numbers): return for i in range(len(numbers)): if not selected[i]: maken += numbers[i] selected[i] = True permutation(idx+1, selected, maken, numbers) selected[i] = False maken = maken[:-1] def solution(numbers): global result result = set() make_prime_number(len(numbers)) selected = [False for _ in range(len(numbers))] permutation(0, selected, "", numbers) return len(result) ex = [ ("17", 3), ("011", 2) ] for n, r in ex: print(solution(n) == r)
1437dc91a974940d13397027c0df03be9e3069e7
alexwohletz/PyTutorScripts
/write_dict_tocsv.py
226
3.609375
4
with open('dict.csv','w') as csv_file: writer = csv.writer(csv_file) writer.writerow(["Colname1","Colname2"]) for key,value in {item[0]:item[1] for item in zip(l1,l2)}.items(): writer.writerow([key,value])
bacd51a3ab3c65745db13e568e172db186693813
VivekMishra02/Naive_Bayes_Classifier
/BaysClassifier.py
3,842
3.65625
4
# Example of calculating class probabilities from math import sqrt from math import pi from math import exp import pandas as pd # Split the dataset by class values, returns a dictionary def separate_by_class(dataset): separated = dict() for i in range(len(dataset)): vector = dataset[i] class_value = vector[-1] if (class_value not in separated): separated[class_value] = list() separated[class_value].append(vector) return separated # Calculate the mean of a list of numbers def mean(numbers): return sum(numbers) / float(len(numbers)) # Calculate the standard deviation of a list of numbers def stdev(numbers): avg = mean(numbers) variance = sum([(x - avg) ** 2 for x in numbers]) / float(len(numbers) - 1) return sqrt(variance) # Calculate the mean, stdev and count for each column in a dataset def summarize_dataset(dataset): d = dataset for x in d: del(x[-1]) summaries = [(mean(column), stdev(column), len(column)) for column in zip(*d)] #del (summaries[-1]) return summaries # Split dataset by class then calculate statistics for each row def summarize_by_class(dataset): separated = separate_by_class(dataset) summaries = dict() for class_value, rows in separated.items(): summaries[class_value] = summarize_dataset(rows) return summaries # Calculate the Gaussian probability distribution function for x def calculate_probability(x, mean, stdev): exponent = exp(-((x - mean) ** 2 / (2 * stdev ** 2))) return (1 / (sqrt(2 * pi) * stdev)) * exponent # Calculate the probabilities of predicting each class for a given row def calculate_class_probabilities(summaries, row, feature): probabilities = {'w1':1/2,'w2':1/2,'w3':0} for class_value, class_summaries in summaries.items(): for i in range(len(class_summaries)-feature): mean, stdev, _ = class_summaries[i] probabilities[class_value] *= calculate_probability(row[i], mean, stdev) return probabilities # Train calculating class probabilities datasets = pd.read_csv("TrainData.csv") dataset = datasets.values.tolist() # Test calculating class probabilities test_datasets = pd.read_csv("TestData.csv") test_datasets = test_datasets.values.tolist() summaries = summarize_by_class(dataset) res1,res2,res3 = [],[],[] count1,count2,count3 = 0,0,0 #For only X1 for x in range(len(test_datasets)): probabilities = calculate_class_probabilities(summaries, test_datasets[x],2) if probabilities["w1"] > probabilities["w2"]: res1.append("w1") else: res1.append("w2") for x in range(len(test_datasets)): if res1[x] != test_datasets[x][3]: count1 +=1 print("ANS 3 B) The training error for only X1 is ",count1/len(test_datasets)*100,"%") #For Only X1 and X2 for x in range(len(test_datasets)): probabilities = calculate_class_probabilities(summaries, test_datasets[x],1) if probabilities["w1"] > probabilities["w2"]: res2.append("w1") else: res2.append("w2") for x in range(len(test_datasets)): if res2[x] != test_datasets[x][3]: count2 += 1 print("ANS 3 C) The training error for only X1 and X2 is ", count2 / len(test_datasets)*100,"%") #For all the three features for x in range(len(test_datasets)): probabilities = calculate_class_probabilities(summaries, test_datasets[x],0) if probabilities["w1"] > probabilities["w2"]: res3.append("w1") else: res3.append("w2") for x in range(len(test_datasets)): if res2[x] != test_datasets[x][3]: count3 += 1 print("ANS 3 D) The training error for only X1, X2 and X3 is ", count3 / len(test_datasets) * 100, "%")
57c6e61deb8c91b3add30bd795811608fabf6896
sarinaxie/K9-trainer
/euclidean_distance.py
887
3.828125
4
""" Name: Sarina Xie UNI: sx2166 This file contains a function that calculates the euclidean distance between two 1 x (n+1) vectors. """ import math #for testing from create_data import create_data from integerize_labels import integerize_labels from split import split def euclidean_distance(x1,x2): """Function that calculates the euclidean distance b/w 2 vectors""" sum = 0 #len(x1.T)-1 is the number of elements excluding the label for i in range(0,len(x1.T)-1): dif = math.pow(x1[0,i] - x2[0,i], 2) sum += dif distance = math.sqrt(sum) return distance if __name__ == '__main__': irisdata = create_data("iris") irisdata = integerize_labels(irisdata) train, test = split(irisdata[0]) a = test[0] b = test[1] print("row 0 of test", a) print("row 1 of test", b) print(euclidean_distance(a,b))
e02fe717ec2e361a4c4c1dcf085439a7d9be7e9d
patriciaslessa/pythonclass
/RepeticaoFor_14.py
428
3.640625
4
#def lista_2_ex_1(): """ Faça um programa que peça 10 números inteiros, calcule e mostre a quantidade de números pares e a quantidade de números impares. """ n_par = 0 n_impar = 0 for i in range(1,11): number = input("Digite um numero: ") n = int(number) print(f" {n}") if (n % 2 == 0 ): n_par = n_par + 1 else: n_impar = n_impar + 1 print (f"n_par: {n_par} e n_impar: {n_impar}")
3cebc64b953e15f1ca038abb92cb6a29319638a6
Zovengrogg/ProjectEuler
/Euler45_TriangularPentagonalAndHexagonal.py
551
3.515625
4
# Triangular, Pentagonal, and Hexagonal https://projecteuler.net/problem=45 from math import sqrt def isPentagonal(n): number = (sqrt(24*n + 1) + 1)/6 if number.is_integer(): return True return False def isTriangular(n): number = (sqrt(8*n + 1) + 1)/2 if number.is_integer(): return True return False found = False i = 143 while not found: i += 1 hexagonal = 2*i*i-i if isPentagonal(hexagonal) and isTriangular(hexagonal): found = True print(hexagonal)
41e72e8a5de24c5c7c4215b669c5d4f1c2fb61f3
AdamKnowles/coins-to-cash
/coinsToCash.py
1,158
4.21875
4
# Create a function called calc_dollars. In the function body, define a dictionary and store it in a variable named piggyBank. The dictionary should have the following keys defined. # quarters # nickels # dimes # pennies # For each coin type, give yourself as many as you like. # piggyBank = { # "pennies": 342, # "nickels": 9, # "dimes": 32 # } # Once you have given yourself a large stash of coins in your piggybank, look at each key and perform the appropriate math on the integer value to determine how much money you have in dollars. Store that value in a variable named dollarAmount and print it. # Given the coins shown above, the output would be 7.07 when you call calc_dollars() def calc_dollars(): piggy_bank = { "quarters": 500, "pennies": 100, "nickels": 400, "dimes": 100 } quarter_amount = piggy_bank["quarters"] /4 penny_amount = piggy_bank["pennies"] /100 nickel_amount = piggy_bank["nickels"] /20 dime_amount = piggy_bank["dimes"] /10 total_amount = quarter_amount + nickel_amount + penny_amount + dime_amount print(total_amount) calc_dollars()
d7d00aa1981b5908e0533106b69690a833b4f5ce
parthoza08/python
/ch-9_prq9.py
168
3.59375
4
with open("file.txt") as F: F1 = F.read() with open("copy.txt") as s: F2 = s.read() if F1 == F2: print("both are same files") else: print("not same")
3557b414b7fc221d7bef53087bd89e8c8efcc130
kdk745/Projects
/CS313E/Josephus.py
3,190
3.625
4
# File: Josephus.py # Description: # Student Name: Juanito Taveras # Student UT EID: jmt3686 # Partner Name: Kayne Khoury # Partner UT EID: # Course Name: CS 313E # Unique Number: # Date Created: 4/2/2015 # Date Last Modified: 4/2/2015 class Link(object): def __init__ (self, data, next = None): self.data = data self.next = next def __str__(self): return str(self.data) class CircularList(object): # Constructor def __init__ ( self ): self.first = Link(None,None) self.first.next = self.first # Insert an element in the list def insert ( self, item): newLink = Link(item) newLink.next = self.first self.first = newLink def find (self, data): current = self.first if current == None: return None while (current.data != data): if (current.next == None): return None else: current = current.next return current # Delete a link with a given key def delete (self, data): current = self.first # make new variable, "current", equal to self.first previous = self.first if current == None: return None while current.data != data: if current.next == None: return None else: previous = current current = current.next if current == self.first: self.first = self.first.next else: previous.next = current.next return current # Delete the nth link starting from the Link start # Return the next link from the deleted Link def deleteAfter ( self, start, n ): current = self.find(start) # returns current, which is first person probe = self.find(start)# first = current.data count = n count2 = n while count > 1 and current.data != None: probe = probe.next count -=1 while count2 > 0 and probe.data != None: current = current.next count2 -= 1 probe.next = current.next # Return a string representation of a Circular List def __str__ ( self ): current = self.first while current.data != None: print(current.data) current = current.next ''' while self != None: print (self.first) self = self.next ''' def __len__ (self): current = self.first length = 0 if current == None: return None while current != None: length += 1 current = current.next return length # return str(self.first) def main(): inFile = open ("./josephus.txt", "r") num_sold = inFile.readline() num_sold = int(num_sold.strip()) first_sold = inFile.readline() first_sold = int(first_sold.strip()) elim_num = inFile.readline() elim_num = int(elim_num.strip()) lyst = CircularList() for sold in range (1, num_sold+1): lyst.insert(sold) start = str (lyst.find (first_sold)) ''' while len(lyst) > 1: next_delete = (int(str(start)) + elim_num) current = lyst.find (next_delete) print (current) lyst.delete(current) self.first = ''' lyst.deleteAfter(1,3) print(lyst) main()
fa0eebc063491f3b68db17e2ab193ab28c57da04
camiloprado/Curso-Python
/Aula 15.py
256
4.03125
4
import math angulo = float(input('Digite o ângulo: ')) print('Para os ângulo de {:.0f}°:\nSeno = {:.1f}\nCosseno = {:.1f}\nTangente = {:.1f}'.format(angulo, math.sin(math.radians(angulo)), math.cos(math.radians(angulo)), math.tan(math.radians(angulo))))
6d1c547df083e7ce7ecdbfb1377cbc2ff212fd23
leocjj/holbertonschool-higher_level_programming
/0x10-python-network_0/6-peak.py
1,022
3.953125
4
#!/usr/bin/python3 """This module has a function that finds a peak in a list of unsorted integers. Prototype: def find_peak(list_of_integers): You are not allowed to import any module Your algorithm must have the lowest complexity 6-peak.py must contain the function 6-peak.txt must contain the complexity of your algorithm: O(log(n)), O(n), O(nlog(n)) or O(n2) """ def find_peak(list_of_integers): """function that finds a peak in a list of unsorted integers Args: list_of_integers: list of unsorted integers. Returns: int: peak of the list """ l = list_of_integers size = len(l) if size == 0: return None if size == 1: return l[1] lo = 0 hi = size - 1 while lo < hi: mid = (lo + hi) // 2 if l[mid] <= l[mid + 1]: lo = mid + 1 elif l[mid - 1] >= l[mid]: hi = mid - 1 elif l[mid - 1] <= l[mid] and l[mid] >= l[mid + 1]: return l[mid] return l[lo]
e491f0183ac88e71e4a0615c6cbdd69664db1ad5
jsoto3000/js_udacity_Intro_to_Python
/tiles.py
204
3.609375
4
# Fill this in with an expression that calculates how many tiles are needed. print(9*7 + 5*7) # Fill this in with an expression that calculates how many tiles will be left over. print(17*6 - (9*7 + 5*7))
1c2c0cbee56b2e828cb9b5b5e796ca1e81e4f2d7
kosemMG/python_avratech
/exercise-5-dots.py
148
3.625
4
for i in range(15): if i <= 5: print('* ' * i) elif i <= 9: print('* ' * (10 - i)) else: print('* ' * (15 - i))
f19332f441ec20a1c70835d6aea92900addb9400
alllllli1/Python_NanJingUniversity
/2.4.1/break_continue_else.py
498
3.875
4
# -*- coding: utf-8 -*- # @Time : 2020/3/20 10:32 # @Author : wscffaa # @Email : 1294714904@qq.com # @File : break_continue_else.py # @Software: PyCharm # break作用:终止当前循环,转而执行循环之后的语句 #输出2-100之间的素数:2~根号x 只要没有可以整除的数,x就是素数 from math import sqrt j = 2 while j <= 100 : i = 2 k = sqrt(j) while i <= k : if j%i == 0 : break i = i + 1 if i > k : print(j, end=' ') j += 1
12fa7134c14a3521294c1e62e08fafa23dffae2f
f-e-d/2021-Algorithm-Study
/Programmers/jiwoo/2021_kakao_blind/메뉴리뉴얼.py
504
3.546875
4
from collections import Counter from itertools import combinations def solution(orders, course): result = [] for course_size in course: order_combinations = [] for order in orders: order_combinations += combinations(sorted(order), course_size) most_ordered = Counter(order_combinations).most_common() result += [menu for menu, count in most_ordered if count > 1 and count == most_ordered[0][1]] return [''.join(menu) for menu in sorted(result)]
8ce13f17f22c1016b281b51bd33f421f240374fd
PritamTCS/python_assignment
/assignment4/str.py
390
4.3125
4
#!/usr/bin/python ## extracting first& last 2 charcter from a given string def pair(s1): if len(s1) >2: s2=s1[0:2]+s1[-2:] #return s2 print("First&last 2 charcters of the string is:",s2) else: #return "" print("length of string is less than 2") s=input("Enter a string:") st=pair(s) #print("First&last 2 charcters of the string is:",st)
9cb9372bdaecb5644ae766b239b3747f3e1e4ffe
tianyulang/Database
/assignment4.py
12,068
3.640625
4
import pandas as pd import sqlite3 import matplotlib.pyplot as plt import folium def q1(qq1,connection): start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') crime_type = input('Enter crime type ') df = pd.read_sql('select month1,count(Incidents_Count) from (select distinct crime_incidents.Month as month1 from crime_incidents where typeof(month1) = \"integer\") left outer join (select * , crime_incidents.Month as month2 from crime_incidents where crime_incidents.Year >= ' + str(start_year) + ' AND crime_incidents.Year <= ' + str(end_year) + ' AND crime_incidents.Crime_Type = \"' + str(crime_type) + '\" ) on month1 = month2 group by month1', connection) plot = df.plot.bar(x="month1") plt.plot() plt.savefig('Q1-'+str(qq1)+'.png') def q2(qq2,conn): m = folium.Map(location=[53.5444,-113.323], zoom_start=11)#connect map c=conn.cursor()#create cursor a=input('Enter number of locations: ') #to select top neighbourhood c.execute('select (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) as number,population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude from population,coordinates where population.Neighbourhood_Name=coordinates.Neighbourhood_Name and number <> 0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0) order by population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE desc limit :a;',{"a":a}) rows=c.fetchall()#get result #draw circles for i in range(0,len(rows)-1): folium.Circle( location=[rows[i][2], rows[i][3]], # location popup=str(rows[i][1])+"<br>"+str(rows[i][0]) , # popup text radius= 0.1*rows[i][0], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) #to select last neighbourhood c.execute('select (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) as number,population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude from population ,coordinates where population.Neighbourhood_Name=coordinates.Neighbourhood_Name and number <> 0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0) order by population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE asc limit :a;',{"a":a}) rows2 = c.fetchall() if len(rows) !=0 and len(rows2)!=0: for i in range(0,len(rows2)-1): folium.Circle( location=[rows2[i][2], rows2[i][3]], # location popup=str(rows2[i][1])+"<br>"+str(rows2[i][0]) , # popup text radius= 0.1*rows2[i][0], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) lasttop = rows[len(rows)-1][0] lastmin = rows2[len(rows2)-1][0] #deal with tie cases c.execute('select (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) as number,population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude from population ,coordinates where population.Neighbourhood_Name=coordinates.Neighbourhood_Name and number <> 0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0) and (number=:a or number=:b);',{"a":int(lasttop),"b":int(lastmin)}) rows3=c.fetchall() s=len(rows3) for i in range(len(rows3)): folium.Circle( location=[rows3[i][2], rows3[i][3]], # location popup=str(rows3[i][1])+"<br>"+str(rows3[i][0]) , # popup text radius= 0.1*rows3[i][0], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) m.save('Q2-'+str(qq2)+'.html') conn.commit() def q3(qq3,conn): m = folium.Map(location=[53.5444,-113.323], zoom_start=11)#connect map c=conn.cursor()#create cursor #get input start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') crime_type = input('Enter crime type ') number=input('Enter number of neighborhoods ') #to select top crime count neighbourhood c.execute("select crime_incidents.Neighbourhood_Name, SUM(crime_incidents.Incidents_Count) as number ,coordinates.Latitude,coordinates.Longitude from crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents. Year <= :b AND crime_incidents.Crime_Type = :c and crime_incidents.Neighbourhood_Name=coordinates.Neighbourhood_Name and(coordinates.Latitude<>0 or coordinates.Longitude<>0) group by crime_incidents.Neighbourhood_Name order by number DESC LIMIT :d;", {"a":int(start_year),"b":int(end_year),"c":crime_type,"d":number}) rows=c.fetchall() for i in range(0,len(rows)-1): folium.Circle( location=[rows[i][2], rows[i][3]], # location popup=str(rows[i][0])+"<br>"+str(rows[i][1]) , # popup text radius= 2*rows[i][1], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) if len(rows)!=0: lasttop=int(rows[len(rows)-1][1]) #deal with tie cases c.execute("select Neighbourhood_Name,number ,Latitude,Longitude from (select crime_incidents.Neighbourhood_Name, SUM(crime_incidents.Incidents_Count) as number ,coordinates.Latitude,coordinates.Longitude from crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents. Year <= :b AND crime_incidents.Crime_Type = :c and crime_incidents.Neighbourhood_Name=coordinates.Neighbourhood_Name and (coordinates.Latitude<>0 or coordinates.Longitude<>0) group by crime_incidents.Neighbourhood_Name) where number=:d;", {"a":int(start_year),"b":int(end_year),"c":crime_type,"d":lasttop}) rows2=rows=c.fetchall() for i in range(len(rows2)): folium.Circle( location=[rows2[i][2], rows2[i][3]], # location popup=str(rows2[i][0])+"<br>"+str(rows2[i][1]) , # popup text radius= 2*rows2[i][1], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) m.save('Q3-'+str(qq3)+'.html') conn.commit() def q4(qq4,conn): m = folium.Map(location=[53.5444,-113.323], zoom_start=11)#connect map c=conn.cursor()#create cursor start_year= input('Enter start year(YYYY) ') end_year = input('Enter end year(YYYY) ') neighborhoods = input('Enter numebr of neighborhoods ') #to select the top radio neighbourhood c.execute('select population.Neighbourhood_Name,max(crime_incidents.Incidents_Count),crime_incidents.Crime_Type,coordinates.Latitude,coordinates.Longitude,cast(sum(crime_incidents.Incidents_Count)as float)/(population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE)as number from population,crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents.Year <= :b and population.Neighbourhood_Name=crime_incidents.Neighbourhood_Name and (population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE) <>0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0)and population.Neighbourhood_Name=coordinates.Neighbourhood_Name group by population.Neighbourhood_Name order by number desc limit :c',{"a":int(start_year),"b":int(end_year),"c":int(neighborhoods)}) rows=c.fetchall() if len(rows)!=0: lasttop=rows[int(neighborhoods)-1][5] #to select the most frenquntly crime type for i in range(len(rows)): s='' c.execute('select Crime_Type from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type) where number = (select max(number) from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type))',{"a":int(start_year),"b":int(end_year),"d":rows[i][0]}) rows2=c.fetchall() for j in range(len(rows2)): s=s+'<br>'+rows2[j][0] folium.Circle( location=[rows[i][3], rows[i][4]], # location popup=str(rows[i][0])+s+"<br>"+str(rows[i][5]) , # popup text radius= 1000*rows[i][5], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) #to deal with tie cases c.execute('select Neighbourhood_Name,Latitude,Longitude,number from(select population.Neighbourhood_Name,coordinates.Latitude,coordinates.Longitude,cast(sum(crime_incidents.Incidents_Count)as float)/(population.CANADIAN_CITIZEN+population.NON_CANADIAN_CITIZEN+population.NO_RESPONSE)as number from population,crime_incidents,coordinates where crime_incidents.Year >=:a AND crime_incidents.Year <= :b and population.Neighbourhood_Name=crime_incidents.Neighbourhood_Name and population.Neighbourhood_Number<>0 and (coordinates.Latitude<>0 or coordinates.Longitude<>0)and population.Neighbourhood_Name=coordinates.Neighbourhood_Name group by population.Neighbourhood_Name) where number =:c',{"a":int(start_year),"b":int(end_year),"c":int(lasttop)}) rows3=c.fetchall() # to find the most frenquntly crime type in tie cases for i in range(len(rows3)): s='' c.execute('select Crime_Type from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type) where number = (select max(number) from (select crime_incidents.Crime_Type ,sum(crime_incidents.Incidents_Count)as number from crime_incidents where crime_incidents.Year >=:a AND crime_incidents.Year <=:b and crime_incidents.Neighbourhood_Name=:d group by crime_incidents.Crime_Type))',{"a":int(start_year),"b":int(end_year),"d":rows[i][0]}) rows2=c.fetchall() for j in range(len(rows2)): s=s+'<br>'+rows2[j][0] folium.Circle( location=[rows3[i][1], rows3[i][2]], # location popup=str(rows[i][0])+s+"<br>"+str(rows[i][3]) , # popup text radius= 1000*rows[i][3], # size of radius in meter color= 'crimson', # color of the radius fill= True, # whether to fill the map fill_color= 'crimson' # color to fill with ).add_to(m) m.save('Q4-'+str(qq4)+'.html') conn.commit() def main(): qq1=0 qq2=0 qq3=0 qq4=0 command = '' connection = sqlite3.connect('./' + input('Enter database name: ')) while command != 'E': command = input('1:Q1\n2:Q2\n3:Q3\n4:Q4\nE:Exit\n') if command=='1': qq1=qq1+1 q1(qq1,connection) if command=='2': qq2=qq2+1 q2(qq2,connection) if command=='3': qq3=qq3+1 q3(qq3,connection) if command=='4': qq4=qq4+1 q4(qq4,connection) connection.close() if __name__ == "__main__": main()
9e6264e52999f19787fd542e82a39fe29d9eabd0
Jonathancui123/Coding-Interview
/PythonProjects/448. Find All Numbers Disappeared in an Array.py
1,833
3.828125
4
# CYCLICE SORT, ARRAY, (Use indices to represent numbers) # Ex 1: [3,3,3] -> [1,2] ''' O(n^2) time [brute] : For each number in [1, n], check if it is in nums. If it is not, add it to the output list O(n) time, O(n) space [set]: Create a set initialized to contain [1,n] and remove each element that we see in nums. Or use a boolean list of size n initialized to False, and set index i - 1 to true if i is found/ We go through the set or the list and populate the final solution O(n) time, O(1) 'extra' space: Cyclic sort to put each number, i, into index i-1. If the duplicate already exists in i-1, let it rest in the current position --> Each index will hold the number (index + 1) if (index + 1) exists. Iterate through nums and find indices that don't hold index + 1 ANOTHER SOLUTION: Since each index can be one-to-one mapped to a number, and all numbers were positive, simpy set an index to negative to mark the number as found. Return the numbers represented by indices where the element is unmarked ''' class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: cycleStartIndex = 0 while cycleStartIndex < len(nums): temp = nums[cycleStartIndex] currentIndex = temp - 1 while temp != cycleStartIndex + 1 and nums[currentIndex] != temp: nextTemp = nums[currentIndex] nums[currentIndex] = temp temp = nextTemp currentIndex = temp - 1 nums[cycleStartIndex] = temp cycleStartIndex += 1 result = [] for i in range(len(nums)): if nums[i] != i + 1: result.append(i+1) return result