text
stringlengths
37
1.41M
class tree_node: def __init__(self,data=None): self.data=data self.left=None self.right=None def append(self,data): if(self.data is None): self.data=data self.right=None self.left=None else: temp=tree_node(data) curr=self while(True): if(data>=curr.data): if(curr.right is None): curr.right=temp break else: curr=curr.right else: if(curr.left is None): curr.left=temp break else: curr=curr.left def print_tree(Tree): if(Tree.left): print_tree(Tree.left) if(Tree.right): print_tree(Tree.right) print(Tree.data) my_tree=tree_node() my_tree.append('5') my_tree.append('6') my_tree.append('4') print_tree(my_tree)
class Node: def __init__(self,data): self.data=data self.left=None self.right=None self.parent=None self.height=1 self.size=1 class AVL: def __init__(self): self.head=None def node_size(self,node): if node: return 1+self.node_size(node.left)+self.node_size(node.right) else: return 0 def height(self,i): if(i is None):return 0 else:return 1+max(self.height(i.left),self.height(i.right)) def find(self,data): curr=self.head while(True): if(curr.data==data or curr.data is None): return curr elif(curr.data>data): curr=curr.left elif(curr.data<data): curr=curr.right def rc_size(self,node): if(node): node.size=self.node_size(node) self.rc_size(node.left) self.rc_size(node.right) def insert(self,data): if self.head is None: self.head=Node(data) else: curr=self.head while(True): if(curr.data>=data): if(curr.left): curr=curr.left else: curr.left=Node(data) curr.left.parent=curr self.rebalance(curr.left) break elif(curr.data<data): if(curr.right): curr=curr.right else: curr.right=Node(data) curr.right.parent=curr self.rebalance(curr.right) break self.rc_size(self.head) def adjustheight(self,head): if(head): head.height=self.height(head) self.adjustheight(head.left) self.adjustheight(head.right) def os(self,node,k): s=node.left.size if k== s+1: return node.data elif k<s+1: return self.os(node.left,k) else: return self.os(node.right,k-s-1) def rotate_right(self,X): B = X.left.right X.left.parent = X.parent if X.parent and X == X.parent.left: X.parent.left = X.left elif X.parent and X == X.parent.right: X.parent.right = X.left else: self.head = X.left X.parent = X.left X.left.right = X X.left = B if X.left: X.left.parent = X def rotate_left(self, X): B = X.right.left X.right.parent = X.parent if X.parent and X == X.parent.left: X.parent.left = X.right elif X.parent and X == X.parent.right: X.parent.right = X.right else: self.head=X.right X.parent = X.right X.right.left = X X.right = B if X.right: X.right.parent = X def p(self,head): if(head): if(head.left): print(head.data,"->",head.left.data) self.p(head.left) if(head.right): print(head.data,"->",head.right.data) self.p(head.right) def rebalance(self,node): p=node.parent if(node.left): lh=node.left.height else: lh=0 if node.right: rh=node.right.height else: rh=0 if(lh>rh+1): self.rebalance_right(node) if(rh>lh+1): self.rebalance_left(node) self.adjustheight(node) if(p): self.rebalance(p) self.rc_size(self.head) def rebalance_right(self,node): m=node.left if(m.left): lh=m.left.height else: lh=0 rh=0 if m.right: rh=m.right.height if(rh>lh): self.rotate_left(m) self.rotate_right(node) def rebalance_left(self,node): m=node.right if(m.left): lh=m.left.height else: lh=0 rh=0 if m.right: rh=m.right.height if(lh>rh): self.rotate_right(m) self.rotate_left(node) a=AVL() while(True): i=int(input()) if(i==1): l=list(map(int,input().split())) for i in l: a.insert(i) elif(i==2): a.p(a.head) print("________________________________________") elif(i==3): q=int(input()) print(a.os(a.head,q)) else: exit()
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all the match records from the database.""" DB = connect() c = DB.cursor() c.execute("DELETE FROM matches;") DB.commit() DB.close() def deletePlayers(): """Remove all the player records from the database.""" DB = connect() c = DB.cursor() c.execute("DELETE FROM players;") DB.commit() DB.close() def countPlayers(): """Returns the number of players currently registered.""" DB = connect() c = DB.cursor() c.execute("SELECT count(*) FROM players;") counts = c.fetchall()[0][0] DB.close() return counts def registerPlayer(name): """Adds a player to the tournament database. The database assigns a unique serial id number for the player. (This should be handled by your SQL database schema, not in your Python code.) Args: name: the player's full name (need not be unique). """ DB = connect() c = DB.cursor() c.execute("INSERT INTO players (name) VALUES (%s);",(name,)) DB.commit() DB.close() def playerStandings(): """Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches): id: the player's unique id (assigned by the database) name: the player's full name (as registered) wins: the number of matches the player has won matches: the number of matches the player has played """ DB = connect() c = DB.cursor() c.execute("select players.id AS id, players.name AS name, COALESCE(sum(matches.result),0) AS wins,COALESCE(count(matches.result),0) AS matches from players left join matches on players.id = matches.id GROUP BY players.id ORDER BY wins DESC;") result = c.fetchall() DB.close() return result def reportMatch(winner, loser): """Records the outcome of a single match between two players. Args: winner: the id number of the player who won loser: the id number of the player who lost """ DB = connect() c = DB.cursor() winner_sql = "INSERT INTO matches(id,result) VALUES (%s, 1);" loser_sql = "INSERT INTO matches(id,result) VALUES (%s, 0);" c.execute(winner_sql,(winner,)) c.execute(loser_sql,(loser,)) DB.commit() DB.close() def swissPairings(): """Returns a list of pairs of players for the next round of a match. Assuming that there are an even number of players registered, each player appears exactly once in the pairings. Each player is paired with another player with an equal or nearly-equal win record, that is, a player adjacent to him or her in the standings. Returns: A list of tuples, each of which contains (id1, name1, id2, name2) id1: the first player's unique id name1: the first player's name id2: the second player's unique id name2: the second player's name """ standings = playerStandings(); return [(standings[i-1][0], standings[i-1][1], standings[i][0], standings[i][1]) for i in range(1, len(standings), 2)] #DB = connect() #c = DB.cursor() #c.execute("select t1.id as id1, t1.name as name1, t2.id as id2, t2.name as name2 from tournament t1, tournament t2 where t1.matches = t2.matches and t1.wins = t2.wins and t1.wins>t2.wins;") #pairs = [{'id1': row[0], 'name1':str(row[1]),'id2': row[2], 'name2':str(row[3]) } for row in c.fetchall() ] #DB.close() #return pairs
#!/usr/env python aeronaves = [] aeroportos = [] def menu(titulo, opcoes): while True: print("=" * len(titulo), titulo, "=" * len(titulo), sep="\n") for i, (opcao, funcao) in enumerate(opcoes, 1): print("[{}] - {}".format(i, opcao)) print("[{}] - Retornar/Sair".format(i+1)) op = input("Opção: ") if op.isdigit(): if int(op) == i + 1: # Encerra este menu e retorna a função anterior break if int(op) < len(opcoes): # Chama a função do menu: opcoes[int(op) - 1][1]() continue print("Opção inválida. \n\n") def principal(): opcoes = [ ("Adicionar", adicionar), ("Listar", listar), ("Procurar", procurar) ] return menu("Menu principal", opcoes) def adicionar(): opcoes = [ ("Aeronaves", adicionar_aeronave), ("Aeroportos", adicionar_aeroporto), # ... ] return menu("Adicionar", opcoes) def adicionar_aeronave(): aeronaves.append(input("Nova aeronave: ")) def adicionar_aeroporto(): aeroportos.append(input("Nova aeronave: ")) #... def listar(): ... def procurar(): ... def systeminfo(): ... def ping (): ... def principal()
import random qas = [ ('What is the brand name for acetaminophen? ', 'Tylenol'), ('What is the brand name for lacosamide? ', 'Vimpat'), ('What is the brand name for levetiracetam? ', 'Keppra') ] random.shuffle(qas) numRight = 0 for question, rightAnswer in qas: answer = input(question + '') if answer.lower() == rightAnswer.lower(): print('Right') numRight = numRight + 1 else: print('Nope! It\'s ' + rightAnswer) print('You got %d right and %d wrong.' %(numRight, len(qas) - numRight))
#! /usr/bin/python import socket import sys import argparse host = 'localhost' data_payload = 4098 backlog = 5 def echo_server(port): """A simple echo server""" # Create socket object sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Enable reuse address sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) # Bind the socket to a address server_address = (host,port) sock.bind(server_address) print "Start service on port : %d" % port sock.listen(backlog) while True: print "Waiting to receive from client..." client,addr = sock.accept() recv_data = client.recv(data_payload) if recv_data: response = "OK.I have received" size = client.send(response) print "Sending %s byte to client." % size client.close() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Socket echo server') parser.add_argument('--port',action='store',dest='port',type=int,required=True) given_args = parser.parse_args() port = given_args.port echo_server(port)
''' DATA FRAME INDEXING AND LOADING ''' import os import pandas as pd os.chdir ("/home/samrat/Documents/Git/PYTHON/PANDAS") df = pd.read_csv('DATA-FILES/olympics.csv') df.head() #Changing the index to column0 AND skipping the 1st row. df = pd.read_csv('DATA-FILES/olympics.csv', index_col=0, skiprows=1) print (df.head()) #This is not a list data type. Rather it is 'index' data type from pandas, which behaves as a list of strings. col_list = df.columns col_list type(col_list) #col_list is a list of strings. So, each element will be a string. And then you can slice strings character wise providin the slicing operators. a = col_list[0] a a[:1] a[:2] a[:3] col = col_list[1] col col[:1] col[:2] col[:3] col[:4] #even u went past the end. no probs. col[:5] col[4:] #in the rename function, inside the dictionary known as column, provide the index as the name of the value of the column you want to replace, and the value to the index:value pair should be the new value. #df.rename(columns = {'old_value':'new_value'}, inplace=True) df.rename(columns = {col:'Gold'+col[4:]}, inplace = True) col new_col = df.columns[1] new_col df.head() #changing the names of the columns for col in df.columns: if col[:2] == '01': df.rename(columns = {col:'Gold'+col[4:]}, inplace = True) if col[:2] == '02': df.rename(columns = {col:'Silver'+col[4:]}, inplace = True) if col[:2] == '03': df.rename(columns = {col:'Bronze'+col[4:]}, inplace = True) if col[:2] == '№': df.rename(columns = {col:'#'+col[4:]}, inplace = True) df.head()
import numpy as np import pandas as pd 1. determining the m, n from a linear combination of a set of basis vectors. lincom = np.array([19,29,54]) set_of_vectors = np.array([[1,2,3], [4,5,6], [1,2,6]]) np.linalg.solve(set_of_vectors, lincom) 2. Doing a Linear Transformation of a matrix of 6 vectors. Just multiply the vectors with the transoforming vector! - ELONGATION METHOD 1 #Let's create a dataframe matrix here to understand the effect. a = [[1,2],[-2,3],[-2,1],[3,7],[4,5],[6,4]] b = ['X','Y'] c = pd.DataFrame(a,columns = b) c ## Now let's denote the linear transformation matrix. ## (2,0) and (0,1) are the vectors that would denote the columns of this matrix. ## Therefore (2,0) and (0,1) would be the rows L = np.array([[2,0],[0,1]]) L #Let's apply the transformation now. #Note that we have used c.values to convert that dataframe to a numpy array #And taken its transpose so that the transformation happens on each vector d = L @ (c.values).T #Now let's show the final changed matrix by findings the transpose again. d.T METHOD 2 a = [[1,2],[-2,3],[-2,1],[3,7],[4,5],[6,4]] b = ['X','Y'] c = pd.DataFrame(a,columns = b) c c.shape L = pd.DataFrame([[2,0],[0,1]]) L L.shape #see it gives an error, as the index names are different from the columns names of the two matrices d = c.dot(L) # to avoid changing the index and column names, it is better to use np.dot() method. It just takes the values of the matrices without worrying about the names of the index and columns. np.dot(c,L) # or your can use numpy @ or matmul function to do the matrix multiplication c.values @ L.values 3. TRANSFORMATION OF A VECTOR WITH ANOTHER MARTRIX a = np.array([2,3]) a b = np.array([[1,0],[0,1]]) b lintrans = a @ b lintrans 4. a = np.array([[1,4],[4,2]]) a b = np.array([[1,2],[3,4],[5,6],[7,8]]) b lintrans = b @ a lintrans 5. Find the eigen vector and matrix pairs A = np.array([[2,1],[1,2]]) v = np.array([1,-1]) Av = A @ v Av K = np.linalg.eig(A) K A = np.array([[2,2],[1,2]]) v = np.array ([1,-1]) Av = A @ v Av K = np.linalg.eig(A) K A = np.array([[1,2,3],[2,3,1],[3,1,2]]) K = np.linalg.eig(A) K a = np.array([1,2,3]) b = np.array([2,4,2]) a @ b np.dot(a,b)
import os path="/home/samrat/Documents/Git/PYTHON/APP-DATASC-PYTHON-COURSERA-SPEC/COURSE3-ML/WEEK2" os.chdir(path) import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier np.set_printoptions(precision=2) fruits = pd.read_table('fruit_data_with_colors.txt') fruits.head() type(fruits) feature_names_fruits = ['height', 'width', 'mass', 'color_score'] X_fruits = fruits[feature_names_fruits] y_fruits = fruits['fruit_label'] target_names_fruits = ['apple', 'mandarin', 'orange', 'lemon'] X_fruits_2d = fruits[['height', 'width']] y_fruits_2d = fruits['fruit_label'] X_fruits_2d.head() y_fruits_2d.head() X_train, X_test, y_train, y_test = train_test_split(X_fruits, y_fruits, random_state=0) from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() X_train_scaled = scaler.fit_transform(X_train) # we must apply the scaling to the test set that we computed for the training set X_test_scaled = scaler.transform(X_test) knn = KNeighborsClassifier(n_neighbors = 5) knn.fit(X_train_scaled, y_train) print('Accuracy of K-NN classifier on training set: {:.2f}' .format(knn.score(X_train_scaled, y_train))) print('Accuracy of K-NN classifier on test set: {:.2f}' .format(knn.score(X_test_scaled, y_test))) example_fruit = [[5.5, 2.2, 10, 0.70]] print('Predicted fruit type for ', example_fruit, ' is ', target_names_fruits[knn.predict(example_fruit)[0]-1])
''' 1. As Prof Raghavan said, each row of a data frame is an object of the same type. The type of each of the objects is determined by the type of the columns. The schema of the columns is determined by the constituent series'. 2. A DataFrame by definition is a collection of series. Each column is a series. So if you have a data frame with several columns, and one column is say 'Sales', to be able to access the first 100 rows of this data frame from this column you need to mention df['Sales'][:100]. Note that the first square bracket just picks the series, and then it is a one dimensional array that you are just slicing following the standard notation of a single dimensional list. ''' import pandas as pd purchase_1 = pd.Series({'Name': 'Chris', 'Item Purchased': 'Dog Food', 'Cost': 22.50}) purchase_2 = pd.Series({'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50}) purchase_3 = pd.Series({'Name': 'Vinod', 'Item Purchased': 'Bird Seed', 'Cost': 5.00}) df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=['Store 1', 'Store 2', 'Store 3']) #NOTE: ACCESSING USING THE ROW NAME GIVES YOU ALWAYS A DATA FRAME df.append ({'City': []) df['Store 1' : 'Store 3'] df['Store 1':] ss = df.loc['Store 1'] print (ss) #NOTE: data type is series. a table is not created as a data frame print (type(ss)) #NOTE : Now since a list of attributes are provided the data type of output is a dataframe df.loc[['Store 1', 'Store 2']] #NOTE : ss is a data frame now! ss = df.loc[['Store 1']] print (ss) print (type(ss)) ss1 = df['Name'] print (ss1) type(ss1) df.loc[:] df[:] df.iloc[0] df.loc['Store 1', 'Name'] df.loc['Store 1', 'Cost'] df.iloc[0,0] df.iloc[0,2] df1 = pd.DataFrame([purchase_1, purchase_2, purchase_3]) df1 df[::] #NOTE : Using iloc index the dataframe to print all the rows of the columns at index 3,4,5. #Hint: Use 3,4,5 not 2,3,4 import pandas as pd df = pd.read_csv('https://query.data.world/s/vBDCsoHCytUSLKkLvq851k2b8JOCkF') df_2 = df.iloc[:,3:6]#Type your code for indexing using iloc print(df_2.head(20)) ''' CONDITION BASED INDEXING ''' import pandas as pd df = pd.read_csv('https://query.data.world/s/vBDCsoHCytUSLKkLvq851k2b8JOCkF') df.head() #iloc is optional to just using the square braces. Since iloc access only row indices, this purges all the rows that finds a corresponding false. df[df['area'] > 0]
''' BOOLEAN MASK - AN ARRAY. Multiple conditions can be connected to give a complex query. ''' import os import pandas as pd os.chdir ("/home/samrat/Documents/Git/PYTHON/PANDAS") #Changing the index to column0 AND skipping the 1st row. df = pd.read_csv('DATA-FILES/olympics.csv', index_col=0, skiprows=1) #changing the names of the columns for col in df.columns: if col[:2] == '01': df.rename(columns = {col:'Gold'+col[4:]}, inplace = True) if col[:2] == '02': df.rename(columns = {col:'Silver'+col[4:]}, inplace = True) if col[:2] == '03': df.rename(columns = {col:'Bronze'+col[4:]}, inplace = True) if col[:2] == '№': df.rename(columns = {col:'#'+col[4:]}, inplace = True) df.head() df['Gold'] > 0 only_gold = df.where(df['Gold']>0) only_gold = df[df['Gold'] > 0] only_gold.head() only_gold = only_gold.dropna() only_gold.head() df[(df['Gold.1']>0) & (df['Gold'] == 0)]
''' NOTE 1 - DIFFERNCE BETWEEN LISTS AND ARRAY - 1. ARRAY IS HOMGENEOUS 2. ARRAY IS MULTI DIMENSIONAL BY DEFAULT. 3. LISTS SHOW UP AS COMMA SEPARATED ITEMS. ARRAYS ARE NOT SEPERATED BY COMMAS 4. VECTORIZED CODE CAN BE WRITTEN ONLY WITH NUMPY AND NOT WITH LIST 5. COMPUTATIONS ARE FASTER IN NUMPY 6. EVERY ARITHMETIC OPERATOR DOES AN ELEMENT WISE OPERATION ON THE ARRAYS. IN LIST WE NEED TO CREATE A MAP AND LAMBDA COMBINATION TO ACHIEVE THE SAME THING. 7. The following ways are commonly used: np.ones(): Create an array of 1s np.zeros(): Create an array of 0s np.random.random(): Create an array of random numbers between 0 and 1 np.arange(): Create an array with increments of a fixed step size np.linspace(): Create an array of fixed length ''' #NOTE : 1. ARRAY CREATION import numpy as np mylist=[1,2,3,4] print (mylist) x = np.array(mylist) print (x) y = np.array([[4,5,6], [7,8,9], [10,11,12]]) print (y) # just size - two dimensional array. np.ones([3,13]) # 4 dimensional array. np.ones((3,3,3,4), dtype = np.int) #random number between 0 to 1. Is useful for probabilities. np.random.random((4,5)) #gives one dimensional array only. np.arange(2,10,2) np.linspace(4,40,100) #any size np.full((3,4),5) np.eye(5,4, dtype = np.int) #second parameter is the number of repitition in row and column. if one number it will repeat only in the row. np.tile (mylist,10) ''' checkered tiled matrix based on the entries ''' # Read the variable from STDIN import numpy as np n = int(input()) checker_unit = np.array([[0,1],[1,0]]) #tile first arranges the array as per the size given, and then it repeats it. print(np.tile(checker_unit, (int(n/2),int(n/2)))) #lowest number, highest number, size np.random.randint(2,20,(3,4)) #2 dimensional matrix in numpy z = np.array([[7,8,9],[10,11,12]]) print(z) #2 dimensional matrix in normal list mylist2 = [[1,2], [4,5], [7,8]] print (mylist2) m = np.array(mylist2) print(m) #2. SHAPE AND SIZING print(m.shape) #printing a series - airthmetic progress #The out put of range and arange are same. Only that arange returns a numpy array. Here i dont know number of elements. #in arange i know the interval. inlinspace, i dont know the interval. I just mention how many elements i need between two limits. import numpy as np a = np.arange(0,30,2) a1 = list(range(0,30,2)) print (a) print (a1) b = np.linspace (0,4,20) print (b) c = a.reshape(3,5) print (c) print (a) #resize returns none and changes the shape of the original matrix. d = a.resize(3,5) print ("d=", d) print (a) #3. STANDARD MATRICES import numpy as np print (np.ones((5,6))) print (np.zeros((5,6))) print (np.eye(5)) #print (np.diag()) #4. repeatst6g import numpy as np print (np.repeat([1,2,3],3)) print(np.array([1,2,3]*3)) #matrix arithmetic import numpy as np x = np.array([[7,8,9],[10,11,12]]) y = np.array([[5,6,7],[8,9,10]]) print(x.sum()) print(x.max()) print(x.min()) print(x.mean()) print(x.std()) print(x.argmax()) print(x.argmin()) #SLICING AND INDEXING import numpy as np a = np.arange(30) print (a[5:]) print (a[-5:]) print (a[5:29]) print (a[5::2]) print (a[-5::-2]) print (a[-5::2]) import numpy as np b = np.arange(30) b.resize(6,6) print (b) print (b[2:3]) print (b[2:4]) print (b[2:6]) print (b[1::3]) print (b[2,2:]) print (b[0::2, 0::2]) print (b[b>15]) b[b>15]= 99 print (b) #numpy array does not create a copy unless .copy() method is called. even if you assign the value to a new variable, the previous matrix gets changed. #CREATING A RANDOM MATRIX - import numpy as np test = np.random.randint(0,4,(4,3)) print(test) #ENUMERATION for row_num, row_val in enumerate (test): print ( 'row:', row_num, 'is', row_val)
#Unlike C, python does not convert automatically the character to ascii number. import numpy as np try: data = input ("Enter name") numeric_data = int(data) except: numeric_data = -1 print (numeric_data) np.arange(5)
import sqlite3, sys class Phonebook(object): def __init__(self): try: c.execute('CREATE TABLE entries(id INTEGER PRIMARY KEY, name TEXT, phone TEXT unique)') except: pass print('Welcome to the Phonebook') def addEntry(): name = input('Введите имя: ') number = input('Введите номер телефона: ') c.execute('INSERT INTO entries(name, phone) VALUES(?,?)', (name, number)) def delEntry(): name = input('Please, enter a name to delete: ') c.execute('DELETE FROM entries WHERE name=?', [name]) def rollback(): db.rollback() def save(): db.commit() def query(): c.execute('SELECT name, phone FROM entries') for items in c: print(items) class MainMenu(Phonebook): def __init__(self): print(''' Меню Выберите действие: 1. "добавить" - добавить контакт. 2. "удалить" - удалить контакт. 3. "отменить" - отменить последнее действиеe. 4. "сохранить" - сохранить изменения. 5. "список" - посмотреть список. ''') selection = input() if selection == 'добавить': try: Phonebook.addEntry() except IntegrityError: print('Телефонный номер добавлен.') if selection == 'удалить': Phonebook.delEntry() if selection == 'отменить': Phonebook.rollback() if selection == 'сохранить': Phonebook.save() if selection == 'список': Phonebook.query() db = sqlite3.connect('phonebookDB.sqlite') c = db.cursor() Phonebook() while True: MainMenu() db.close()
# -*- coding: utf-8 -*- """ Created on Tue Nov 27 12:34:02 2018 @author: datacore """ # plot feature importance manually from numpy import loadtxt from xgboost import XGBClassifier from matplotlib import pyplot # load data dataset = loadtxt('stockdata.csv', delimiter=",") print(dataset) # split data into X and y X = dataset[:,0:89] y = dataset[:,90] # fit model no training data model = XGBClassifier() model.fit(X, y) # feature importance print(model.feature_importances_) # plot pyplot.bar(range(len(model.feature_importances_)), model.feature_importances_) pyplot.show()
__author__ = 'mohammadsafwat' def binarySearchRecursive(alist, item): if len(alist) == 0: return False else: midpoint = len(alist) // 2 if alist[midpoint] == item: return True else: if item < alist[midpoint]: return binarySearchRecursive(alist[:midpoint], item) else: return binarySearchRecursive(alist[midpoint+1:], item) testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42] print(binarySearchRecursive(testlist, 3)) print(binarySearchRecursive(testlist, 32))
# -*- coding: utf-8 -*- # !/usr/bin/env python3 """This defines the structure of a UCT""" import copy import random class UCT(object): """Tree definition but not including expand, select, simulate and backup""" def __init__(self): # common tree structure self.state = None # Board information from game.board, including black and white pieces and the whole board info, used to identity a node self.parent = None # the parent of the node self.children = [] # the children of the node self.parent_action = None # parent's action to reach this state, used to make decisions, a binary tuple # self.weight = float('inf') # initialize the max fla # UCT characters self.visit_time = 0 # the times a node is visited throughout the whole process self.total_reward = 0 # how many times winning throughout whole process self.psa = 0 # prior experience # common operations of tree def initialize_state(self, state): self.state = copy.deepcopy(state) def set_parent(self, uct_node): self.parent = uct_node def add_child(self, uct_node): self.children.append(uct_node) def rand_choose_child(self): return random.choice(self.children) @property def mean_reward(self): if self.visit_time == 0: return 0 else: return self.total_reward/self.visit_time @property def my_parent(self): return self.parent @property def my_board(self): return self.state @property def my_children(self): return self.children
import sys,pygame #Importar para la creacion de la vetana import Image #Importar para trabajar con imagene (PIL) from sys import argv #Importar para trabajar con argumentos de terminal #def main: se crea la ventana y se carga la imagen ya en escala de grises def main(image): ancho,altura,new_image=escala_grises(image) #Llama a funcion escala de grises ventana = pygame.display.set_mode((ancho,altura)) #Crea una ventana cn las dimensiones de la imagen pygame.display.set_caption('Imagen') #Definimos el nombre d ela ventana imagen = pygame.image.load(new_image) #Carga nuestra imagen while True: #Para que la ventana no se cierre #Para poder cerrar la ventana for eventos in pygame.event.get(): if eventos.type == pygame.QUIT: sys.exit(0) ventana.blit(imagen,(0,0))#Mostrar la imagen posicion x=0, y=0 pygame.display.update() return 0 #Convierte la imagen a escalade grises def escala_grises(image): image = Image.open(image) new_image = 'escala_grises.png' pixeles = image.load() ancho, altura =image.size for i in range(ancho): for j in range(altura): (r,g,b) = image.getpixel((i,j)) escala = (r+g+b)/3 pixeles[i,j]=(escala,escala,escala) image=image.save(new_image) return ancho,altura,new_image pygame.init() #Inicializa pygame main(argv[1])
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.sum = 0 def getSum(self, root: TreeNode, current: int): if root.left is None and root.right is None: self.sum += current + root.val if root.left is not None: self.getSum(root.left, (current + root.val) * 10) if root.right is not None: self.getSum(root.right, (current + root.val) * 10) def sumNumbers(self, root: TreeNode) -> int: if root is None: return 0 self.getSum(root, 0) return self.sum def main(): s = Solution() tree_list = [TreeNode(i) for i in [1, 2, 3]] tree_list[0].left = tree_list[1] tree_list[0].right = tree_list[2] ans = s.sumNumbers(tree_list[0]) print(ans) return if __name__ == "__main__": main()
#!/usr/bin/python3 # -*- coding: UTF-8 -*- from typing import List class Solution: def longestConsecutive(self, num: List[int]) -> int: if not num: return 0 num_first = {} for n in num: if n + 1 in num_first: num_first[n + 1] = False if n - 1 in num_first: num_first[n] = False else: num_first[n] = True max_cnt = 1 for n, is_first in num_first.items(): if is_first: current_num = n + 1 while current_num in num_first: current_num += 1 if current_num - n > max_cnt: max_cnt = current_num - n return max_cnt def main(): s = Solution() ans = s.longestConsecutive([100, 4, 200, 1, 3, 2]) print(ans) return if __name__ == "__main__": main()
''' Algorithm to discover if a string is a palyndrome or not ''' class Palyndromes(object): @staticmethod def is_palyndrome(s): r = s[::-1] return s == r def is_palyndrome(a_string): if len(a_string) > 0: return False else: reversed = a_string[::-1] if reversed == a_string: return True else: return False if __name__ == "__main__": print(is_palyndrome("aba")) print(is_palyndrome("hello")) print(Palindromes.is_palindrome("ooo")) print(Palindromes.is_palindrome("foo"))
#!/usr/bin/python # -*- coding: ascii -*- ''' AVL (Adelson-Velsky and Landis) Tree: A balanced binary search tree where the height of the two subtrees (children) of a node differs by at most one. Look-up, insertion, and deletion are O(log n), where n is the number of nodes in the tree. (Definition from http://xlinux.nist.gov/dads//HTML/avltree.html) In big O notation terms: (http://en.wikipedia.org/wiki/AVL_tree) Algorithm Average Worst Case Space O(n) O(n) Search O(log n) O(log n) Insert O(log n) O(log n) Delete O(log n) O(log n) ''' import sys # https://docs.python.org/2/library/sys.html sys.setrecursionlimit(4000) # Just a way to implement an enumeration def enum(**enums): return type('Enum', (), enums) Balances = enum(left_heavy=0, balanced=1, right_heavy=2) log = False debug = True class Rebalancing: __status = None def __init__(self, status): self.__status = status def setStatus(self, status): self.__status = status def getStatus(self): return self.__status class AVLNode: """Class to represent a AVL tree node""" key = "" value = "" left = None right = None balance = Balances.balanced def __init__(self): if log: print "AVLNode::__init__(self) ini" self.key = "" self.value = "" self.left = None self.right = None self.balance = Balances.balanced '''def __init__(self, key, value, letf, right, balance): print "AVLNode::__init__(self, key, value, letf, right, balance) ini" self.key = key self.value = value self.left = left self.right = right self.balance = balance''' '''Method to know if a node is empty''' def is_empty(self): if log: print "AVLNode::is_empty(self) ini" return self == None or self.key == None or self.key == "" '''Draw AVLNode fields''' def draw(self, margin): if log: print "AVLNode::draw(self, margin) ini" if self != None: print margin + "k: ", self.key print margin + "v: ", self.value if self.balance == Balances.right_heavy: print margin + "Right Balanced" elif self.balance == Balances.left_heavy: print margin + "Left Balanced" else: print margin + "Balanced" if self.left != None: margin = "\t" + margin if '(R)' in margin: margin = margin.replace("(R)","(L)") if '(L)' not in margin: margin = margin + "(L)" # self.left.draw("\t" + margin + "--(L) ") #else: # self.left.draw("\t" + margin) self.left.draw(margin) if self.right != None: margin = "\t" + margin if '(L)' in margin: margin = margin.replace("(L)", "(R)") if '(R)' not in margin: margin = margin + "(R)" #self.right.draw("\t" + margin + "--(R) ") #else: # self.right.draw("\t" + margin) self.right.draw(margin) '''Remove a node from a tree''' def remove(self, key, rebalance): if log: print "AVLNode::remove(self, key, rebalance) ini" if self != None: if debug: print 'self != None' if key < self.key: if debug: print 'key ' + key + '< self.key ' + self.key self.left.remove(key, rebalance) if rebalance: if debug: print 'left rebalance' self.left_balance(rebalance) elif key > self.key: if debug: print 'key ' + key + ' > self.key ' + self.key self.right.remove(key, rebalance) else: if self.left == None: if debug: print 'self.left == None' aux = self self = self.right aux = None rebalance = True elif self.right == None: if debug: print 'self.right == None' aux = self self = self.left aux = None rebalance = True else: if debug: print 'invoking delete_maximum_key' self.left.delete_maximum_key(self.key, self.value, rebalance) if rebalance: self.left_balance(rebalance) def delete_maximum_key(self, key, value, rebalance): if log: print "AVLNode::delete_maximum_key(self, key, value, rebalance) ini" """ It has been implemented dispose method : obj = None """ if self.right == None: key = self.key value = self.value aux = self self = self.left aux = None rebalance = True else: self.right.delete_maximum_key(key, value, rebalance) if rebalance: self.right_balance(rebalance) def search(self, key): if log: print "AVLNode::search(self, key) ini" success = False if self == None: return False else: if self.key == key: success = True elif key < self.key: self.left.search(key, success, value) else: self.right.search(key, success, value) return success def test_balancing_factors(self): if log: print "AVLNode::test_balancing_factors(self) ini" if self == None: return True elif self.left == None and self.right == None: return self.balance == Balances.balanced elif self.left == None and self.right != None: return self.balance == (Balances.right_heavy and self.right.test_balancing_factors()) else: hi = self.left.height() hr = self.right.height() if hi == hr: ok = self.balance == Balances.balanced elif hi > hr: ok = self.balance == Balances.left_heavy else: ok = self.balance == Balances.right_heavy def balancing(self): if log: print "AVLNode::balancing(self) ini" if self == None: return True elif self.left == None and self.right == None: return true elif self.left == None and self.right != None: return self.right.height() == 0 elif self.left != None and self.right == None: return self.left.height() == 0 else: hi = self.left.height() hr = self.right.height() return abs(hi - hr) <= 1 and self.left.balancing() and self.right.balancing() def height(self): if log: print "AVLNode::height(self) ini" def max(left, right): if left >= right: return left else: return right if self.left == None and self.right != None: return 1 + self.right.height() elif self.left != None and self.right == None: return 1 + self.left.height() elif self.left != None and self.right != None: return 1 + max(self.left.height(), self.right.height()) else: return 1 '''Method to balance a letf balanced tree''' def left_balance(self, rebalance): if log: print "AVLNode::left_balance(self, rebalance) ini" if self.balance == Balances.left_heavy: if debug: print 'self.balance ', self.balance, ' == Balances.left_heavy ', Balances.left_heavy self.balance = Balances.balanced elif self.balance == Balances.balanced: if debug: print 'self.balance ', self.balance, ' == Balances.balanced ', Balances.balanced self.balance = Balances.right_heavy rebalance = False elif self.balance == Balances.right_heavy: if debug: print 'self.balance ', self.balance, ' == Balances.right_heavy ', Balances.right_heavy right_subtree = self.right balance_subtree = right_subtree.balance if balance_subtree != left_heavy: if debug: print 'balance_subtree != left_heavy' self.right = right_subtree.left right_subtree.left = self if right_subtree == Balances.balanced: if debug: print 'right_subtree == Balances.balanced' self.balance = Balances.right_heavy right_subtree.balance = Balances.left_heavy rebalance = False else: self.balance = balanced right_subtree.balance = Balances.balanced self = right_subtree else: left_subtree = right_subtree.left balance_subtree = left_subtree.balance right_subtree.left = left_subtree.right left_subtree.right = right_subtree self.right = left_subtree.left left_subtree.left = self if balance_subtree == right_heavy: self.balance = left_heavy right_subtree.balance = Balances.balanced elif balance_subtree == Balances.balanced: self.balance = Balances.balanced right_subtree.balance = Balances.balanced else: self.balance = Balances.balanced right_subtree.balance = Balances.right_heavy self = self.left left_subtree.balance = Balances.balanced '''Method to balance a right balanced tree''' def right_balance(self, rebalance): if log: print "AVLNode::right_balance(self, rebalance) ini" if self.balance == Balances.right_heavy: self.balance = Balances.balanced elif self.balance == Balances.balanced: self.balance = Balances.left_heavy rebalance = False elif self.balance == Balances.left_heavy: left_subtree = self.left balance_subtree = left_subtree.balance if balance_subtree != Balances.right_heavy: self.left = left_subtree.right left_subtree.right = self if balance_subtree == Balances.balanced: self.balance = Balances.right_heavy left_subtree.balance = Balances.right_heavy rebalance = False else: self.balance = Balances.balanced left_subtree.balance = Balances.balanced self = left_subtree else: right_subtree = left_subtree.right balance_subtree = right_subtree.balance left_subtree.right = right_subtree.left right_subtree.left = left_subtree self.left = right_subtree.right right_subtree.right = self if balance_subtree == left_heavy: self.balance = Balances.right_heavy left_subtree.balance = Balances.balanced elif balance_subtree == Balances.balanced: self.balance = Balances.balanced left_subtree.balance = Balances.balanced else: self.balance = Balances.balanced left_subtree.balance = Balances.left_heavy self = right_subtree right_subtree.balance = Balances.balanced class AVLTree: """ AVL Tree class This Dictorionary ADT implementation is based on Javier Campos's Ada95 AVL implementation (@javifields): http://webdiis.unizar.es/asignaturas/EDA/gnat/ejemplos_TADs/arboles_AVL/campos/ There are many examples of a Python AVL tree implementation out there using Object Oriented Programming techniques, for instance: http://www.brpreiss.com/books/opus7/ And in other programming language: (C++) http://cis.stvincent.edu/html/tutorials/swd/avltrees/avltrees.html https://www.auto.tuwien.ac.at/~blieb/woop/avl.html """ __root = None def __init__(self, **dargs): #Order to option parameters: node, key, value if log: print "AVLTree::__init__(self, **dargs)" #dargs -- dictionary of named arguments self.__root = AVLNode() for key in dargs: if key == "node": self.__root = dargs['node'] elif key == "key": if self.__root is None: self.__root = AVLNode() self.__root.key = dargs[key] elif key == "value": if self.__root is None: self.__root = AVLNode() self.__root.value = dargs[value] def empty(self): if log: print "AVLTree::empty() ini" self.__root = None self = None def get_root(self): if log: print "AVLTree::get_root() ini" return self.__root ''' Internal method to add a node in AVL tree ''' def __modify(self, key, value, rebalance): if log: print "AVLTree::__modify(key, value, rebalance) ini" if self.is_empty(): if debug: print "Insert node in tree and rebalance = True" self.__root = AVLNode() self.__root.key = key self.__root.value = value # Rebalance marked as true to the next?? rebalance.setStatus(True) elif key < self.__root.key: if debug: print "key " + key + "< self.__root.key " + self.__root.key if self.__root.left == None: self.__root.left = AVLNode() self.__root.left.key = key self.__root.left.value = value rebalance.setStatus(True) left_subtree = AVLTree(node = self.__root.left) left_subtree.__modify(key, value, rebalance) if rebalance.getStatus(): print "key < self.__root.key -> rebalance" if self.__root.balance == Balances.left_heavy: print "key < self.__root.key -> Balances.left_heavy" if self.__root.left.balance == Balances.left_heavy: print "left_rotation()" self.left_rotation() else: print "left_right_rotation()" self.left_right_rotation() rebalance.setStatus(False) #rebalance.__status = False elif self.__root.balance == Balances.balanced: print "key < self.__root.key -> Balances.balanced" self.__root.balance = Balances.right_heavy elif self.__root.balance == Balances.right_heavy: print "key < self.__root.key -> Balances.right_heavy" self.__root.balance = Balances.balanced rebalance.setStatus(False) #rebalance.__status = False elif key > self.__root.key: if debug: print "key ", key, " > self.__root.key ", self.__root.key if self.__root.right == None: self.__root.right = AVLNode() self.__root.right.key = key self.__root.right.value = value rebalance.setStatus(True) right_subtree = AVLTree(node = self.__root.right) right_subtree.__modify(key, value, rebalance) if debug: print "-------------paiting Root right subtree" right_subtree.draw_tree() print "-------------end Root right subtree" if rebalance.getStatus(): if debug: print "Rebalance status: ", rebalance.getStatus() print "key > self.__root.key => rebalance" if self.__root.balance == Balances.left_heavy: if debug: print "key > self.__root.key => Balances.left_heavy" self.__root.balance = Balances.balanced rebalance.setStatus(False) elif self.__root.balance == Balances.balanced: if debug: print "key > self.__root.key => Balances.balanced" self.__root.balance = Balances.right_heavy elif self.__root.balance == Balances.right_heavy: if debug: print "key > self.__root.key => Balances.right_heavy" if self.__root.right.balance == Balances.right_heavy: if debug: print "Invoking right_rotation()" self.right_rotation() else: if debug: print "right_left_rotation()" self.right_left_rotation() rebalance.setStatus(False) else: # Unchanged balance self.__root.value = value def modify(self, key, value): if log: print "AVLTree::modify(self, key, value) ini" rebalance = Rebalancing(False) self.__modify(key, value, rebalance) def is_empty(self): if log: print "AVLTree::is_empty(self) ini" return self is None and self._root is None and self._root.key == "" and self._root.value == "" def left_rotation(self): if log: print "AVLTree::left_rotation(self) ini" aux = self.__root.left self.__root.right = aux.left self.__root.balance = Balances.balanced self.__root = aux self.__root.balance = Balances.balanced self.__root.left, self.__root.right = self.__root.right, self.__root.left def right_rotation(self): if log: print "AVLTree::right_rotation(self) ini" aux = self.__root.right self.__root.right = aux.left self.__root.balance = Balances.balanced aux.left = self.__root self.__root = aux self.__root.balance = Balances.balanced def left_right_rotation(self): if log: print "AVLTree::left_right_rotation(self) ini" aux1 = self.__root.left aux2 = self.__root.left.right aux1.right = aux2.left aux2.left = aux1 if aux2.balance == Balances.left_heavy: aux1.balance = Balances.balanced elif aux2.balance == Balances.balanced: aux1.balance = Balances.balanced self.__root.balance = Balances.balanced else: aux1.balance = Balances.left_heavy self.__root.balance = Balances.balanced self.__root.left = aux2.right aux2.right = self.__root aux2.balance = Balances.balanced self.__root = aux2 def right_left_rotation(self): if log: print "AVLTree::right_left_rotation(self) ini" root = self.__root aux1 = self.__root.right aux2 = aux1.left if aux2 != None: aux1.left = aux2.right else: aux1.left = None self.__root.right = aux2 if aux2.balance == Balances.right_heavy: aux1.balance = Balances.balanced elif aux2.balance == Balances.balanced: aux1.balance = Balances.balanced self.__root.balance = Balances.balanced else: aux1.balance = Balances.left_heavy self.__root.balance = Balances.balanced self.__root.right = aux2.left aux2.left = self.__root aux2.balance = Balances.balanced self.__root = aux2 def delete(self, key): if log: print "AVLTree::delete(self, key) ini" rebalance = False self.__root.remove(key, rebalance) '''Method to search a key in tree''' def search(self, key): if log: print "AVLTree::delete(self, key) ini" if self == None: return False else: return self.__root.search(key) def is_empty(self): if log: print "AVLTree::is_empty(self) ini" return self == None or self.__root == None or self.__root.key == "" def dump_in_order(self): if log: print "AVLTree::dump_in_order(self) ini" if self != None and self.__root != None: self.__root.left.dump_in_order() print self.__root.key, ":", self.__root.value print "\n" self._root.right.dump_in_order() def height(self): if log: print "AVLTree::height(self) ini" if self.is_empty: return 0 return self.__root.height() ''' Method to draw a tree ''' def draw_tree(self, margin=''): if log: print "AVLTree::draw_tree(self) ini" if self.is_empty(): print '----EMPTY----' else: print margin + '----' self.__root.draw(margin) def balancing(self): if log: print "AVLTree::balancing(self) ini" if self != None and self.__root != None: self.__root.balancing() def test_balancing_factors(self): if log: print "AVLTree::test_balancing_factors(self) ini" if self == None: return True else: return self.__root.test_balancing_factors()
# -*- coding: utf-8 -*- from date import TOTAL_NUMS from query import QUERY total_num = 0 for k, v in(TOTAL_NUMS.items()): total_num = total_num + v total_num2 = 0 for k, v in(QUERY.items()): total_num2 = total_num2 + 1 if total_num == total_num2: print("match: ", total_num) else: print("not match: ", total_num, total_num2)
# Name: Kevin Nakashima # Class: CPSC 223P # Date: 02/07/2017 # File: Binary2Text.py # converts a binary set to a string #Imports======================================================================= #T2B=========================================================================== def Bin2Text(binary): text = [] for set in binary: text.append(chr(int(set, 2))) print(*text, sep = '') #MAIN========================================================================== def main(): binary = input("Please enter binary: ") binaryList = binary.split(' ') Bin2Text(binaryList) main() #==============================================================================
#!/usr/bin/env python3 """ This is a quick function that can work out the distance between two GPS coordinates. """ import sys from math import asin, cos, radians, sin, sqrt if len(sys.argv) != 5: print("Usage: distance lat1 lon1 lat2 lon2") sys.exit(1) lat1 = float(sys.argv[1].strip().strip(",")) lon1 = float(sys.argv[2].strip().strip(",")) lat2 = float(sys.argv[3].strip().strip(",")) lon2 = float(sys.argv[4].strip().strip(",")) print( 6372.8 * 2 * asin( sqrt( sin(radians(lat2 - lat1) / 2) ** 2 + sin(radians(lon2 - lon1) / 2) ** 2 * cos(radians(lat1)) * cos(radians(lat2)) ) ) )
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 25 23:54:49 2018 @author: apple """ week = [30,39,34,35,37,30,40] for i in range(0,6): if i == 2: print('周三:',end='') print(week[i])
import smtplib from email.message import EmailMessage from getpass import getpass from collections import defaultdict if __name__ == "__main__": name = input("Name: ") n = get_user_input(f"Hi, {name}!\nHow many products do you want to add to the shopping list? ", int) shopping_list = defaultdict(int) for _ in range(n): add_item(shopping_list) print_list(shopping_list) email = input("Email: ") password = getpass("Password: ") recipient = input("Recipient's email: ") email_to(shopping_list, email, password, recipient) class ShoppingList: def __init__(self): self.items = defaultdict(int) def __str__(self): return "\n".join(f"{name} x {quantity}" for name, quantity in self.items.items()) def add_item(self, name, quantity): self.items[name] += quantity def email_to(self, from_email, password, *recipients): ... if __name__ == "__main__": name = input("Name: ") n = get_user_input(f"Hi, {name}!\nHow many products do you want to add to the shopping list? ", int) shopping_list = ShoppingList() for _ in range(n): name = get_user_input("Input the product name: ") quantity = get_user_input("Input the product quantity: ", int) shopping_list.add_item(name, quantity) print(shopping_list) email = input("Email: ") password = getpass("Password: ") recipient = input("Recipient's email: ") shopping_list.email_to(email, password, recipient)
import random import string # Satunnaisuus print(random.randint(1, 10)) # Nopan heittäminen print("Silmäluku: ", random.randint(1,6)) # Toinen vaihtoehto, kuten edellinen print("Silmäluku: " + str(random.randint(1,6))) # Kolikon heittäminen a = ["kruuna", "klaava"] print("Tulos: " + random.choice(a)) # Salasanan arpoja merkkienmaara = 0 salasana = "" while(merkkienmaara < 8): salasana += random.choice(string.ascii_lowercase) merkkienmaara += 1 print(salasana) # Toinene esimerkki salasana = "" for x in range(8): salasana += random.choice(string.ascii_lowercase) print(salasana) # Sekoittaja def sekoitaLista(luvut): random.shuffle(luvut) def tulostaLista(luvut): print(luvut) luvut = [1, 2, 3, 4, 5, 6, 7, 8] sekoitaLista(luvut) tulostaLista(luvut) # Vihollisen sijainnit sijaintilista=[] for i in range(0,200): n = str(random.randint(0,100)) + "," + str(random.randint(0,100)) sijaintilista.append(n) print(sijaintilista) # Listan järjestäminen lista = [1, 3, 5, 4] lista.sort() print(lista) # Pistelista Kierrokset = True x = [] y = [] lisaaInput = "" while Kierrokset: lisaaInput = input("Anna pelaaja: ") if lisaaInput == "lopeta": Kierrokset = False else: x.append(lisaaInput) test = int(input("Anna pisteet: ")) y.append(test) esiintymat = [i for i, z in enumerate(y) if z == max(y)] pituusEsiintymat = len(esiintymat) Kierrokset = 0 while(Kierrokset < pituusEsiintymat): print(x[esiintymat[Kierrokset]] + ", " + str(y[esiintymat[Kierrokset]])) Kierrokset += 1
from collections import Counter import csv import matplotlib.pyplot as plt import numpy.numarray as na import parse MY_FILE = "../data/sample_sfpd_incident_all.csv" def visualize_days(): """Visualize data by day of week""" # grab our parsed data that we parsed earlier data_file = parse.parse(MY_FILE, ",") # make a new variable, 'counter', from iterating through each # line of data in the parsed data, and count how many incidents # happen on each day of the week counter = Counter(item["DayOfWeek"] for item in data_file) # separate the x-axis data (the days of the week) from the # 'counter' variable from the y-axis data (the number of # incidents for each day) data_list = [ counter["Monday"], counter["Tuesday"], counter["Wednesday"], counter["Thursday"], counter["Friday"], counter["Saturday"], counter["Sunday"] ] day_tuple = tuple(["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]) # with that y-axis data, assign it to a matplotlib plot instance plt.plot(data_list) # create the amount of ticks needed for our x-axis, and assign # the labels plt.xticks(range(len(day_tuple)), day_tuple) # save the plot! plt.savefig("Days.png") # close plot file plt.clf() def main(): visualize_days() if __name__ == "__main__": main()
''' At the start of the game the user selects class, based on that selection the users hero will be assigned attributes correlating to the type of hero. Attributes determine the hero's ability to use certain spell and weapons and also determine the amount of health that the character has at the start of the game. ''' base = 10 class Attributes: # Constitution will determine starting hit points def constitution(self, heroclass): self.heroclass = heroclass conmodifier = 0 if heroclass is 'Wizard': print('---------------------------------\n' 'Wizard' '\n---------------------------------') conmodifier = 5 elif heroclass is 'Warrior': print('---------------------------------\n' 'Warrior' '\n---------------------------------') conmodifier = 15 elif heroclass is 'Archer': print('---------------------------------\n' 'Archer' '\n---------------------------------') conmodifier = 10 life = base + conmodifier return life # Strength Attribute will determine melee damage def strength(self, heroclass): self.heroclass = heroclass strmodifier = 0 if heroclass is 'Wizard': strmodifier = 0 elif heroclass is 'Warrior': strmodifier = 10 elif heroclass is 'Archer': strmodifier = 2 base_melee_damage = base + strmodifier return base_melee_damage # Intelligence will determine spell damage def intelligence(self, heroclass): self.heroclass = heroclass intmodifier = 0 if heroclass is 'Wizard': intmodifier = 10 elif heroclass is 'Warrior': intmodifier = 0 elif heroclass is 'Archer': intmodifier = 0 base_spell_damage = base + intmodifier return base_spell_damage # Dexterity will determine ranged damage and dodge percentage def dexterity(self, heroclass): self.heroclass = heroclass dexmodifier = 0 if heroclass is 'Wizard': dexmodifier = 2 elif heroclass is 'Warrior': dexmodifier = 4 elif heroclass is 'Archer': dexmodifier = 10 base_ranged_damage = base + dexmodifier return base_ranged_damage
import pymongo ''' The ArmorDB class directly queries the MongoDB database for all the Armor specifications. We import the pymongo plugin to incorporate MongoDB with python. We initially setup a client to run mongoDB, then we specify which Database we will be accessing via (db = client.armory). Where client.armory specifies the armory database, thus, armory must exist in the MongoDB database. Next we access the armory Collections by using db.armor.find() where armor is the Collection that we are browsing. Additionally this script could be used to insert and delete database entries, However currently I am using the Mongo Explorer Tool in Pycharm to access the databases rather than writing them in code here. ''' class ArmorQuery: def armor_query_name(self, armor_name): self.armor_name = armor_name client = pymongo.MongoClient() db = client.armory armory = db.armor.find() for a in armory: if a['Armor Name'] == armor_name: armor_name = a['Armor Name'] return armor_name def armor_query_type(self, armor_name): self.armor_name = armor_name client = pymongo.MongoClient() db = client.armory armory = db.armor.find() for a in armory: if a['Armor Name'] == armor_name: armor_type = a['Armor Type'] return armor_type def armor_query_slot(self, armor_name): self.armor_name = armor_name client = pymongo.MongoClient() db = client.armory armory = db.armor.find() for a in armory: if a['Armor Name'] == armor_name: armor_slot = a['Armor Slot'] return armor_slot def armor_query_weight(self, armor_name): self.armor_name = armor_name client = pymongo.MongoClient() db = client.armory armory = db.armor.find() for a in armory: if a['Armor Name'] == armor_name: weight = a['Weight'] return weight def armor_query_defense(self, armor_name): self.armor_name = armor_name client = pymongo.MongoClient() db = client.armory armory = db.armor.find() for a in armory: if a['Armor Name'] == armor_name: armor_defense = a['Armor Defense'] return armor_defense #a = ArmorQuery() #print(a.armor_query_name('Skyguard'))
ch=0 stack=[] while ch!=4: print "Stack Operation" print "1. PUSH" print "2. POP" print "3. DISPLAY" print "4. QUITE" ch=int(raw_input('Enter your choice : ')) if ch==1: n=int(raw_input('Enter number to PUSH : ')) stack.append(n) elif ch==2: if len(stack)>0: stack.pop() else: print "Stack is Underflow" elif ch==3: print stack else: print "quite program"
# -*- coding: utf-8 -*- # Создайте списки: # моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что) from typing import List, Tuple, Union my_family = ['father', 'mother', 'son'] # список списков приблизителного роста членов вашей семьи my_family_height = ['father', 183], ['mother', 165], ['son', 95] # Выведите на консоль рост отца в формате # Рост отца - ХХ см print('rost ' + my_family[0] + ' ', my_family_height[0][1], 'cm') # Выведите на консоль общий рост вашей семьи как сумму ростов всех членов # Общий рост моей семьи - ХХ см sum_height = 0 sum_height += my_family_height[0][1] sum_height += my_family_height[1][1] sum_height += my_family_height[2][1] print(sum_height)
# This program import the insect_class_polymorphism module here # The isinstance() function is incorporated here import insect_class_polymorphism as ic def find_member(member): if isinstance(member, ic.Insect): # isinstance method print(member) else: print(member,' isn\'t an instance of Insect') def create_instance(): wasp = ic.Insect('Yellow Jacket') find_member(wasp) mosquito = ic.Mosquito('Aedes') find_member(mosquito) bug = ic.Bug('Laby-bug') find_member(bug) find_member('Long Horn') find_member('Hornet') create_instance()
# 1: Preprocessing transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]) # 2: Model class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(1, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(320, 50) self.fc2 = nn.Linear(50, 10) def forward(self, x): x = torch.sigmoid(F.max_pool2d(self.conv1(x), 2)) x = torch.sigmoid(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 320) x = F.sigmoid(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) x = F.softmax(x, dim=1) return x # 3: Postprocess prob, outputs = torch.max(outputs,1)#[1] maxi = torch.max(prob) mini = torch.min(prob) prob = torch.add(prob,mini*-1) prob = torch.div(prob,maxi-mini) y = torch.ones(prob.shape) z = torch.zeros(prob.shape) outputs = torch.where(prob <= .4, y, z) # 4: Written explanation We implemented a CNN with two convolutions and then trained it on the training data, wherein we used a sigmoid activation function. The softmax function was used to obtain classification probabilities. An L1 loss function was implemented following this, along with stochastic gradient descent. During the post process, we examined the outputs, which were tensors of probabilities. If any probability was under our proposed threshold (see above), it was likely representative of a novel piece of data.
""" py实现递归算法 function recursive(input): if input <= 0: return input else output = recursive(input - 1) return output """ def get_fib(position): if position == 0 or position == 1: return position return get_fib(position-1) + get_fib(position - 2) #Test cases print(get_fib(9)) print(get_fib(11)) print(get_fib(0))
#!/usr/bin/env python # -*- coding: UTF-8 -*- u'描述了之前未接触的类的相关知识' #私有变量,以__开头就是私有变量,但同时不要以__防止被视为类似于__name__的特殊变量 ''' class MyClass(object): def __init__(self,name,data): self.__name = name self.__data = data def print_data(self): print '%r : %r'%(self.__name,self.__data) cc = MyClass('sawyer',45) cc.print_data() ''' #继承的多态体现在子类的函数可以覆盖从父类继承的函数 class Father1(object): def run(self): print "father is running" class Sun1(Father1): def run(self): print "son is running" class Not_extend(object): def run(self): print u"哈哈,这样也行" def try_run(father): father.run() ''' try_run(Sun1()) try_run(Father1()) try_run(Not_extend()) ''' ase = Sun1() #print dir(ase) #dir()返回对象所有属性和方法的列表 #getattr(,),hasattr(,),setattr(,,)分别表示获得对象一个属性的、判断是否有该属性 #和设置一个属性(新增或改变都行) setattr(ase,'sdata',67) #setattr(,,)设置的属性只和对象绑定,中间的参数为属性名 print ase.sdata #必须使用字符串表示,get和has也同样
# -*- coding: UTF-8 -*- ''' def print_two(*args): arg1 , arg2 = args print "arg1: %r, arg2: %r" %(arg1 , arg2) ''' def print_again(a1 , a2): print "a1: %r , a2: %r" %(a1 , a2) def print_none(): print "is ok." def print_two(*args): #它的功能是告诉 python a1 , a2 = args #让它把函数的所有参数都接受进来,然后放到名字叫 args 的元组中去。 print "arg1: %r, arg2: %r" %(a1 , a2) print_two("asd","sa") print_again("adf","wqert") print_none()
#Exercício: Faça um nome que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas. nome = input("Digite seu nome: ") print("É um prazer em te conhecer,{}.".format(nome))
#Exercício: Faça um algoritmo que leia o preço de um produto e mostre seu novo preço com 5% de desconto. preco = float(input("Digite o valor do produto: ")) desconto = preco - (preco * 0.05) print("O valor a ser pago é R${:.2f}, já está com o desconto aplicado.".format(desconto))
""" ชื่อDiscord = ม.6 ภูมิ ภูมิระพี ระยอง ชื่อนามสกุล = นายภูมิระพี เสริญวณิชกุล Email = [email protected] ชั้น = ม.6 """ import random Questions = ["รักพ่อแม่ไหม?", "เคยช่วยพ่อแม่รดน้ำต้นไม้ไหม?", "เคยช่วยคนตาบอดข้ามถนน?", "ให้อาหารปลาไหม?", "เคยช่วยครูยกของไหม?"] random.shuffle(Questions) # เรียงข้อมูลที่อยู่ใน Questions ใหม่ LastQuesttion = "คุณรักสถาบันพระมหากษัตริย์ไหม?" # คำถามปั่น def random_question(): return random.shuffle(Questions) def fake_check(point, vip): if point >= 3 or vip == 1: print("คุณเป็นคนดีมากกกกกกก") else: print("คุณเป็นคนที่ไม่ดี อย่าลืมทำความดีกด้วยล่ะ") def get_point(ans): if ans == 1: return 1 else: return 0 def question(): point = 0 for i in Questions: print(i, " (ใส่แค่ 1 หรือ 2)", "\n1.Yes\n2.No") ans = 3 while ans > 2: ans = int(input(":")) point += get_point(ans) print("---------------------------------") epic_question(point) # อันนี้ปั่นเฉยๆ 5555 def epic_question(point): # ไม่ว่าใน question() จะตอบยังไงถ้าตอบข้อนี้ว่า Yes ก็คือเป็นคนดี print(LastQuesttion, " (ใส่แค่ 1 หรือ 2)", "\n1.Yes\n2.No") vip = int(input(":")) print("---------------------------------") fake_check(point , vip) def main(): question() if __name__ == "__main__": main()
import unittest from itertools import combinations """ A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,a2 + b2 = c2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the product abc. """ def is_pythagorean_triangle(lst): lst = sorted(lst) if len(lst) != 3: return False return (lst[0] * lst[0]) + (lst[1] * lst[1]) == (lst[2] * lst[2]) # AP function - Learnt use of combination ! def combine(product): for x, y in combinations(range(1, product - 1), 2): z = product - x - y if z > 0: if is_pythagorean_triangle([x, y, z]): return x * y * z class Test(unittest.TestCase): def test_known_input(self): self.assertTrue(is_pythagorean_triangle([4, 3, 5])) self.assertFalse(is_pythagorean_triangle([5, 6, 7])) self.assertFalse(is_pythagorean_triangle([5])) def test_combine(self): self.assertEqual(combine(1000), 31875000) if __name__ == "__main__": unittest.main()
from graphics import Point, Line, GraphWin, Text from math import sin, cos, radians def vect(point, theta): length = .00005 x = point.x + (length * cos(theta)) y = point.y + (length * sin(theta)) return Point(x, y) def main(): win = GraphWin("map", 1000, 800) win.setCoords(-88.357, 41.786, -88.355, 41.788) with open("2016-08-04_20-20-41.000.txt", "r") as log: lines = log.readlines() for n in range(0, len(lines) - 1, 3): line = lines[n].split(", ") if len(line) == 6: p = Point(float(line[2]), float(line[1])) p.setFill('red') Line(p, vect(p, radians(-(float(line[3]) + 270)))).draw(win) p.draw(win) else: Text(Point(float(lines[n+1].split(", ")[2]) + .00005, float(lines[n+1].split(", ")[1]) + .00005), line[0]).draw(win) print(line) main()
"""Read in data from a text file and process it using the algorithm. Current output line format: TIME, LAT, LON, CALC_BEARING, HEADING, STATUS """ # import tracker as track import header class Transcriber: """docstring for Transcriber.""" def __init__(self, filename): """Constructor.""" self.filename = filename self.data = [] self.index = 0 self.generate_data() print("Data populated, max index", self.max_index) def generate_data(self): """Read a line and extract the variables.""" with open(self.filename) as f: for line in f: data_list = line.replace('\n', '').split(',') try: self.data.append((data_list[0], data_list[1], data_list[2], data_list[4])) except IndexError: print("Ignoring malformed sentence at", line) self.max_index = len(self.data) - 1 def refresh(self): """Emulate refreshing the tracker by advancing to the next dataset.""" if self.index < self.max_index: self.index += 1 print("Refreshed. New index", self.index) def get_time(self): """Return time.""" # print("Time", self.data[self.index][0]) return self.data[self.index][0] def get_lat(self): """Return latitude.""" # print("Lat", self.data[self.index][1]) try: lat = float(self.data[self.index][1]) except TypeError: print("TypeError encountered", self.data[self.index][1]) lat = 0 finally: return lat def get_lon(self): """Return longitude.""" # print("Lon", self.data[self.index][2]) try: lon = float(self.data[self.index][2]) except TypeError: print("TypeError encountered", self.data[self.index][2]) lon = 0 finally: return lon def get_yaw(self): """Return heading.""" # print("Yaw", self.data[self.index][3]) try: yaw = float(self.data[self.index][3]) except TypeError: print("TypeError encountered", self.data[self.index][3]) yaw = 0 finally: return yaw def drift_check(coords, calc_bearings, comp_bearings, rotate_threshold): """Check if the vessel is currently drifting.""" # Check if the difference between the change in calculated bearing and the # change in compass bearing are greater than an arbitrary threshold. delta_diff = abs((coords.get_current_bearing() - calc_bearings.b[0]) - comp_bearings.delta_bearing()) return delta_diff > rotate_threshold def rotate_check(comp_bearings, rotate_threshold): """Check if the vessel is currently rotating.""" return abs(comp_bearings.delta_bearing()) > rotate_threshold def update_status(tracker, coords, calc_bearings, comp_bearings, rotate_threshold): """Update various status variables (drifting and float checks).""" # drifting = drift_check(coords, calc_bearings, comp_bearings, # rotate_threshold) is_float_coords = (type(tracker.get_lat()) is float and type(tracker.get_lon()) is float) is_float_yaw = type(tracker.get_yaw()) is float return is_float_coords, is_float_yaw def initialize(tracker, dist_threshold): """Initilialize the tracker with the given thresholds.""" coords = header.Coords(tracker.get_lat(), tracker.get_lon()) # tracker.refresh() is_float_coords = (type(tracker.get_lat()) is float and type(tracker.get_lon()) is float) for i in range(2): # print("I'm stuck! 1") if is_float_coords: coords.add_coords(tracker.get_lat(), tracker.get_lon()) # while coords.get_dist_travelled() < dist_threshold: # # print("I'm stuck! 2") # coords.lock() # tracker.refresh() # # if is_float_coords: # coords.add_coords(tracker.get_lat(), tracker.get_lon()) calc_bearings = header.Bearings(coords.get_current_bearing()) comp_bearings = header.Bearings(tracker.get_yaw()) return coords, calc_bearings, comp_bearings def run(): """Main algorithmic loop.""" tracker = Transcriber(file_in) init_dist_threshold = 2 dist_threshold = 3 # Threshold for linear movement in meters rotate_threshold = 4 # Threshold for rotational movement in degrees coords, calc_bearings, comp_bearings = initialize(tracker, init_dist_threshold) filename = (file_in.rsplit('.', 1)[0] + "_reprocessed.txt") print("Opening file", filename) data = open(filename, 'w') while tracker.index < tracker.max_index: # print("I'm stuck! 3") tracker.refresh() print(tracker.get_time()) state = "" is_float_coords, is_float_yaw = update_status( tracker, coords, calc_bearings, comp_bearings, rotate_threshold) try: drifting = drift_check(coords, calc_bearings, comp_bearings, rotate_threshold) except IndexError: print("Drift check failed!") if is_float_coords: coords.add_coords(tracker.get_lat(), tracker.get_lon()) if is_float_yaw: comp_bearings.add_bearing(tracker.get_yaw()) if comp_bearings.delta_bearing() < rotate_threshold: comp_bearings.lock() try: if coords.get_dist_travelled() > dist_threshold: if drifting: calc_bearings.adjust_bearing(comp_bearings.delta_bearing()) state = "D" else: calc_bearings.add_bearing(coords.get_current_bearing()) state = "N" else: coords.lock() if rotate_check(comp_bearings, rotate_threshold): calc_bearings.adjust_bearing(comp_bearings.delta_bearing()) state = "R" else: calc_bearings.lock() state = "S" data.write(str(tracker.get_time()) + ', ' + str(coords.lats[0]) + ', ' + str(coords.longs[0]) + ', ' + str(calc_bearings.b[0]) + ', ' + str(comp_bearings.b[0]) + ', ' + state + '\n') except (TypeError): pass data.close() file_in = "2016-08-04_18-11-10.000.txt" run()
"""Provides bearinga nd coords classes.""" import math import gps class Bearings: """Object that stores bearing calculated from GPS position.""" # This should not initialize with an initial bearing def __init__(self, bear=0): """Constructor.""" self.b = [bear] def add_bearing(self, b): """Insert a bearing at the beginning of the list.""" self.b.insert(0, b) if len(self.b) >= 10: __ = self.b.pop() # This stuff is for drift (maybe, we'll see how it goes) def delta_bearing(self): """Find the change in bearing.""" return(self.b[0]-self.b[1]) def lock(self): """Lock changes in bearing.""" self.add_bearing(self.b[0]) def adjust_bearing(self, delta): """Adjust bearing.""" self.add_bearing((self.b[0] + delta) % 360) class Coords: """An object that holds the 10 most recent lat/long values in degrees.""" def __init__(self, lat, lon): """Constructor.""" self.lats = [lat] self.longs = [lon] def add_coords(self, lat, lon): """Add new coords to beginning of list. If there are more than 10 coords, discard the oldest set. """ self.lats.insert(0, lat) self.longs.insert(0, lon) if(len(self.lats) >= 10): __ = self.lats.pop() __ = self.longs.pop() def get_current_bearing(self): """Return most recent calculated bearing based on GPS coordinates. In degrees East of North. """ # Find length of one degree of latitude and longitude based on average # of two most recent latitudes latlen, lonlen = gps.len_lat_lon((self.lats[0] + self.lats[1]) / 2) x = (self.longs[0] - self.longs[1]) * lonlen y = (self.lats[0] - self.lats[1]) * latlen # Bearing in degrees East of North b = 90 - math.degrees(math.atan2(y, x)) return b % 360 def lock(self): """Lock latitude and longitude.""" self.lats[0] = self.lats[1] self.longs[0] = self.longs[1] def get_dist_travelled(self): """Return distance between two most recent points.""" latlen, lonlen = gps.len_lat_lon((self.lats[0] + self.lats[1]) / 2) x = (self.longs[0] - self.longs[1]) * lonlen y = (self.lats[0] - self.lats[1]) * latlen d = ((x * x) + (y * y)) ** .5 return(d) # def rotation_check(gpsBearing, compBearing): # deltaGPS = gpsBearing.delta_bearing() # deltaComp = compBearing.delta_bearing() # allowedVariation = 10 # will be adjusted based on experiment # if(abs(deltaComp) > 5): # <-- change 0 to rotation threshold # if(abs(deltaGPS - deltaComp) > allowedVariation): # print("Stationary rotation is occuring (maybe)") # return True # else: # print("Turning is occuring (maybe)") # # else: # print("No rotation is occuring (probably)") # return False # def drift_check(gpsBearing, compBearing): # deltaGPS = gpsBearing.delta_bearing() # deltaComp = compBearing.delta_bearing() # allowedVariation = 10 # this number will be changed based on experiments # if(abs(deltaGPS) > 5): # <-- rotation threshold # if(abs(deltaGPS - deltaComp) > allowedVariation): # print("Drift is occuring (maybe)") # return True # else: # print("No drift is occuring (probably)") # return False # else: # print("No drift is occuring (probably)") # return False
''' ID: 2010pes1 TASK: dualpal LANG: PYTHON3 ''' def convert(n,i,nums): lst = [] st = '' while i>0: lst.append(nums[i%n]) i = (i - (i%n))/n for i in range(len(lst)): st += lst[len(lst)-1-i] return st # filter solutions that are already palindromic in one base (ex: base 2) # with every other base to find a solution (ex: bases, 3 or 4 or 5 or 6.. or 10) # in case there are lesser solutions than the current one # store the first n numbers greater than s, that satisfy the above condition in memory def checkPal(lst): p = True for j in range(len(lst)//2): if lst[j] != lst[len(lst)-1-j]: p = False break return p def solve(n,s,nums): f = open("dualpal.out","w") i = 0 val = s+1 while i < n: counter = 0 for k in range (2,10+1): lst = convert(k,val,nums) p = checkPal(lst) if p and i<n: counter+=1 if counter > 1: f.write(f"{val}\n") i+=1 break val+=1 f.close() def main(): f = open("dualpal.in", "r") n, s = map(int,f.read().strip().split(" ")) nums = {} for i in range(0,9+1): nums[i] = str(i) solve(n,s,nums) f.close() if __name__ == "__main__": main()
class person: def __init__(self,n,a,g): self.name=n self.age=a self.gender=g def display(self): print("Name:",self.name) print("Age:",self.age) print("Gender:",self.gender) class publications: def __init__(self,no_rp,no_of_books,no_art): self.no_rp=no_rp self.no_of_books=no_of_books self.no_art=no_art def display(self): print("Number of research program published=",self.no_rp) print("Number of books published=",self.no_of_books) print("Number of articles published=",self.no_art) class faculty(person,publications): def __init__(self,name,age,gender,desig,dept,no_rp,no_of_books,no_art): person.__init__(self,name,age,gender) publications.__init__(self,no_rp, no_of_books, no_art) self.desig=desig self.dept=dept def display(self): person.display(self) print("Designation=",self.desig) print("Department=",self.dept) publications.display(self) n=input("Enter name:") a=int(input("Enter age:")) g=input("Enter gender:") d=input("Enter degination:") c=input("Enter course:") r=int(input("Enter number of research programs:")) b=int(input("Enter number of books published:")) ar=int(input("Enter number articles published:")) print('\n') f=faculty(n,a,g,d,c,r,b,ar) f.display()
a=input("Enter file name to read:") b=input("Enter file name to write:") f1=open(a,mode='r') f2=open(b,mode='w') str=f1.read() f2.write(str) f1.close() f2.close() with open("two.txt",mode='r') as f: fstr=f.read() print("The contents in the file two is:\n ") print(fstr)
n=int(input("Enter a number:")) rev=0 while n!=0: rev=rev*10+n%10 n=int(n/10) print(f"Reverse={rev}")
#dict={x:2*x for x in range(1,10)} d={} for i in range(1,10): d[i]=i*2 print(d)
class name(Exception): def __init__(self,name): self.name=name def display(self): print(f"Hello {self.name} :)") try: uname=(input("Enter the name:")) raise name(uname) except name as r: r.display()
a=input("Enter the file name:") with open(a,mode='r') as f: str=f.read() l=str.split() k=len(l) print(f"Number of words ={k}")
import re ch=input("Enter a word:") k=len(ch) str="" l=re.findall(".",ch) if(ch[k-1]=='f'): l.pop() for i in l: str+=i str+="ves" elif(ch[k-2]=='f'): l.pop() l.pop() for i in l: str+=i str+="ves" elif(ch[k-1]=='y'): l.pop() for i in l: str+=i str+="ies" elif(ch[k-1]=='h'): str+=ch str+="es" else: str+=ch+"s" print(str)
s=int(input("Enter the salary:")) g=input("Enter the gender(m/f):") r=0 if(s<=10000): r=2 if(g=="m"): r=r+5 elif(g=='f'): r=r+10 s+=(r*s)/100 print("Salary=",s)
ch=int(input("Area:\n1.rectange\n2.triangle\n3.circle\n4.square\nEnter choice:")) if (ch==1): a = int(input("Enter length:")) b = int(input("Enter breadth:")) area=a*b print("Area of rectangle=",area) elif(ch==2): a = int(input("Enter length:")) b = int(input("Enter breadth:")) area=(a*b)/2 print("Area of triangle=", area) elif(ch==3): a = int(input("Enter the value of side:")) area=(22*a**2)/7 print("Area of circle=",area) elif(ch==4): a = int(input("Enter the value of side:")) area=a**2 print("Area of square=",area) else: print("Invalid Input!!!")
jedi=(input("Name a jedi master: ")) if jedi.upper()=="YODA": print("Jedi Master, he is!")
from bitterdispute.variable import Variable import numpy as np import math def sin(x): """Defines what happens when sin operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: new_x = Variable(name=x.name, value=np.sin(x.val), derivative=x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*np.cos(x.val) for key in x.der2: new_x.der2[key] = x.der2.get(key)*np.cos(x.val) - (x.der.get(key))**2*np.sin(x.val) return new_x except AttributeError: # constant return np.sin(x) def cos(x): #--> -sin """Defines what happens when cosine operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: new_x = Variable(name = x.name, value = np.cos(x.val), derivative = x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*(-np.sin(x.val)) for key in x.der2: new_x.der2[key] = x.der.get(key)**2*(-np.cos(x.val)) - x.der2.get(key)*np.sin(x.val) return new_x except AttributeError: return np.cos(x) def tan(x): #--> 1/cos^2(x) """Defines what happens when tangent operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: new_x = Variable(name = x.name, value = np.tan(x.val), derivative = x.der, second_derivative = x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*(1 / (np.cos(x.val) ** 2)) for key in x.der2: new_x.der2[key] = (1/np.cos(x.val))**2*(x.der2.get(key) + 2*(x.der.get(key)**2)*np.tan(x.val)) return new_x except AttributeError: return np.tan(x) def sqrt(x): """Defines what happens when square root operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: #Ensure input domain valid if x.val < 0: raise ValueError('Cannot evaluate the square root of a negative number') new_x = Variable(name = x.name, value = np.sqrt(x.val), derivative = x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*(1/(2*np.sqrt(x.val))) for key in x.der2: new_x.der2[key] = (2*x.val*x.der2.get(key) - x.der.get(key)**2)/(4*x.val**(3/2)) return new_x except AttributeError: return np.sqrt(x) def log(x, base=math.e): """Defines what happens when log operations are performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: #Ensure input domain valid if x.val <=0: raise ValueError('Cannot evaluate the log of a non-positive number') new_x = Variable(name = x.name, value = math.log(x.val, base), derivative = x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = x.der.get(key)/(x.val * math.log(base)) for key in x.der2: new_x.der2[key] = x.val*x.der2.get(key) - x.der.get(key)**2/x.val**2 return new_x except AttributeError: return math.log(x, base) def exp(x): """Defines what happens when exponential operations are performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: new_x = Variable(name=x.name, value = np.exp(x.val), derivative = x.der, second_derivative = x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*new_x.val for key in x.der2: new_x.der2[key] = np.exp(x.val)*(x.der2.get(key) + x.der.get(key)**2) return new_x except AttributeError: # constant return np.exp(x) def arcsin(x): """Defines what happens when arcsin operations are performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: if x.val < -1.0 or x.val > 1.0: raise ValueError("input of arcsin should within (-1, 1)") new_x = Variable(name=x.name, value = np.arcsin(x.val), derivative = x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = 1/np.sqrt(1 - x.val**2)*x.der.get(key) for key in x.der2: new_x.der2[key] = x.val*x.der.get(key)**2 - (x.val**2 -1)*x.der2.get(key)/((1-x.val**2)**3/2) return new_x except AttributeError: # constant if x < -1.0 or x > 1.0: raise ValueError("input of arcsin should within (-1, 1)") return np.arcsin(x) def arccos(x): """Defines what happens when arccos operations are performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: if x.val < -1.0 or x.val > 1.0: raise ValueError("input of arccos should within (-1, 1)") new_x = Variable(name=x.name, value = np.arccos(x.val), derivative = x.der, second_derivative = x.der2) for key in x.der: new_x.der[key] = -1/np.sqrt(1 - x.val**2)*x.der.get(key) for key in x.der2: new_x.der2[key] = -((x.val**2*(-x.der2.get(key)) + x.der2.get(key) + x.val*x.der.get(key)**2)/((1-x.val**2)**3/2)) return new_x except AttributeError: # constant if x < -1.0 or x > 1.0: raise ValueError("input of arcsin should within (-1, 1)") return np.arccos(x) def arctan(x): """Defines what happens when arctan operations are performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: new_x = Variable(name=x.name, value = np.arctan(x.val), derivative = x.der, second_derivative = x.der2) for key in x.der: new_x.der[key] = 1/(1+x.val**2)*x.der.get(key) for key in x.der2: new_x.der2[key] = (x.val**2 + 1)*x.der2.get(key)-2*x.val*x.der.get(key)**2/(x.val**2 + 1)**2 return new_x except AttributeError: # constant return np.arctan(x) def sinh(x): """Defines what happens when hyperbolic sine operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: # Create a Variable instance new_x = Variable(name=x.name, value = np.sinh(x.val), derivative = x.der, second_derivative = x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*np.cosh(x.val) for key in x.der2: new_x.der2[key] = x.der2.get(key)*np.cosh(x.val) + x.der.get(key)**2*np.sinh(x.val) return new_x except AttributeError: # if x = constant return math.sinh(x) def cosh(x): """Defines what happens when hyperbolic cosine operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ try: # Create a Variable instance new_x = Variable(name=x.name, value = np.cosh(x.val), derivative = x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*np.sinh(x.val) for key in x.der2: new_x.der2[key] = x.der2.get(key)*np.sinh(x.val) + x.der.get(key)**2*np.cosh(x.val) return new_x except AttributeError: # if x = constant return math.cosh(x) def tanh(x): """Defines what happens when hyperbolic tangent operations performed on a Variable() object or a constant value. Includes calculation of first and second derivative. """ print(x) try: # Create a Variable instance new_x = Variable(name=x.name, value = np.tanh(x.val), derivative = x.der, second_derivative=x.der2) for key in x.der: new_x.der[key] = x.der.get(key)*((1.0/np.cosh(x.val))**2) for key in x.der2: new_x.der2[key] = (1/np.cosh(x.val)**2)*(x.der2.get(key) - 2*x.der.get(key)**2*np.tanh(x.val)) return new_x except AttributeError: # if x = constant return math.tanh(x)
class QuizBrain: """ ... """ # ... def __init__(self, question_list, question_number=0, score=0): self.current_question_number = question_number self.question_list = question_list self.user_score = score # def next_question(self): # if self.current_question_number <= len(self.question_list) - 1: # self.current_question_number += 1 # # # user_option = input(self.question_list[self.current_question_number]['question']) # wrong! Not this! # user_option = input(f'Q.{self.current_question_number}: ' # # we want this! # f'{self.question_list[self.current_question_number - 1].question} (True/False): ') def next_question(self): self.current_question_number += 1 user_option = input(f'Q.{self.current_question_number}: ' f'{self.question_list[self.current_question_number - 1].question} (True/False): ') self.check_answer(user_option, self.question_list[self.current_question_number - 1].answer) def still_has_questions(self): return self.current_question_number <= len(self.question_list) - 1 def check_answer(self, user_choice, correct_choice): if user_choice.lower() == correct_choice.lower(): self.user_score += 1 print('You got it right!') else: print('That\'s wrong!') print(f'The correct answer was: {correct_choice}') print(f'Your current score is: {self.user_score}/{self.current_question_number}.') print('\n')
import pandas as pd import quandl class Stockobj(): """ By Ben Rogojan Date: 2018-09-25 A class used to represent a stock and the data for its stock prices in a set data range Attributes ---------- StockTicker : str Represents the 1-5 character ticker symbol Start_Date : date Represents the starting date the price data was pulled from End_Date : date Represents the ending date the price data was pulled from price_data : data frame Represents a data frame that contains price data on the Stock ticker - the ticker symbol for the stock date - the date the prices and volumes were recorded volume - the number of shares that exchanged traders close - the closing price of the stock open - the opening price of the Stock high - the highest price the stock got during the day low - the lowest price the stock got during the day date_ym - This is added in and represents the day variable in the YYYY-MM format Methods ------- get_price_dict Gets data from the WIKIP API using the quandl library """ StockTicker ="" Start_Date="" End_Date="" price_data = pd.DataFrame() def __init__(self, p_StockTicker,p_Start_Date,p_EndDate): self.Start_Date = p_Start_Date self.End_Date = p_EndDate self.StockTicker = p_StockTicker self.get_price_dict() def get_price_dict(self): quandl.ApiConfig.api_key = "s-GMZ_xkw6CrkGYUWs1p" data = quandl.get_table('WIKI/PRICES' , qopts = { 'columns': ['ticker', 'date', 'volume','close','open','high','low'] } , ticker =self.StockTicker , date = { 'gte': self.Start_Date, 'lte': self.End_Date }) #We are adding a column to the data frame that contains YYYYMM data['date_ym'] = pd.to_datetime(data['date']).dt.to_period('M') self.price_data = data
from maze import Maze from maze import Map class DepthLimited(Maze): def __init__(self, x, y): Maze.__init__(self, x, y) self._map = self.m def create_node(self, x, y): self._map.visit(x, y, self.win, "blue") def check_neighbours(self, b): neighbours = [] mp = self._map i = b.x j = b.y left = False right = False top = False bot = False if i + 1 < 40: right = True if i - 1 > 0: left = True if j + 1 < 40: bot = True if j - 1 > 0: top = True for z in range(0, 4): if not b.walls[z]: if z == 0 and top and mp.mapping[i][j - 1] and (mp.mapping[i][j - 1] not in DepthLimited.visited) and not \ mp.mapping[i][j - 1].walls[3]: neighbours.append(mp.mapping[i][j - 1]) if z == 1 and left and mp.mapping[i - 1][j] and (mp.mapping[i - 1][j] not in DepthLimited.visited) and not \ mp.mapping[i - 1][j].walls[2]: neighbours.append(mp.mapping[i - 1][j]) if z == 2 and right and mp.mapping[i + 1][j] and (mp.mapping[i + 1][j] not in DepthLimited.visited) and not \ mp.mapping[i + 1][j].walls[1]: neighbours.append(mp.mapping[i + 1][j]) if z == 3 and bot and mp.mapping[i][j + 1] and (mp.mapping[i][j + 1] not in DepthLimited.visited) and not \ mp.mapping[i][j + 1].walls[0]: neighbours.append(mp.mapping[i][j + 1]) return neighbours def DIS(self, root, depth): s = self.DFS(root, depth, root) print("here") stack = [] visited = {} solution = [] solution_found = False def DFS(self, current, count): if count > 500: DepthLimited.solution_found = True return if DepthLimited.solution_found: self._map.visit(current.x, current.y, self.win, "yellow") return DepthLimited.stack.append(current) goal = self._map.mapping[self._map.row - 5][self._map.col - 5] if current.x == goal.x and current.y == goal.y: self._map.visit(current.x, current.y, self.win, "yellow") return DepthLimited.visited[count] = current neighbours = self.check_neighbours(current) for z in range(0, len(neighbours)): self.DFS(neighbours[z], count + 1) ''' def DFLS(self, node, depth, parent): current = node print("visiting: x: ", current.x, " y: ", current.y) DepthLimited.stack.append(current) goal = self._map.mapping[self._map.row - 1][self._map.col - 1] if node.x == goal.x and node.y == goal.y: return node if depth == 0: return False else: cut_off_occurred = False neighbours = self.check_neighbours(current, parent) for z in range(0, len(neighbours)): print("-----------> child: x: ", neighbours[z].x, " y: ", neighbours[z].y) s = self.DFS(neighbours[z], depth - 1, current) if not s: cut_off_occurred = True # CutOff occurred on path so cut down root to path somehow elif s: return node if cut_off_occurred: return False else: return False ''' def _visit(stack, mp, win): b = stack.copy() for i in b: cur = b.pop() mp.visit(cur.x, cur.y, win, "yellow") win.getMouse() def main(): d = DepthLimited(20, 20) d.DFS(d.m.mapping[0][0], 0) main()
#INDEX ERROR import sys a = "abcde" n = input() print(a[n]) #BUG, IndexError print(a[-7]) #BUG, IndexError print(sys.argv[0]) print(sys.argv[1]) #BUG, IndexError a_list = ['a', 'b', 'mpilgrim', 'z', 'example'] print(a_list[-6]) #BUG, IndexError print(a_list[-3]) a_list.append(['c','d','e']) print(a_list[5][3]) #BUG, IndexError , two dimensional a_list.pop(-1) #BUG, IndexError
#Python number to check if number is armstrong or not def check_armstrong_number(num): sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit**3 temp//= 10 if sum == num: print(num, 'Is armstrong number') else: print(num, 'Is not armstrong number') input_val = int(input('Enter any number')) check_armstrong_number(input_val)
#_*_ coding: utf-8 _*_ #test data ''' Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed. BONUS: If we represent _ as sea level, a step up as /, and a step down as \, ''' #n: the number of steps Gary takes nn = 8 #s: a string describing his path ss = ['U','D','D','D','U','D','U','U'] sss = ['U','U','D','D','U','D','U','U'] 5 # Complete the countingValleys function below. def countingValleys(n, s): #add a unit test case- for practice # variable to keep track of number of valley numOvalley = 0 # vaiable for the valley pattern, previousValue= 'D' #working things out to find the pattern #walk through list for path in s: #eveluate if the value is not equal to "D" if path != previousValue: #if meet requirement then add value numOvalley = numOvalley + 1 print(f'Valley {numOvalley}') #need work since it only counts the nummber of "U" #add another requirement that looks at the previoud index countingValleys(nn,sss) """ help to solve problems.. Read the problem completely twice. Solve the problem manually with 3 sets of sample data. Optimize the manual steps. Write the manual steps as comments or pseudo-code. Replace the comments or pseudo-code with real code. Optimize the real code. """
# -*- coding: utf-8 -*- """ Created on Thu Feb 15 11:09:05 2018 @author: mclower """ import numpy as np n=6 p1=5 p2=3 def f(n,p1,p2): Sum=0 for ii in range(n): if(ii % p1 == 0): Sum= Sum +ii elif(ii % p2==0): Sum=Sum +ii return Sum X=f(n,p1,p2) print(X)
import unittest from InventoryAllocator import InventoryAllocator ########################################## # INSTRUCTIONS FOR TESTING # ########################################## # # # run the following code: # # # # $ python InventoryAllocatorTest.py # # # ########################################## class InventoryAllocatorTest(unittest.TestCase): def test_happy_case(self): print("\nStarting Test: test_happy_case") IA = InventoryAllocator() order = { 'apple': 5} store_1 = {'name':'owd', 'inventory': { 'apple': 5}} inventory_dist = [store_1] expected = [{'owd': {'apple': 5}}] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_not_enough_inventory(self): print("\nStarting Test: test_not_enough_inventory") IA = InventoryAllocator() order = { 'apple': 5} store_1 = {'name':'owd', 'inventory': { 'apple': 2 }} inventory_dist = [store_1] expected = [] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_should_split(self): print("\nStarting Test: test_should_split") IA = InventoryAllocator() order = { 'apple': 5, 'banana': 10} store_1 = {'name':'owd', 'inventory': { 'apple': 2 , 'banana': 1}} store_2 = {'name':'dsw', 'inventory': { 'apple': 3 , 'banana': 12}} inventory_dist = [store_1, store_2] expected = [{'owd': {'apple': 2, 'banana': 1}}, {'dsw': {'apple':3, 'banana': 9}}] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_not_at_any_stores(self): print("\nStarting Test: test_not_at_any_stores") IA = InventoryAllocator() order = { 'apple': 5, 'banana': 10} store_1 = {'name':'owd', 'inventory': { 'pickles': 2 , 'grapes': 1}} store_2 = {'name':'dsw', 'inventory': { 'chips': 3 , 'juice': 12}} inventory_dist = [store_1, store_2] expected = [] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_zero_inventory_stores(self): print("\nStarting Test: test_zero_inventory_stores") IA = InventoryAllocator() order = { 'apple': 5, 'banana': 10} store_1 = {'name':'owd', 'inventory': { 'apple': 0 , 'banana': 0}} store_2 = {'name':'dsw', 'inventory': { 'chips': 0 , 'banana': 0}} inventory_dist = [store_1, store_2] expected = [] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_no_stores(self): print("\nStarting Test: test_no_stores") IA = InventoryAllocator() order = { 'apple': 5, 'banana': 10} inventory_dist = [] expected = [] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_no_order(self): print("\nStarting Test: test_no_order") IA = InventoryAllocator() order = {} store_1 = {'name':'owd', 'inventory': { 'apple': 0 , 'banana': 0}} store_2 = {'name':'dsw', 'inventory': { 'chips': 0 , 'banana': 0}} inventory_dist = [store_1, store_2] expected = [] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") def test_no_order_no_stores(self): print("\nStarting Test: test_no_order_no_stores") IA = InventoryAllocator() order = {} inventory_dist = [] expected = [] self.assertEqual(IA.solution(order, inventory_dist), expected) print("PASSED!") if __name__ == '__main__': print('\n'+'='*40) print('= Running Tests for InventoryAllocator =') print('='*40,'\n') unittest.main()
from tkinter import * #importing tkinter module. root = Tk() #creating the master. frame = Frame(root) #creating the frame. frame.pack() bottomframe = Frame(root) #creating the bottom frame. bottomframe.pack( side = BOTTOM ) redbutton = Button(frame, text="Red", fg="red") #creating the red button. redbutton.pack( side = LEFT) greenbutton = Button(frame, text="Brown", fg="brown")#creating the green button. greenbutton.pack( side = LEFT ) bluebutton = Button(frame, text="Blue", fg="blue")#creating the blue button. bluebutton.pack( side = LEFT ) blackbutton = Button(bottomframe, text="Black", fg="black")#creating the black button. blackbutton.pack( side = BOTTOM) root.mainloop()
from datetime import datetime class Account: def __init__(self, first_name, last_name,phone_no,bank): self.self.first_name = first_name self.last_name = last_name self.phone_no = phone_no self.bank = bank self.balance = 0 self.withdraw_summary = [] self.deposit_summary = [] self.loan_balance = 0 def account_name(self): name = "{} account for {} {}".format( self.bank, self.first_name, self.last_name, self.phone_no, self.bank) return name def deposit(self, amount): try: amount + 1 except:TypeError print("Please enter amount in figures") return if amount <=0: print("You can\'t deposit zero or negative") else: self.balance += amount self.deposits.append(amount) formated_time = time.strftime("%A, %drd %B %Y, %H:%M %p") print("You have deposited {} to {}".format(amount, self.account_name(),formated_time)) return def withdraw(self, amount): try: amount + 1 except TypeError: print("You must enter the amount in figures") return if amount <= 0: print("You can\'t withdraw zero or negative") elif amount > self.balance: print("Insufficient funds") else: self.balance -= amount self.withdrawals.append(amount) print("You have withdrawn {} from {}".format(amount, self.account_name())) def get_balance(self): return "The balance for {} is {}".format(self.account_name(), self.balance) def show_deposit_statements(self): for deposit in self.deposits: formated_time = time.strftime("%A, %drd %B %Y, %H:%M %p") print("{} deposited on {}".format(deposit, formated_time)) def show_withdrawals_statement(self): for withdraw in self.withdrawals: print(withdraw) def request_loan(self, amount): try: amount + 1 except TypeError: print("Please enter the amount in figures") return if amount <= 0: print("You can\'t request for an amount low than zero") else: self.loan = amount print("You have been given a loan of {}".format(amount)) def repay_loan(self, amount): try: amount + 1 except TypeError: print("Please enter the amount in figures") return if amount <= 0: print("Too low to repay your amount") elif self.loan == 0: print("You don't have a loan at the moment") elif amount > self.loan: print("Your loan is {} please enter an amount that is less or equal".format(self.loan)) else: self.loan == amount time ==datetime.now() repayment={ "time":time "amount":amount } self.loan -= amount print("You have repaid you loan with {} your balance is {}".format(amount, self.loan)) def repay_loan_statement(self) for repayment in self.loan_repayments: time= repayment["time"] amount=repayment["amount"] formated_time=self.get_formatted_time(time) statement="You repaid {} on {}".format(amount,formated_time) print (statement0 class BankAccount(Account): def __init__(self,first_name,last_name,phone_no,bank) self.bank = bank super().__init__(first_name,last_name,phone_no) class MobileMoneyAccount(Account): def __init__(self,first_name,last_name,phone_no,service_provider) self.service_provider=service_provider self.airtime =[] super().__init__(first_name,last_name,phone_no) def buy_airtime(self,amount): try: amount +1 except TypeError: print("Please enter amount in figures") return if amount >self.balance: print ("You should have enough balance") else: self.balance-= amount time =datetime.now() "time":time "airtime":amount } self.airtime.append(airtime) print("You\'ve bought airtime worth {} on {}".format(amount,self.get_formatted_time(time))) def pay_bill(self,amount): try: amount +1 except TypeError: print("Please enter amount figures") return if amount>self.balance: print("Should have enough balance") else: self.balnce -= amount time=datetime.now() "time":time "bill":amount } self.bill.append(bill) print("You\'ve paid bill worth {} on {} to {}".format(amount,self,get_formatted_time(time))) def send_money(self.amount): try: amount +1 except TypeError: print("Please enter amount in figures") if amount >self.balance: print("You have enough balance") else: self.balance -=amount time = datetime .now() sendmoney{ "time":time "send_money":amount } self.send_money.append(send_money) print ("You\'ve sent {} money to {} on {}".format(amount,self.get_formatted_time(time))) def recieve_money(self,amount): time=datetime.now() recieve_money{ "time":time, "recieve_money":amount } self.recieve_money.append(recieve_money) print("You\'ve recieved {} on {} and your new balance is {}".format(amount,get_formated_time(time),self.balance)) acc1 = BankAccount("Ringo" ,"Martinez",+2547093886720,"Equity") acc1.first_name acc1.deposit(100500) print(acc1.first_name) acc1.deposit(200500) print(acc1.balance) acc1.request_loan(8000) acc1.repay_loan(3000) acc1.repay_loan(45000) acc1.repay_loan(40000) print(acc1.loan) print(acc1.balance) acc1.request_loan(7040) acc1.deposit(700) acc1.deposit("eighty") acc1.deposit(3556) acc1.deposit(1504) acc1.show_deposit_statements() acc1.request_loan("eighty")
# sorted()相当于for i in 括号里的参数,把i排序,key=相当于把i加工一下,按加工之后的排序,但是最后排序结果还是原来的i # 结果里面只有排序好的i # sort和sorted一样,只是sorted返回新的列表,sort排序原来的对象 # 按照键排序 l3 = sorted({1: 'D', 5: 'B', 2: 'B', 4: 'E', 3: 'A'}.items(),key = lambda item:item[0]) print('l3',l3) l2 = sorted([1,5,3,2],key=lambda item:item**2) l4 = sorted([1,5,3,2],reverse=True) l1 = sorted({1: 'D', 5: 'B', 2: 'B', 4: 'E', 3: 'A'}) l5 = sorted({1: 'D', 5: 'B', 2: 'B', 4: 'E', 3: 'A'}.values(),key=lambda x:x.lower()) l6 = sorted(['b','a','c','A','C','B'],key=lambda item:item.lower()) l7 = sorted(['b','a','c','A','C','B'],key=str.lower) # 不懂 print(l7) l = ['b','a','c','A','C','B'] l.sort(key=lambda item:item.upper(),reverse=True) print(l)
# Good morning! Write a function called reverseNumber that reverses a number. # Input Example: # 12345 # 555 # Output Example: # 54321 # 555 def reverse(num): newNum = '' for n in str(num): newNum = n + newNum return int(newNum) print(reverse(12345))
def code(invoerstring): ascistring = "" for letter in invoerstring: ascistring = ascistring + chr(ord(letter)+3) return ascistring naam = str(input("Naam: ")) beginst = str(input("Beginstation: ")) eindst = str(input("Eindstation: ")) invoerstring = str(naam + beginst + eindst) print(code(invoerstring))
from tkinter import * from tkinter.messagebox import showinfo root = Tk() label = Label(master=root, text='Hello World', background='white', foreground='blue', font=('Helvetica', 16, 'bold italic'), width=20, height=3) label.pack() def hallo(): grondtal = int(entry.get()) kwadraat = grondtal ** 2 tekst = "kwadraat: van {} = {}" label["text"] = tekst.format(grondtal, kwadraat) def clicked(): bericht = 'Chris je moeder!' showinfo(title='popup', message=bericht) button1 = Button(master=root, text='Button 1',command=hallo) button1.place(x=10, y=100) button = Button(master=root, text='Druk hier', command=clicked) button.pack(pady=10) entry = Entry(master=root) entry.pack(padx=10, pady=10) root.mainloop()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 4 21:21:19 2019 @author: Bowton """ import math import numpy as np import matplotlib.pyplot as plt def getArea(): #gets user input for the length of the wind farm #then calculates the area and returns length and area length = input('What is the length of the wind farm in km?') length = float(length)#makes sure length isn't a string length = length * 1000 #makes length in meters area = (length**2)#our area is a grid (could be adapted to different shapes later on) return area, length def getSweptArea():#gets user input for swept area, same as function above sweptArea = input('What is the swept area of the wind turbine in meters squared?') sweptArea = float(sweptArea) return sweptArea def getRotorDiameter(sweptArea):#calculates the rotor diameter based on the A = pi*r^2 diameter = 2*math.sqrt(sweptArea/math.pi) return diameter def getMaxTurbines(diameter,length):#gets maximum number of turbines that will fit in the wind farm diameter = round(diameter)#rounds the diameter maxTurbines = (length / (7*diameter))**2#divides the length of the farm by 7 diameters of the wind turbine maxTurbines = math.floor(maxTurbines)#rounds down to nearest int because you can't go over this amount of turbines return maxTurbines def getTurbineCoordinates(maxTurbines,diameter,length):#gets the coordinates of the turbines xCoordinates = np.zeros(maxTurbines)#array of zeros, length is max number of turbines because we need the locations of all of them, for x values yCoordinates = np.zeros(maxTurbines)#this array is for the y values x = 0 y = 7.5*diameter #makes sure it isn't too close to the start in case there are obstacles right on the edge of the wind farm that must be avoided i = 0#counter while y < length: #makes sure it doesn't go out of bounds based on the length of the wind farm x = 7.5*diameter while x < (length): #adds values to their respective arrays incrementally xCoordinates[i] = x yCoordinates[i] = y x = x + 7.5*diameter i = i + 1 y = y + 7.5*diameter return xCoordinates, yCoordinates def graphCoordinateList(xCoordinates,yCoordinates,diameter,length):#graphs the arrays of coordinates j = 0 totalTurbines = 0#number of turbines that are not at location (0,0) while (xCoordinates[j] != 0):#this gets the number of turbines that are not at location (0,0) and graphs them plt.plot(xCoordinates[j], yCoordinates[j], "b.") totalTurbines = totalTurbines + 1 j = j+1 #increments plt.xlim(0, length+(7.5*diameter))#setting x limit of the graph plt.ylim(0, length+(7.5*diameter))#setting y limit of the graph plt.xlabel('xCoordinates') plt.ylabel('yCoordinates') plt.show() return totalTurbines def totalPowerOutput(sweptArea, totalTurbines):#calculates the total power output of the wind farm totalPower =0 totalPower = (0.5*(sweptArea)*(1728*1.225))/1000 totalPower = (totalPower*totalTurbines)/1000 print("The total power output of this wind farm is " + str(totalPower) + " Mega Watts") return totalPower
graph = { 'A':['B','C'], 'B':['A','C','D'], 'C':['A','B','D','E'], 'D':['B','C','E','F'], 'E':['C','D'], 'F':['D'] } def BFS(graph,s): stack = [] stack.append(s) #节点栈 seen = set() #已输出队列 seen.add(s) while (len(stack) > 0): vertex = stack.pop() #后进先出 nodes = graph[vertex] for w in nodes: if w not in seen: stack.append(w) seen.add(w) print(vertex) BFS(graph,'A')
print('{}'.format("format this string")) fname="abhishek" lname="sawant" print('{}....{}'.format(fname,lname)) #Use format to align the output and give width print(format(fname,"<50s")) print(format(fname,">50s")) #Fill Empty spaces print(format(fname,"@<50s")) print(format(fname,"$>50s")) #Format integers print("Score is {}".format(8)) print("Score is {:,}".format(898978)) print("Score is {:,}".format(456898978)) print("Score is {:15,} only".format(456898978)) print("Score is {:<15,} only".format(456898978)) print("Score is {:@>15,} only".format(456898978)) print("Score is {:@<15,} only".format(456898978)) #Center Alignment print("Score is {:@^50,} only".format(456898978)) #Integer to Binary number = 0 print("Binary of 12 is {0:o}".format(number)) while(number <= 20): print("Binary of {0} is {1:b} Octal is {2:o} HExa is {3:x}".format(number,number,number,number)) number+=1 #Format to access list and dictionary items language=['Python','django','java','node'] print("I love to work with",language[0]) print("I love to work with {0[0]}".format(language)) print("Secure Language is {0[2]}".format(language)) friends = {"mohan":"CHina","rohan":"Japan"} print("Friend in Chennai: {0[mohan]} \nRohan is from{0[rohan]}".format(friends))
sample=() print(type(sample)) sample= 25,35,45 print(sample) sample = (25,65,45,[90,"check",5.5]) print(sample) sample=((3,4,5),(4,5,6),(5,6,7)) print(sample) print(sample[1][1]) #creating tuples from list and sets scores = [25,35,45] sample=tuple(scores) print(sample) scores = {25,35,45} sample=tuple(scores) print(sample) onlyOne = "omg" checkOne=(onlyOne,) print(checkOne) print(type(checkOne)) sample = (25,65,45,[90,"check",5.5],90,78,'d') print(sample[1:]) #(25, 65, 45, [90, 'check', 5.5], 90) print(sample[:5]) #(25, 45, 90) print(sample[:5:2]) #Tuple is immutable -> You cannot modify elements in the tuple # ->but you can assign new tuple to same variable sample=(25,65,45) print(sample[0]) #TypeError: 'tuple' object does not support item assignment #sample[0]=35 sample=(35,64,45) print(sample) vowel1=('a','e','i') vowel2=('o','u') print( vowel1+vowel2) #TypeError: 'tuple' object doesn't support item deletion #del sample[0] #print(sample) #Delete the given tuple #del sample for item in sample: print(item)
lengthOfList=int (input("Enter the length of list :- ")) list=[] for i in range(lengthOfList) : list.insert(i,int (input("Enter element in list:-"))) print(list) sliceStart=int(input("Slice Start :- ")) sliceEnd=int(input("Slice End :- ")) list=list[sliceStart:sliceEnd] list.sort() print(list)
import threading import time def callMeForEachThread(threadName,delay): counter=0 while counter <= 10: print(threadName," ",str(counter)) time.sleep(delay) counter+=1 thread1=threading.Thread(target=callMeForEachThread,args=("Thread1",1)) thread2=threading.Thread(target=callMeForEachThread,args=("Thread2",2)) thread1.start() thread2.start() thread1.join() thread2.join() print("Multithreading")
""" Given 1->2->3->4, you should return the list as 2->1->4->3 """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ # if size of list is 0 or 1 if head == None or head.next == None: return head # does the swap new_node = head.next nxt = new_node.next new_node.next = head head.next = self.swapPairs(nxt) return new_node
""" minimum swaps """ def minimumSwaps(arr): count = 0 i = 0 l = len(arr) sorted_arr = sorted(arr) while i < l: n = arr[i] pos = sorted_arr.index(n) if (i != pos): arr[i], arr[pos] = arr[pos], arr[i] count += 1 i -= 1 i += 1 return count print(minimumSwaps([4, 3, 1, 2])) print(minimumSwaps([2, 3, 4, 1, 5])) print(minimumSwaps([1, 3, 5, 2, 4, 6, 8])) print(minimumSwaps([10, 4, 5, 3, 7]))
# fb phone interview 1 - donna # input: list of pairs of integers, for example [(1,2), (5,6), (7,3), ...] # input: a non-negative integer "K" # output: the "K" points from the input that are closest to the origin (0,0) # for example: if K=2, [(1,2), (7,3)] # first solution that I thought of right off the bat # time complexity: O(nlogn) because of the sorting def k_from_origins(coords, k): lenC = len(coords) if lenC < k: #edge case: if k is greater than the elements in the list return None # list stores tuples of the calculated distance and the original index that # the point was located in as (dist, index) distances = [] for i in range(lenC): (x, y) = coords[i] distance = sqrt(x^2 + y^2) distances.append((distance, i)) """ what this is doing is sorting the distances array using only the distance calculated and not the index """ distances = sorted(distances, lambda (d, ind): d) ret = [] #creates an array of just the k elements for j in range(k): (d, ind) = distances[j] ret.append(coords[ind]) return ret """ Interviewer then asks if there was a way for me to sort the coordinates using lambda and im a motherfucking dumbass for not realizing earlier because its like 2 lines of code lolol """ def k_from origin2(coords, k): """ The lambda is a sort function given to sorted which is used on each each element in coords to calc their distance and the sorted will sort the array using the distances """ coords = sorted(coords, lambda (x, y): sqrt(x^2 + y^2)) return coords[:k] #returns first k """ Interviewer says what if k is really small, are you going to sort each element in coords? At first I say you can use a min heap that has k elements so you can keep track of the minimum k elements but get confused and change that to an array. After being lost for like 10 minutes going in the wrong direction, I get to the conclusion of using a maxHeap (thx fb dude for not telling me I was going in the completely wrong direction) max Heap: root will have the greatest element and all its children will be less than it note: i didnt know the syntax for the heap class in python so I told him that and made up some random heap function names """ def k_from_origin(coords, k): maxHeap = maxHeap() #goes through the coordinate array and calculates the distance for i in range(len(coords)): (x, y) = coords[i] distance = sqrt(x^2 + y^2) # if the maxheap is not filled yet, insert the distance and index into it # this is kinda like the first method if maxHeap.size() < k: maxHeap.insert((distance, index)) else: # compare the distance to the root of the max heap and if it is less # it add it to the head and remove the root (python function should # automatically keep the heap invariant) if distance < maxHeap.top(): maxHeap.insert((distance, index)) maxHeap.deleteMax() listHeap = list(maxHeap) #changes the heap into a list # then you can go through it again like in the first function and get the # k elements that are in the heap according the index (didnt write this out) return Li
import string def idcheck(s): print "idcheck start!" letters = string.ascii_letters digits= string.digits s_l=len(s) if s_l >0 : if (s[0] in letters) == False and s[0] != "_": return False i=1 while i < s_l: if (s[0] in letters) == False and s[0] != '_' and (s[0] in dights) ==False: return False i += 1 return True if __name__ == "__main__" : while True: s=raw_input(">") if idcheck(s) : print s, ": is a id" else : print s, ": is not a id"
import turtle as t def rectangle(horizontal, vertical, color): t.pendown() t.pensize(1) t.color(color) t.begin_fill() for counter in range(1, 3): t.forward(horizontal) t.right(90) t.forward(vertical) t.right(90) t.end_fill() t.penup() def arm(color): t.pendown() t.begin_fill() t.color(color) t.forward(60) t.right(90) t.forward(50) t.right(90) t.forward(10) t.right(90) t.forward(40) t.left(90) t.forward(50) t.right(90) t.forward(10) t.end_fill() t.penup() t.setheading(0) t.speed('fastest') t.bgcolor('Dodger blue') t.shape('turtle') # feet t.goto(-100, -150) rectangle(50, 20, 'navy') t.goto(-30, -150) rectangle(50, 20, 'navy') t.goto(-25, -50) # legs rectangle(15, 100, 'turquoise') t.goto(-55, -50) rectangle(-15, 100, 'turquoise') t.goto(-90, 100) # body rectangle(100, 150, 'purple') # arms t.goto(-90, 80) t.setheading(135) arm('turquoise') t.goto(10, 80) t.setheading(315) arm('turquoise') #neck t.goto(-50, 120) rectangle(15, 20, 'navy') # head t.goto(-85, 170) rectangle(80, 50, 'green') # eyes t.goto(-60, 160) rectangle(30, 10, 'white') t.goto(-55, 155) rectangle(5, 5, 'black') t.goto(-40, 155) rectangle(5, 5, 'black') # mouth t.goto(-65, 135) rectangle(40, 5, 'black') t.hideturtle() t.mainloop()
import pygame # Globals size = width, height = 458, 458 rows = cols = 9 tileSize = width//rows white = (255,255,255) black = (0,0,0) grey = (220,220,220) #Function def backtrack(board, screen, animate): solved = False for row in range(9): for col in range(9): if board[row][col][1] == 0: for value in range(1,10): board[row][col][1] = value if(animate): draw_board(screen,board) validMove = validate(board,row,col) if validMove: solved = backtrack(board,screen,animate) if solved: return True board[row][col][1] = 0 return return True def validate(board,currRow,currCol): #validate row counter = 0 for value in board[currRow]: if board[currRow][currCol][1] == value[1]: counter += 1 if counter > 1: return False #validate col counter = 0 for row in board: if board[currRow][currCol][1] == row[currCol][1]: counter += 1 if counter > 1: return False #validate grid gridRow = int(currRow/3) * 3 gridCol = int(currCol/3) * 3 counter = 0 for row in range(gridRow, gridRow+3): for col in range(gridCol, gridCol+3): if board[currRow][currCol][1] == board[row][col][1]: counter += 1 if counter > 1: return False return True def initial_board(boardFile): with open(boardFile, "r") as gameFile: board = [] for line in gameFile: row = [] for value in line: editable = False if value != '\n': if value == '0': editable = True entry = [editable,int(value)] row.append(entry) board.append(row) return board def draw_board(screen, board): offset = 4 digitFont = pygame.font.SysFont(None, 50) #Draw White Background (workaround for blinking buttons) background = pygame.Rect(offset,offset,width,height) pygame.draw.rect(screen,white,background) #Draw Tiles for row in range(rows): for col in range(cols): rect = pygame.Rect(tileSize*col+offset, tileSize*row+offset, tileSize, tileSize) pygame.draw.rect(screen,grey,rect, 1) #Draw Grid for row in range (rows//3): row *=3 for col in range(cols//3): col*=3 rect = pygame.Rect(tileSize*col+offset, tileSize*row+offset, 3*tileSize, 3*tileSize) pygame.draw.rect(screen,black,rect,1) #Draw Numbers currRow = currCol = 0 for row in board: for value in row: if(value[1] != 0): digit = digitFont.render(str(value[1]),black,True) xPos = currCol*tileSize + tileSize//2 + offset - digit.get_rect().width//2 yPos = currRow*tileSize + tileSize//2 + offset - digit.get_rect().height//2 screen.blit(digit, (xPos,yPos)) currCol += 1 currRow += 1 currCol = 0 pygame.display.flip()
'''Задание1. Найти сумму и произведение цифр трехзначного числа, которое вводит пользователь. https://drive.google.com/file/d/1YlUtqLMn-ZPQXjRHXaQ0omqdbkv3rtnn/view?usp=sharing''' abc = int(input('Введите целое трехзначное число: ')) a = int(abc / 100) b = int((abc - (100*a)) / 10) c = int(abc - (a*100) - (b * 10)) s = a + b + c p = a * b * c print('Сумма трехзначного числа равна: ', s, 'Произведение равно : ', p) ''' задание 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. https://drive.google.com/file/d/1YlUtqLMn-ZPQXjRHXaQ0omqdbkv3rtnn/view?usp=sharing''' n = int(input('Введите номер буквы английского алфавита: ')) alphabet = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] l = alphabet[n] print(l) '''Задание 8: Определить, является ли год, который ввел пользователь, високосным или не високосным. https://drive.google.com/file/d/1YlUtqLMn-ZPQXjRHXaQ0omqdbkv3rtnn/view?usp=sharing''' year = int(input('Введите год: ')) if year % 4 != 0: print('не високосный год') elif year % 100 == 0: if year % 400 != 0: print('не високосный год') else: print('високосный год') else: print('високосный год') '''Задание 9. Вводятся три разных числа. Найти, какое из них является средним (больше одного, но меньше другого). https://drive.google.com/file/d/1YlUtqLMn-ZPQXjRHXaQ0omqdbkv3rtnn/view?usp=sharing''' print('Введите три разных целых числа') d = int(input('Первое число: ')) e = int(input('Второе число: ')) f = int(input('Третье число: ')) if e < d < f or f < d < e: print('Среднее число равно ', d) elif d < e < f or f < e < d: print('Среднее число равно ', e) else: print('Среднее число равно ', f)
import sys from random import randint from turtle import forward, left, speed speed('slowest') for idx, argument in enumerate(sys.stdin): if idx == 0: # In case of the first argument -the Python program name- do nothing in # this iteration, jump over it with `continue` continue turtle_steps = int(argument) forward(turtle_steps) random_angle = randint(45, 135) left(random_angle)
def tic_tac_toe(): board = [1, 2, 3, 11, 12, 13, 21, 22, 23, 4, 5, 6, 14, 15, 16, 24, 25, 26, 7, 8, 9, 17, 18, 19, 27, 28, 29, 31, 32, 33, 41, 42, 43, 51, 52, 53, 34, 35, 36, 44, 45, 46, 54, 55, 56, 37, 38, 39, 47, 48, 49, 57, 58, 59, 61, 62, 63, 71, 72, 73, 81, 82, 83, 64, 65, 66, 74, 75, 76, 84, 85, 86, 67, 68, 69, 77, 78, 79, 87, 88, 89] end = False win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)) def draw(): print(board[0], "|", board[1],"|", board[2], "|", board[3], "|",board[11],"|", board[12],"|",board[21], "|", board[22] ,"|", board[23], board[10]) print ("__________|______________|______________") print(board[9], "|", board[10], "|", board[11], "|", board[12], "|", board[13], "|", board[14], "|", board[15], "|", board[16], "|", board[17]) print ("__________|______________|______________") print(board[18],"|", board[19],"|", board[20], "|", board[21],"|", board[22],"|", board[23], "|", board[24],"|", board[25],"|", board[26]) print ("__________|______________|______________") print(board[27], "|", board[28],"|", board[29],"|", board[30], "|", board[31],"|", board[32], "|", board[33], "|", board[34],"|", board[35]) print ("__________|______________|______________") print(board[36],"|", board[37],"|", board[38], "|", board[39], "|", board[40],"|", board[41], "|", board[42], "|", board[43],"|", board[44]) print ("__________|______________|______________") print(board[45],"|", board[46],"|", board[47], "|", board[48], "|", board[49],"|", board[50], "|", board[51], "|", board[52],"|", board[53]) print ("__________|______________|______________") print(board[54], "|", board[55],"|", board[56],"|",board[57], "|",board[58],"|", board[59],"|",board[60], "|", board[61] ,"|", board[62]) print ("__________|______________|______________") print(board[63], "|", board[64], "|", board[65],"|", board[66], "|", board[67], "|", board[68], "|", board[69], "|", board[70], "|", board[71]) print ("__________|______________|______________") print(board[72],"|", board[73],"|", board[74], "|", board[75],"|", board[76],"|", board[77], "|", board[78],"|", board[79],"|", board[80]) print() def p1(): n = choose_number() if board[n] == "X" or board[n] == "O": print("\nYou can't go there. Try again") p1() else: board[n] = " X " def p2(): n = choose_number() if board[n] == "X" or board[n] == "O": print("\nYou can't go there. Try again") p2() else: board[n] = " O " def choose_number(): while True: while True: a = input() try: a = int(a) a -= 1 if a in range(0, 81): return a else: print("\nThat's not on the board. Try again") continue except ValueError: print("\nThat's not a number. Try again") continue def check_board(): count = 0 for a in win_commbinations: if board[a[0]] == board[a[1]] == board[a[2]] == "X": print("Player 1 Wins!\n") print("Congratulations!\n") return True if board[a[0]] == board[a[1]] == board[a[2]] == "O": print("Player 2 Wins!\n") print("Congratulations!\n") return True for a in range(9): if board[a] == "X" or board[a] == "O": count += 1 if count == 9: print("The game ends in a Tie\n") return True while not end: draw() end = check_board() if end == True: break print("Player 1 choose where to place a cross") p1() print() draw() end = check_board() if end == True: break print("Player 2 choose where to place a nought") p2() print() if input("Play again (y/n)\n") == "y": print() tic_tac_toe() tic_tac_toe()
def sort(values): for m range(len(values)): for n in range(m, len(values)): if (values[m] > values[n]): temp = values[m] values[m] = values[n] values[n] = temp y = raw_input().rstrip() yList = list(y) sort(yList) print("".join(yList))
candyInStore = ["Snickers", "Kit Kat", "Sour Patch Kids", "Juicy Fruit", "Sweedish Fish", "Skittles", "Hershey Bar", "Skittles", "Starbursts", "M&Ms"] allowance = 5 selectedCandy = [] #for i in range(len(candyInStore)): #print("[" + str(i) + "] " + candyInStore[i]) for candy in candyInStore: print ("[" + str(candyInStore.index(candy)) + "] " + candy) while allowance > 0: candyIndex = int(input ("Which candy would you like to take home?")) selectedCandy.append(candyInStore[candyIndex]) allowance = allowance - 1 print("You are taking home: ") for j in range(len(selectedCandy)): print(selectedCandy[j])
fname = input("Enter file name: ") fh = open(fname) #fh = open('romeo.txt') lst = list() lst2 = [] for line in fh: #print(line.rstrip()) lst += line.split() #print(sorted(lst)) for item in lst: if item not in lst2: lst2.append(item) print(sorted(lst2))
import random from functools import wraps import csv class Deck(): def __init__(self): """ This should populate our card deck""" suits = ["Hearts", "Diamonds", "Clubs", "Spades"] values = ["A" ,"2", "3", "4","5", "6", "7", "8", "9", "10", "J", "Q", "K"] self.card_list = [] for suit in suits: for value in values: self.card_list.append(Card(suit,value)) def __iter__(self): return iter(self.card_list) @classmethod def deal(cls,card_list): """ This function takes a list of 52 cards i.e. card_list as input and returns the last card. It also removes the last card from the deck""" if len(card_list) == 0: return "Deck is empty. Start a new game?" return card_list.pop() @classmethod def shuffle(cls,card_list): """ This function re-arranges the deck randomly""" return card_list.random.shuffle() def save_deck(self): with open("deck.csv", "a") as deck_csv: data_writer=csv.writer(deck_csv, delimiter = ",") data_writer.writerow(["SUIT", "VALUE"]) for card in self.card_list: print(card) data_writer.writerow([card.suit, card.value]) def load_deck(self): # Load your deck from a CSV file # take the deck from CSV # then replace the current deck # they should be the same and in the same order with open("deck.csv", "r") as deck_csv: data_reader = csv.reader(deck_csv, delimiter =",") self.card_list # You should be able to kill your program after doing a save. Start it up again and do a load and have the same deck of cards in the same order class Card(): def __init__(self,suit,value): self.suit = suit self.value = value def __str__(self): return "{} {}".format(self.suit, self.value) def __repr__(self): return "{} {}".format(self.suit, self.value) # Create a decorator called `log` that will print the name of the function being invoked and the arguments to that function def log(func): @wraps(func) def inner(*args): print(func.__name__ + "was called with the following arguments:" + locals(["args"])) with open("deck.log", "w") as file: file.write(func.__name__ + "was called with the following arguments:" + locals(["args"])) return func(*args) return inner @log def add(a,b): return a+b new_deck = Deck() # for card in new_deck: # print(card) new_deck.save_deck() new_deck.load_deck()
def flip(x): if x == 0: return 1 if x == 1: return 0 def Scramble(binary): msgBinary = binary key = "e81e38192bfd4B7e" msgBinaryList = list(msgBinary) keyList = list(key) numRange = range(0,16) #Get the numeric values of the key for x in numRange: keyList[x] = int(keyList[x],16) for x in keyList: #Find the bit that corresponds to the key. a = msgBinaryList[x] b = flip(int(a)) msgBinaryList[x] = b return msgBinaryList
#This contains all the functions relating to the binary decoding of a file def splitString(numberString): tempString = str(numberString) outStringPiv0 = numberString[:4] outStringPiv1 = numberString[4:] outString0 = outStringPiv0[:2] outString1 = outStringPiv0[2:] outString2 = outStringPiv1[:2] outString3 = outStringPiv1[2:] outIntString0 = int(outString0) outIntString1 = int(outString1) outIntString2 = int(outString2) outIntString3 = int(outString3) outList = [] outList.append(outIntString0) outList.append(outIntString1) outList.append(outIntString2) outList.append(outIntString3) return outList def BinaryList(numericlist): binarylist = [] binarylist.append(RetrieveBits(numericlist[0])) binarylist.append(RetrieveBits(numericlist[1])) binarylist.append(RetrieveBits(numericlist[2])) binarylist.append(RetrieveBits(numericlist[3])) return binarylist def RetrieveBits(integer): binarystring = bin(integer)[2:] binarylist = list(binarystring) while len(binarylist) < 4: binarylist.insert(0, '0') binarystring = "".join(binarylist) return binarystring def GetBitDict(binary): binarystring = "".join(binarylist) binarydict[0] = binarystring[0:4] binarydict[1] = binarystring[4:8] binarydict[2] = binarystring[8:12] binarydict[3] = binarystring[12:16] return binarydict def GetBitString(binarylist): return "".join(binarylist)
i=int(raw_input()) if i<0: print "Negative" elif i>0: print "Positive" else: print "Zero"
import time import datetime ''' input: Epoch format date processing: convert Epoch format date to human readable time. Output: human readable date and time. ''' def epotchToDateTime(data): return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data)) ''' input: human readable date and time. processing: convert human readable time to Epoch format date. Output: Epoch format date. ''' def dateTimeToEpotch(data): date = data.split(':') day = date[0].split('-') return int(datetime.datetime(int(day[0]), int(day[1]), int(day[2]), int(date[1]), int(date[2]), int(date[3])).timestamp()) def dateTimeToEpotchFilter(date, time): date = date.split('-') time = time.split(':') if len(time) == 1: return int(datetime.datetime(int(date[0]), int(date[1]), int(date[2])).timestamp()) return int(datetime.datetime(int(date[0]), int(date[1]), int(date[2]), int(time[0]), int(time[1])).timestamp())
from copy import deepcopy from queue import Queue import time class Problem(object): def __init__(self, initial, goal): self.initial = initial self.goal = goal def actions(self, state): #goes through actions of the current node being observed to generate its children action_list = [] for i in range(0, 3): for j in range(0, 3): if (state[i].peek() > 0 and state[j].peek() == 0): action_list.append([i, j]) elif (state[i].peek() < state[j].peek()) and state[i].peek() > 0: action_list.append([i, j]) return action_list def result(self, state, action): #returns the state of the node after a given action is implemented on the current state of the node state_copy = deepcopy(state) state_copy[action[1]].push(state_copy[action[0]].pop()) return state_copy def BBFS_goal_test(self, initial, goal): #used to check and see if the initial node state is the same as the goal node state for the bidirectional search if initial[0].stack == goal[0].stack and initial[1].stack == goal[1].stack and initial[2].stack == goal[2].stack: return True return False def BFS_goal_test(self, state): #used in the breadth-first-search to determine whether the current node state is the same as the goal node state if state[0].stack == self.goal[0].stack and state[1].stack == self.goal[1].stack and state[2].stack == self.goal[2].stack: return True return False class Node(object): #node in a search tree. Contains the current state of the tree and connects the tree through keeping track of its children/parent def __init__(self, state, parent=None): self.state = state self.parent = parent def expand(self, problem): # List the nodes reachable in one step from this node. return [self.child_node(problem, action) for action in problem.actions(self.state)] def child_node(self, problem, action): #returns the child node of the current node after a given action next = problem.result(self.state, action) return Node(next, self) def compare_node(self, node): #used to compare the current node to another node to see if they are equal if (self.state[0].same_stack(node.state[0])) and (self.state[1].same_stack(node.state[1])) and (self.state[2].same_stack(node.state[2])): return True return False def compare_state(self, state): #used to compare the state of the current node to the state of another node to see if they are equal if (self.state[0].same_stack(state[0])) and (self.state[1].same_stack(state[1])) and (self.state[2].same_stack(state[2])): return True return False def compare_node_list(self, list): #used to compare the current node to a list of other nodes(the frontier) for x in list: if self.compare_node(x): return True return False def compare_state_list(self, list): #used to compare the state of the current node to a list of states of other nodes(the explored list) for x in list: if self.compare_state(x): return True return False class Stack: #Created a stack data structure to more easily manipulate moves def __init__(self, stack): self.stack = stack def pop(self): #returns first item of list and removes it if self.stack: return self.stack.pop(0) def push(self, x): #inserts element into the front of list self.stack.insert(0, x) def peek(self): #returns the first item of the list but does not remove it like pop if self.stack: return self.stack[0] return 0 def same_stack(self, stack): #checks if two stacks are the same if self.stack == stack.stack: return True return False def bidirectional_breadth_first_search(problem): #essentially the same as breadth first search except we need to make two of everything. One for the initial start and one for the goal start. start_time = time.time() #used to measure total time that this function takes start_node = Node(problem.initial) #initial node from the starting state goal_node = Node(problem.goal) #initial node starting from the goal state if problem.BBFS_goal_test(start_node.state, goal_node.state): print("--- %s seconds ---" % (time.time() - start_time)) return start_node start_frontier = [] goal_frontier = [] start_frontier.append(start_node) goal_frontier.append(goal_node) start_explored = [] goal_explored = [] while start_frontier or goal_frontier: start_node = start_frontier.pop() goal_node = goal_frontier.pop() start_explored.append(start_node.state) goal_explored.append(goal_node.state) for child in start_node.expand(problem): #goes through all children of current forward searching node and adds them to the forward frontier if they are not already explored or in the frontier if not(child.compare_state_list(start_explored)) and not(child.compare_node_list(start_frontier)): if child.compare_node_list(goal_frontier): #checks to see if the current forward child node is in the backward frontier which means a solution was found print(len(start_explored)) print(len(goal_explored)) print("--- %s seconds ---" % (time.time() - start_time)) return child start_frontier.append(child) for child in goal_node.expand(problem): #goes through all children of current backward searching node and adds them to the backward frontier if they are not already explored or in the frontier if not(child.compare_state_list(goal_explored)) and not(child.compare_node_list(goal_frontier)): if child.compare_node_list(start_frontier): #checks to see if the current backward child node is in the forward frontier which means a solution was found print(len(start_explored)) print(len(goal_explored)) print("--- %s seconds ---" % (time.time() - start_time)) return child goal_frontier.append(child) return None def breadth_first_search(problem): start_time = time.time() #used to measure total time that this function takes node = Node(problem.initial) if problem.BFS_goal_test(node.state): #checks to see if the initial node happens to be the goal node print("--- %s seconds ---" % (time.time() - start_time)) return node frontier = [] #list to store children nodes. determines the order in which the tree is traversed frontier.append(node) explored = [] #list to keep track of states that have already been explored while frontier: node = frontier.pop() explored.append(node.state) for child in node.expand(problem): #goes through all children of current node and adds them to the frontier if they are not already explored or in the frontier if not(child.compare_state_list(explored)) and not(child.compare_node_list(frontier)): if problem.BFS_goal_test(child.state): #checks if the current child node is the same as the goal node print(len(explored)) print("--- %s seconds ---" % (time.time() - start_time)) return child frontier.append(child) return None #test cases one_ring = Problem([Stack([1]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1])]) two_rings = Problem([Stack([1, 2]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2])]) three_rings = Problem([Stack([1, 2, 3]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3])]) four_rings = Problem([Stack([1, 2, 3, 4]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4])]) five_rings = Problem([Stack([1, 2, 3, 4, 5]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4, 5])]) six_rings = Problem([Stack([1, 2, 3, 4, 5, 6]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4, 5, 6])]) seven_rings = Problem([Stack([1, 2, 3, 4, 5, 6, 7]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4, 5, 6, 7])]) eight_rings = Problem([Stack([1, 2, 3, 4, 5, 6, 7, 8]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4, 5, 6, 7, 8])]) nine_rings = Problem([Stack([1, 2, 3, 4, 5, 6, 7, 8, 9]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4, 5, 6, 7, 8, 9])]) ten_rings = Problem([Stack([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), Stack([]), Stack([])], [Stack([]), Stack([]), Stack([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])]) print("BFS 1"), breadth_first_search(one_ring) print("BBFS 1"), bidirectional_breadth_first_search(one_ring) print("BFS 2"), breadth_first_search(two_rings) print("BBFS 2"), bidirectional_breadth_first_search(two_rings) print("BFS 3"), breadth_first_search(three_rings) print("BBFS 3"), bidirectional_breadth_first_search(three_rings) print("BFS 4"), breadth_first_search(four_rings) print("BBFS 4"), bidirectional_breadth_first_search(four_rings) print("BFS 5"), breadth_first_search(five_rings) print("BBFS 5"), bidirectional_breadth_first_search(five_rings) print("BFS 6"), breadth_first_search(six_rings) print("BBFS 6"), bidirectional_breadth_first_search(six_rings) print("BFS 7"), breadth_first_search(seven_rings) print("BBFS 7"), bidirectional_breadth_first_search(seven_rings) print("BFS 8"), breadth_first_search(eight_rings) print("BBFS 8"), bidirectional_breadth_first_search(eight_rings) print("BFS 9"), breadth_first_search(nine_rings) print("BBFS 9"), bidirectional_breadth_first_search(nine_rings) #print("BFS 10"), #breadth_first_search(ten_rings) #print("BBFS 10"), #bidirectional_breadth_first_search(ten_rings)
#Exercise 7 - Get first list of numbers and create a second list and store only even numbers from first list #Create a list with random numbers a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] #Create another list with only even numbers taken from list 1 b = [number for number in a if number % 2 == 0] print(b)
#Get a string as input from user and reverse the string and store it in different variable def reverse_v4(x): y = x.split() y.reverse() return " ".join(y) #Get user input test1 = input("Enter a sentence: ") #Print test result print (reverse_v4(test1))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: if not root: return [] allPaths = [] def traverseAndAccumulate(node, currPath): nonlocal allPaths if node.left == None and node.right == None: allPaths.append("->".join(currPath+[str(node.val)])) return if node.left != None: traverseAndAccumulate(node.left, currPath+[str(node.val)]) if node.right != None: traverseAndAccumulate(node.right, currPath+[str(node.val)]) traverseAndAccumulate(root, []) return allPaths
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: TreeNode) -> int: longestDiameter = 0 def depth(node): if not node: return 0 nonlocal longestDiameter leftDepth = depth(node.left) rightDepth = depth(node.right) longestDiameter = max(longestDiameter, leftDepth + rightDepth) return 1 + max(leftDepth, rightDepth) depth(root) return longestDiameter
class Solution: def maxProfit(self, prices: List[int]) -> int: totProfit = 0 for i in range(1, len(prices)): if prices[i-1] < prices[i]: totProfit += prices[i] - prices[i - 1] return totProfit # 1 3 4 5 6 7 """ for each buying price find the max amount of profit you can have. add that profit to totprofit and return total profit O(n*n) greedy strategy: buy a share and sell it as soon as you get best price """