text
stringlengths
37
1.41M
_dict1 = { 1: "one", "two": 2 } _list1 = [101, False, "Hello", [3, 4, 5], _dict1] print(_list1) print(_list1[0]) print(_list1[1]) print(_list1[2]) print(_list1[3]) print(_list1[4]) a = "123.456" b = float(a) print(type(b), b) c = '{}{}{}'.format(a[0], a[1], a[2]) c = int(c) print(type(c), c)
from data_structures.graph.graph import Graph, Vertex def get_edges(route_map: Graph, itinerary: list) -> tuple: """Determine if the given itinerary is possible with direct flights and how much it will cost Args: route_map (Graph): Map of the existing cities itinerary (list): List of cities Returns: tuple: Wheter or not the trip is possible with direct fligts only, total trip price """ def get_node_reference(city: any) -> Vertex: """Get a node reference that matches provided value Args: city (any): Value to look for Returns: Vertex: Reference to the vertex """ for node in route_map.get_nodes(): if node.val == city: return node return None if len(itinerary) < 2: raise ValueError('You must provide at least 2 cities') possible, price = True, 0 start_city = get_node_reference(itinerary[0]) for i in range(1, len(itinerary)): end_city = itinerary[i] connections = route_map.get_neighbors(start_city) for connection in connections: if connection['vertex'].val == end_city: price += connection['weight'] start_city = get_node_reference(end_city) possible = True break else: possible = False if not possible: return (False, f'${0}') return (True, f'${price}')
def binary_search(arr: list, target: int) -> int: """Uses binary search algorithm to search the given array for a given element. Returns index of the element if found and -1 otherwise Args: arr (list): Sorted array target (int): Element to look for in the given array Returns: int: Index of the element if found, -1 otherwise """ min_idx, max_idx = 0, len(arr) - 1 while min_idx <= max_idx: mid_idx = min_idx + (max_idx - min_idx) // 2 if arr[mid_idx] == target: return mid_idx elif arr[mid_idx] > target: max_idx = mid_idx - 1 else: min_idx = mid_idx + 1 return -1
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: values = [] def traverse(head: ListNode): nonlocal values while head: values.append(head.val) head = head.next for l in lists: traverse(l) values.sort() dummy = curr = ListNode() for val in values: curr.next = ListNode(val) curr = curr.next return dummy.next
from data_structures.stacks_and_queues.stacks_and_queues import Queue def tree_intersection(bt1: object, bt2: object) -> set: output = set() q1 = q2 = Queue() if bt1.root and bt2.root: q1.enqueue(bt1.root) q2.enqueue(bt2.root) while not (q1.is_empty() and q2.is_empty()): el1, el2 = q1.dequeue(), q2.dequeue() if el1.val == el2.val: output.add(el1.val) if el1.left and el2.left: q1.enqueue(el1.left) q2.enqueue(el2.left) if el1.right and el2.right: q1.enqueue(el1.right) q2.enqueue(el2.right) return output
import plotly.express as px import csv with open('cups of coffee vs hours of sleep.csv', newline='') as f: df=csv.DictReader(f) fig=px.scatter(df, x="sleep in hours", y="Coffee in ml") fig.show()
import time def timerfunc(func): """ A timer decorator """ def function_timer(*args, **kwargs): """ A nested function for timing other functions """ start = time.time() value = func(*args, **kwargs) end = time.time() runtime = end - start msg = "{time} completed for {func} of {cls} took seconds to complete" print(msg.format(func=func.__name__, cls=func.__module__, time=runtime)) return value return function_timer
from io import open """ archivo = open("/home/fhc/Desktop/Software Engineering Career/0. Python desde 0 a Experto/Avanzado/0. TratamientoDeErrores/archivo2.txt", "w") frase = input("Ingrese por favor el contenido del archivo: -->") archivo.write(frase) archivo.close() archivo = open("/home/fhc/Desktop/Software Engineering Career/0. Python desde 0 a Experto/Avanzado/0. TratamientoDeErrores/archivo2.txt", "r") texto = archivo.readlines() archivo.close() print(texto) archivo = open("/home/fhc/Desktop/Software Engineering Career/0. Python desde 0 a Experto/Avanzado/0. TratamientoDeErrores/archivo2.txt", "a") archivo.write("\nawa") archivo.close() """ archivo = open("/home/fhc/Desktop/Software Engineering Career/0. Python desde 0 a Experto/Avanzado/0. TratamientoDeErrores/archivo2.txt", "r") texto = archivo.read() #Se puede ingresar un limitante en el read print(texto) archivo.seek(0) print(texto)
def evaluacionEdad(edad): if edad<0: raise TypeError("Ingrese una edad valida") #Error de tipeo if edad<20: return "Eres muy joven" elif edad<40: return "Eres joven" elif edad<65: return "Eres maduro" elif edad<100: return "Too old..." edadD = int(input("Ingres su edad: -->")) print(evaluacionEdad(edadD))
# Uses python3 import sys def gcd_naive(a, b): current_gcd = 1 for d in range(2, min(a, b) + 1): if a % d == 0 and b % d == 0: if d > current_gcd: current_gcd = d return current_gcd def gcd(a, b): result = 1 if max(a,b) % min(a,b) != 0: return gcd(b%a, a%b) result = min(a, b) return result a, b = map(int, input().split()) print(gcd(a, b))
#!/usr/bin/python def outlierCleaner(predictions, ages, net_worths): """ Clean away the 10% of points that have the largest residual errors (difference between the prediction and the actual net worth). Return a list of tuples named cleaned_data where each tuple is of the form (age, net_worth, error). """ cleaned_data = [] ### your code goes here for prediction, age, net_worth in zip(predictions, ages, net_worths): error = prediction - net_worth tu = (age, net_worth, error) if abs(error) < 80: cleaned_data.append(tu) # print (tu) print(len(cleaned_data)) return cleaned_data
#리스트 생성 d = [] #리스트에 입력받기(9개) for i in range(9): d.append(int(input())) #최댓값 구하기 print(max(d)) #오프셋은 0부터 시작하므로 1 더해준다 print(d.index(max(d))+1)
my_list = [1, 2, 3, 4, 5, 6, 7] first_element = my_list[0] last_element = my_list[-1] new_list = [] new_list.append(first_element) new_list.append(last_element) print('first and last:', new_list)
import sys import csv def inputs_checker(): """Check command line arguments and if all are correct return them""" try: csv_file_path = sys.argv[1] velocity = int(sys.argv[2]) if not csv_file_path.endswith('.csv'): print("WARNING! First argument needs to be a .csv file.") sys.exit() f = open(csv_file_path) f.close() except IndexError: print("WARNING! There have to be exactly 2 command line arguments.") sys.exit() except ValueError: print("WARNING! Second argument (team velocity) has to be an integer.") sys.exit() except FileNotFoundError: print("WARNING! There is no such file or directory '{}'.".format(csv_file_path)) sys.exit() else: cli_args = [csv_file_path, velocity] return cli_args def sorted_tasks_list_creator(arguments): """Take a file path and team velocity from a command line arguments and return sorted list of tasks.""" csv_file_path = arguments[0] velocity = arguments[1] with open(csv_file_path) as csv_file: csv_reader = csv.DictReader(csv_file) csv_content_list = [] for row in csv_reader: task_id = int(row['task_id']) story_points = int(row['story_points']) ksp = int(row['KSP']) profit_index = ksp / story_points if story_points <= velocity: csv_content_list.append([task_id, story_points, ksp, profit_index]) csv_content_list.sort(key=lambda x: (x[3], x[1]), reverse=True) return csv_content_list def task_chooser(tasks_list, arguments): """Take a sorted tasks list and team velocity, choose most profitable tasks that don't exceed velocity value and write to STDOUT their indexes""" velocity = arguments[1] total_story_points = 0 chosen_tasks = [] for task in tasks_list: if total_story_points == velocity: break elif total_story_points + task[1] <= velocity: total_story_points += task[1] chosen_tasks.append(task[0]) chosen_tasks.sort() chosen_tasks = [str(task) for task in chosen_tasks] sys.stdout.write(', '.join(chosen_tasks) + '\n') if __name__ == '__main__': args = inputs_checker() csv_sorted_list = sorted_tasks_list_creator(args) task_chooser(csv_sorted_list, args)
from __future__ import absolute_import from __future__ import division from __future__ import print_function # Imports import numpy as np import tensorflow as tf tf.logging.set_verbosity(tf.logging.INFO) # Application logic # https://www.tensorflow.org/tutorials/layers # The MNIST dataset comprises 60,000 training examples and 10,000 test examples of the handwritten digits 0–9, # formatted as 28x28-pixel monochrome images. Use layers to build a convolutional neural network model to # recognize the handwritten digits in the MNIST data set. def cnn_model_fn(features, labels, mode): """Model function for CNN""" # Input layer # Convert feature map to shape: # batch_size = -1 => dimension dynamically computed based on # of input values in features["x"] # image_width and image_height = 28x28 pixel images # channels = 1 => 3 for red-green-blue, 1 for monochrome input_layer = tf.reshape(features["x"], [-1, 28, 28, 1]) # Convolution layer #1 # Apply 32 5x5 filters to the input layer with a ReLU activation function, # using conv2d() to create this layer # kernel_size => dimension of the filters as [width, height] # padding = valid/same => output tensor should have the same width and height as the input ten%Ssor conv1 = tf.layers.conv2d( inputs=input_layer, filters=32, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling layer #1 # Connect first pooling layer to the created convolutional layer # Perform max pooling with a 2x2 filter and stride of 2 using max_pooling2d() # pool_size => size of the max pooling filter as [width, height] # strides => size of the strides, subregions extracted bt the filter should separate by 2 pixels in both width and height dimensions pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2) # Convolution layer #2 # Connect a second convolutional layer to the CNN: 64 5x5 filters with ReLU activation # Takes the output tensor of the first pooling layer as input conv2 = tf.layers.conv2d( inputs=pool1, filters=64, kernel_size=[5, 5], padding="same", activation=tf.nn.relu) # Pooling layer #2 # Connect a second pooling layer to the CNN: 2x2 max pooling filter with a stride of 2 # Takes the output tensor of the second convolutional layer as input pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2) # Dense layer # Add a dense layer with 1024 neurons and ReLU activation to the CNN # to perform classification on features extracted by the convolution and pooling layers. # Flatten feature map to shape [batch_size, features] to the tensor has only 2 dimensions # Each example has 7 (pool2 width) * 7 (pool2 height) * 64 (pool2 channels) features pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) # Connect the dense layer # units => numbers of neurons in the dense layer dense = tf.layers.dense( inputs=pool2_flat, units=1024, activation=tf.nn.relu) # Apply dropout regularization to the dense layer to improve the results of the model # rate => dropout rate, 40% of the elements will be randomly dropped out during training # training => dropout will be performend only in TRAIN mode dropout = tf.layers.dropout( inputs=dense, rate=0.4, training=mode == tf.estimator.ModeKeys.TRAIN) # Logits layer # Create dense layer with 10 neurons (one for each target class 0-9) with default linear activation # Returns the raw values for the predictions logits = tf.layers.dense(inputs=dropout, units=10) # Convert the raw values into two different formats that the model function can return # predicted class for each example = 0-9 # probabilities for each target class for each example predictions = { # Generate predictions (for PREDICT and EVAL mode) # Predicted class is the element in the corresponding row of the logits tensor with the highest raw value # axis => axis of the input tensor along which to find the greatest value "classes": tf.argmax(input=logits, axis=1), # Add `softmax_tensor` to the graph. It is used for PREDICT and by the `logging_hook`. "probabilities": tf.nn.softmax(logits, name="softmax_tensor") } # Compile the predictions into a dict and return an EstimatorSpec object if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions) # Calculate Loss (for both TRAIN and EVAL modes) # For training and evaluation, measure how closely the model's predictions match the target classes loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits) # Configure the Training Op (for TRAIN mode) # Configure the model to optimize the loss value during training with learning rate and optimization algorithm if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001) train_op = optimizer.minimize( loss=loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode=mode, loss=loss, train_op=train_op) # Add evaluation metrics (for EVAL mode) # Add accuracy metric to the model eval_metric_ops = { "accuracy": tf.metrics.accuracy( labels=labels, predictions=predictions["classes"])} return tf.estimator.EstimatorSpec(mode=mode, loss=loss, eval_metric_ops=eval_metric_ops) def main(unused_argv): # Load training and eval data mnist = tf.contrib.learn.datasets.load_dataset("mnist") # Training feature data (the raw pixel values for 55,000 images of hand-drawn digits) train_data = mnist.train.images # Returns np.array # Training labels (the corresponding value from 0–9 for each image) trains_labels = np.asarray(mnist.train.labels, dtype=np.int32) # Evaluation feature data (10,000 images) eval_data = mnist.test.images # Returns np.array # Evaluation labels eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) # Create the Estimator # model_fn => the model function to use for training, evaluation and prediction # model_dir => directory where the model data (checkpoints) will be saved mnist_classifier = tf.estimator.Estimator( model_fn=cnn_model_fn, model_dir="/tmp/mnist_convnet_model") # Set up logging for predictions # CNNs can take some time to train, log the probability values from the softmax layer # of the CNN to track progress during training tensors_to_log = {"probabilities": "softmax_tensor"} # tensors => dict of tensors we want to log # every_n_iter => probabilities logged after every 50 steps of training logging_hook = tf.train.LoggingTensorHook( tensors=tensors_to_log, every_n_iter=50) # Train the model # x => training feature data # y => training labels # batch_size => the model will train on minibatches of 100 examples at each step # num_epoch => the model will train until the specifid steps is reached # shuffle => shuffle the training data train_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": train_data}, y=trains_labels, batch_size=100, num_epochs=None, shuffle=True) # steps => the model will train for 20000 steps total # hooks => trigger the logging hook during training mnist_classifier.train( input_fn=train_input_fn, steps=20000, hooks=[logging_hook]) # Evaluate the model and print results # Determine the accuracy on the MNIST test set # num_epochs => the model evaluates the metrics over one epoch of data and returns the result # shuffle => iterate through the data sequentially eval_input_fn = tf.estimator.inputs.numpy_input_fn( x={"x": eval_data}, y=eval_labels, num_epochs=1, shuffle=False) eval_results = mnist_classifier.evaluate(input_fn=eval_input_fn) print(eval_results) if __name__ == "__main__": tf.app.run()
"""contains every function needed to get the data from the database according to the user's choices""" from constants import * def categories_display(cursor): """displays categories and returns the user's choice""" user_input = False while not user_input: # until the user chooses a category print("Trouver un substitut") print("\n") print("Sélectionnez la catégorie :") print("\n") get_categories = "SELECT name FROM categories" # sql request to get the categories names cursor.execute(get_categories) for idx, category in enumerate(cursor, 1): print(idx, "-", category) print("\n") try: choice = int(input()) if choice <= 0 or choice > CATEGORIES_NB: # if user's choice is not valid print("Choix invalide") else: user_input = True return choice except ValueError: continue def products_display(cursor, category_choice): """displays the products for the chosen category and returns the user's choice""" user_input = False while not user_input: # until the user chooses a product print("\n") print("Sélectionnez l'aliment") get_products = ("SELECT name, p_id FROM products " "WHERE category_id = %d ") % category_choice # sql request to get the products names and ids from the chosen category cursor.execute(get_products) idx = 0 for idx, (name, p_id) in enumerate(cursor, 1): print(p_id, "-", name) idx = p_id print("\n") try: choice = int(input()) if choice <= 0 or choice > idx: # if user's choice is not valid print("Choix invalide") else: user_input = True return choice except ValueError: continue def item_display(cursor, connection, product_choice): """displays the chosen product's details and call the get_substitute function if one can be found""" loop_on = True while loop_on: # until the user chooses to return to the menu print("\n") print("Voici les détails de l'aliment choisi :") get_item = ("SELECT name, url, score, category_id FROM products " "WHERE p_id = %d ") % product_choice # sql request to get the details on the chosen product cursor.execute(get_item) for name, url, score, category_id in cursor: print("Nom du produit : ", name, "\n", "Lien vers la page produit : ", url, "\n", "Nutriscore : ", SCORES[score - 1]) if score != 1: # a substitute can be found only # if the product's nutrition score isn't already the lowest loop_on = get_substitute(cursor, connection, score, category_id, product_choice) # gets False when user wants to return to menu else: print("\n Ce produit n'a pas de substitut") print("Appuyez sur 'E' pour retourner au menu") key = input() if key == 'E': loop_on = False def substitute_details(choice, cursor, connection): """displays the chosen substitute details and allow to unsave it""" print("Voici les détails du substitut choisi") get_selection = ("SELECT name, url, score, category_id FROM products " "WHERE p_id = %d ") % choice cursor.execute(get_selection) for name, url, score, category_id in cursor: print("Nom du produit : ", name, "\n", "Lien vers la page produit : ", url, "\n", "Nutriscore : ", SCORES[score - 1], "\n", "Catégorie : ", CATEGORIES_NAMES_URL[category_id - 1]) print( "Appuyez sur 'S' si vous voulez retirer ce produit " "de vos aliments substitués ou sur 'E' pour retourner au menu") key = input() if key == 'S': delete_substitute = ("UPDATE products SET saved = '0'" "WHERE p_id = %d ") % choice # sql request to set back the saved column to '0' cursor.execute(delete_substitute) connection.commit() if key == 'E': return False def substitutes_display(cursor, connection): """displays all the saved substitutes if any and calls the substitute_details function if the user chooses one to get more info on it""" loop_on = True while loop_on: # until the user chooses to return to the menu print("Mes aliments substitués") get_substitutes = ("SELECT name, p_id FROM products " "WHERE saved = '1'") cursor.execute(get_substitutes) idx = 0 s_id = 0 for idx, (name, s_id) in enumerate(cursor, 1): print(s_id, "-", name) if idx == 0: # if the cursor was empty # (meaning there was no product where the column saved equaled '1') print("Vous n'avez enregistré aucun substitut") print("Appuyez sur 'E' pour retourner au menu") key = input() if key == 'E': loop_on = False else: # if there are saved substitutes print("\n") print("Sélectionnez un substitut") try: choice = int(input()) if choice <= 0 or choice > s_id: # if user's choice is not valid print("Choix invalide") else: loop_on = substitute_details(choice, cursor, connection) # displays the substitute's details # and returns False when user chooses to return to menu except ValueError: continue print("\n") connection.commit() def get_substitute(cursor, connection, score, category_id, product_choice): """gets a substitute for the chosen product""" print("\n") print("Voici un substitut pour cet aliment :") substitute_request = ("SELECT name, url, score, saved, category_id, " "p_id FROM products " "WHERE score < %d AND p_id != %d" " AND category_id = %d " "ORDER BY RAND() LIMIT 1") % ( score, product_choice, category_id) # sql request to select a random product from the same category # and that has a lower nutrition score cursor.execute(substitute_request) idx = 0 for idx, (name, url, score, saved, category_id, s_id) \ in enumerate(cursor, 1): print("Nom du produit : ", name, "\n", "Lien vers la page produit : ", url, "\n", "Nutriscore : ", SCORES[int(score) - 1], "\n", "Catégorie : ", CATEGORIES_NAMES_URL[int(category_id) - 1]) if saved == 1: # if the substitute displayed has already been saved print("Vous avez déjà enregistré ce substitut") print("Appuyez sur 'E' pour retourner au menu") key = input() if key == 'E': return False elif saved != 1: print("\n") print( "Appuyez sur 'S' pour sauvegarder cet aliment " "ou sur 'E' pour retourner au menu") key = input() if key == 'S': save_substitute = ("UPDATE products SET saved = '1'" "WHERE p_id = %d ") % s_id # sql request to set the saved column to '1' cursor.execute(save_substitute) connection.commit() if key == 'E': return False if idx == 0: # if the cursor was empty print("Ce produit n'a pas de substitut") def replace_product(cursor, connection): """calls every function needed to get a substitute for a chosen product in a chosen category""" loop_on = True while loop_on: choice = categories_display(cursor) choice = products_display(cursor, choice) item_display(cursor, connection, choice) loop_on = False
elements = ['Adam', 'Alicja', 'Olaf', 'Elżbieta'] for x in elements: print(x) for x in range(2,5): print(x) for x in range(len(elements)): print(x, elements[x]) print(range(6), type(range(6))) my_range = list(range(6)) print(my_range, type(my_range)) cond = True i =1 while cond: print(cond) # i++ nie ma inkrementacji w pythonie i+=1 if i>3: cond = False #elif warunek: else: print("dalej") mapa = { 2 : "Alabama", 'imie': 'Ala', 'wiek':33 } for index in mapa.keys(): print(index, '->', mapa[index]) zbior = {'Ala', "Alan", "Ala", "Tomasz"} print(zbior, type(zbior)) # slices print(elements) el = elements[1:3] print(el) # slice tylko początek print( elements[2:] ) # slice tylko koniec print( elements[:3] ) print( elements[:-2] ) #-2 drugi element od końca tab = [ [1,3] , [6,2.4], [3, 12], [33,7.5] ] print(tab[2][1]) #możliwe zadania #zapelnić tablice 20 wartościami losowymi #a) znaleźć max, min, średnią #b) ręcznie posortować #zapełnić tablicę 10 słowami #a) posortować alfabetycznie #a2) co z językiem polskim ??
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello, world!" @app.route("/jack") def david(): return "Hello, Jack!" @app.route("/<string:name>") def hello(name): name1 = "" names = name.split(" ") for name in names: name1 += name.capitalize() + " " name1 = name1.strip() return f"Hello, {name1}!"
from scipy import integrate def f(x,y): return x*y # Maybe default return to 1 for triple integration(cartesian) def bounds_y(): # args are what function is in terms of return [0, 0.5] def bounds_x(y): return [0, 1-2*y] area = integrate.nquad(f, [bounds_x, bounds_y]) # Inner to outer with nquad # possibly assume x,y,z are all 1 unless specified for class function # lambda 1* # [1,1] # needs to eval to 1 for integral of z portion. Stop guessing print(area) def g(o, m, i): # outer, middle, inner return 1 # default 1 def bounds_o(): return [0, 1] def bounds_m(o): return [0, 2*(1-o)] def bounds_i(o,m): return [0, 3*((1-m)/(2-o))] tArea = integrate.nquad(g, [bounds_i, bounds_m, bounds_o]) print(tArea) """nquad is definately easier for simple integrals perhaps it could be further simplified by wrapping a class around bounds o, m, i I probably still should learn how to use tplquad..""" """ Centre of Mass """ # integral w respecitve dimension divided by mass rho = 3 # or some funct # new g = lambda a, b: g(x,y,z) * rho(x,y,z) vol = integrate.nquad(g, [bounds_i, bounds_m, bounds_o]) print(vol) def h(o, m, i): return 1 def rho(o,m,i): return 3 herho = lambda o, m, i: h(o,m,i) * rho(o,m,i) mass2 = integrate.nquad(herho, [bounds_i, bounds_m, bounds_o]) print(mass2) # Now rho and h can be functions and live appily ever after #Now I have to calculate centre of mass def com(mass): # must corespond with variables used for integration lol = integrate.nquad(lambda o,m,i: h(o,m,i) * o,\ [bounds_i, bounds_m, bounds_o]) lml = integrade.nquad(lambda o,m,i: h(o,m,i) * m,\ [bounds_i, bounds_m, bounds_o]) lil = integrade.nquad(lambda o,m,i: h(o,m,i) * i,\ [bounds_i, bounds_m, bounds_o]) return lol/mass2, lml/mass2, lil/mass2 print(com(mass2))
# -*- coding : utf-8 -*- # # install : pip install -U memory_profiler # # usage : python -m memory_profiler Memory_Profiler/1.Getting_Start.py @profile def Fibonacci_Recursion(val): if (val == 1): return 0 elif (val == 2): return 1 else: return Fibonacci_Recursion(val - 1) + Fibonacci_Recursion(val - 2) @profile def Fibonacci_Repeat(val): val_1 = 0 val_2 = 1 val_3 = 0 temp = 0 if (val == 0): return 0 elif (val == 1): return 1 else: for i in range(0, val): temp = val_2 val_2 = val_1 + val_2 val_1 = temp return val_2 @profile def TEST(): recursion = 0 repeat = 0 recursion = Fibonacci_Recursion(20) repeat = Fibonacci_Repeat(20) print(recursion, repeat) if __name__ == "__main__": TEST()
words = [] maxLengthList = 50 while len(words) < maxLengthList: item = input("Enter your words to the List: ") words.append(item) print (words) print ("That's your words List") print (words)
import numpy as np """ Function that normalizes each row of the matrix x (to have unit length). """ def normalizeRows(x): # Compute x_norm as the norm 2 of x. x_norm = np.linalg.norm(x, ord = 2, axis = 1, keepdims = True) # Divide x by its norm. x = x / x_norm # x -- The normalized (by row) numpy matrix. return x x = np.array([ [0, 3, 4], [1, 6, 4]]) print("normalizeRows(x) = " + str(normalizeRows(x)))
import random import argparse import sys parser = argparse.ArgumentParser() parser.add_argument("-n", "--number", type=int, help="number of users to extract (default: 3)", default=3) parser.add_argument("-f", "--file", type=str, help="Gradebook.md file to be processed (default: ../final-gradebook.md)", default='../final-gradebook.md') args = parser.parse_args() # by default, extracts 3 users from the 'final-gradebook.md' file USER_LIMIT = args.number fname = args.file # tries to open the chosen file, the default file name # is the one selected in the parser try: with open(fname) as f: all_lines = f.readlines() except getattr(__builtins__,'FileNotFoundError', IOError): print "#### the file %s has not been found! ####" % fname sys.exit() # trims every line in the input file all_lines = [x.strip().replace(" ", "") for x in all_lines] # list which will contain the users rankings users = [] # adds each user's score to the list just created for line in all_lines: if "http" in line: array = line.split("**") users.append((array[1],int(array[3]))) # this line can be commented if the list of # users is already sorted users.sort(key=lambda l: l[1], reverse=True) # DEBUG: prints all the users contained in the file # for pair in users: # print "User %s scored %d" % (pair[0], pair[1]) # resulting list from the process chosen = [] # iteratively selects a subset of the users, starting # from those in the first positions of the 'users' list while len(users) > 0: # select the subset of users with the current maximum score subset = [l for l in users if l[1] == users[0][1]] # select either the whole subset of users or only a part of it if(len(subset) + len(chosen) > USER_LIMIT): chosen += [subset[i] for i in random.sample(xrange(len(subset)), USER_LIMIT-len(chosen))] break else: chosen += subset users = users[len(subset):] # opens a file for output and writes there the results of the process with open('selected_students.txt', 'w') as out_file: for pair in chosen: print "--- Chosen user %s with score %d" % (pair[0], pair[1]) out_file.write('--- Chosen user ' + pair[0] + ' with score ' + str(pair[1]) + '\n')
# edgelist_to_adjlist.py def printAdjList(adjList): for i in range(len(adjList)): print(i, ":", adjList[i]) #---------------------------------------------------------------- def main(): edge_u = [0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4] edge_v = [1, 3, 4, 0, 2, 3, 4, 1, 3, 0, 1, 2, 4, 0, 1, 3] # our graph has n=5 nodes n = 5 # create empty adjacency lists - one for each node - # with a Python list comprehension adjList = [[] for k in range(n)] # create empty adjaceny list using dictionary dictAdjList = {} dictAdjList = [[] for k in range(n)] print(type(dictAdjList) # scan the arrays edge_u and edge_v for i in range(len(edge_u)): print(i) u = edge_u[i] v = edge_v[i] adjList[u].append(v) dictAdjList[u].append(v) # check adjacency list print("Adjacency list: ") printAdjList(adjList) print(dictAdjList[0]) print(dictAdjList[1]) print(dictAdjList[0]) #------------------------------------------------------------------ main()
#!/usr/bin/env python3 #Kevin Wong #kmw396 - 14240214 #10/28/2018 #Lab 5 - Python Intro - Q2 #Imports UTF-8 file ids, removes whitespace and splits name from number, sorts name and numbers, and prints output import sys if len(sys.argv) == 1: print("Missing Arguments") sys.exit() else: f = open(sys.argv[1], "r") #open file d = {} #dictionary read = f.readline() while read: read = read.strip("\n") #remove whitespace split = read.split(" ", 1) #split name from number d[int(split[0])] = split[1] #add record to dictionary read = f.readline() #read next line for key in sorted(d): #print output print('{0} {1}'.format(key, d[key]))
"""This module contains a collection of functions related to geographical data.""" from floodsystem.utils import sorted_by_key from floodsystem.haversine import haversine '''Function that recieves a list of monitoring station objects, and a longitude and latitude coordinates in the form of a touple, then returns a list of the station name, location and distance sorted in increasing distance from the coordinates''' def stations_by_distance(stations, p): a = [] for i in stations: x = float(haversine(p,i.coord, miles=False)) y = (i,x) a.append(y) a=sorted_by_key(a,1) return a '''Function that recieves a list of monitoring station objects and creates a list of the rivers with a monitoring station''' def stations_within_radius(stations, centre, r,): stations_with_distance = stations_by_distance(stations, centre) stations_relative_to_r= [] for i in stations_with_distance: if i[1]<r: m = i[0] stations_relative_to_r.append(m) else: pass return stations_relative_to_r def rivers_with_station(stations): a = [] for i in stations: x = str(i.river) a.append(x) return sorted(set(a)) '''Function that maps river names to a list of stations on that given river''' def stations_by_river(stations): d={} for i in range(len(stations)): x = stations[i].river l = [] if not x in d: for i in range(len(stations)): if stations[i].river == x: y = stations[i].name l.append(y) l = sorted(l) d[x]=l return d "Function that prints the number of stations along N rivers" def rivers_by_station_number(stations, N): m = stations_by_river(stations) n=[] for key, value in m.items(): x= (key, len(list(filter(bool, value)))) n.append(x) n.sort( key=lambda x: x[1], reverse=True) while n[N-1][1] == n[N][1]: N += 1 return n[:N-1]
# coding: utf-8 # In[9]: import networkx as nx import pandas as pd import numpy as np from networkx.algorithms import bipartite # This is the set of employees employees = set(['Pablo', 'Lee', 'Georgia', 'Vincent', 'Andy', 'Frida', 'Joan', 'Claude']) # This is the set of movies movies = set(['The Shawshank Redemption', 'Forrest Gump', 'The Matrix', 'Anaconda', 'The Social Network', 'The Godfather', 'Monty Python and the Holy Grail', 'Snakes on a Plane', 'Kung Fu Panda', 'The Dark Knight', 'Mean Girls']) # you can use the following function to plot graphs # make sure to comment it out before submitting to the autograder def plot_graph(G, weight_name=None): ''' G: a networkx G weight_name: name of the attribute for plotting edge weights (if G is weighted) ''' # %matplotlib notebook # import matplotlib.pyplot as plt plt.figure() pos = nx.spring_layout(G) edges = G.edges() weights = None if weight_name: weights = [int(G[u][v][weight_name]) for u,v in edges] labels = nx.get_edge_attributes(G,weight_name) nx.draw_networkx_edge_labels(G,pos,edge_labels=labels) nx.draw_networkx(G, pos, edges=edges, width=weights); else: nx.draw_networkx(G, pos, edges=edges); # In[2]: # Question 1 # Using NetworkX, load in the bipartite graph from Employee_Movie_Choices.txt and return that graph. # This function should return a networkx graph with 19 nodes and 24 edges def answer_one(): movie_choices = nx.read_edgelist('Employee_Movie_Choices.txt', delimiter = "\t") return movie_choices # plot_graph(answer_one()) # In[3]: # Question 2 # Using the graph from the previous question, add nodes attributes named 'type' # where movies have the value 'movie' and employees have the value 'employee' and return that graph. # This function should return a networkx graph with node attributes {'type': 'movie'} or {'type': 'employee'} def answer_two(): P = answer_one() for item,value in P.nodes(data=True): if item in movies: value['type']='movie' if item in employees: value['type']='employee' return P # In[4]: # Question 3 # Find a weighted projection of the graph from answer_two which tells us # how many movies different pairs of employees have in common. # This function should return a weighted projected graph. def answer_three(): P = answer_two() weig_proj = bipartite.weighted_projected_graph(P, employees) return weig_proj # plot_graph(answer_three()) # In[5]: # Question 4 # Suppose you''d like to find out if people that have a high relationship score also like the same types of movies. # Find the Pearson correlation ( using DataFrame.corr() ) between employee relationship scores # and the number of movies they have in common. # If two employees have no movies in common it should be treated as a 0, not a missing value, # and should be included in the correlation calculation. # This function should return a float. def answer_four(): B = answer_three() B_df = pd.DataFrame(list(B.edges(data = True)), columns = ['From1', 'To1', 'mov_score']) EmpRel = nx.read_edgelist('Employee_Relationships.txt', data = [('rel_score', int)]) EmpRel_df = pd.DataFrame(list(EmpRel.edges(data = True)), columns=['From', 'To', 'rel_score']) # Convert the one edge direction to double directional B_copy_df = B_df.copy() B_copy_df.rename(columns = {'From1': 'To', 'To1': 'From'}, inplace = True) B_df.rename(columns = {'From1': 'From', 'To1': 'To'}, inplace = True) B_final_df = pd.concat([B_df, B_copy_df]) #Merge Weighted Bi-directional and Emp Relation DFs final_df = pd.merge(B_final_df, EmpRel_df, on = ['From', 'To'], how = 'right') final_df['mov_score'] = final_df['mov_score'].map(lambda x: x['weight'] if type(x) == dict else None) final_df['mov_score'].fillna(value = 0, inplace = True) final_df['rel_score'] = final_df['rel_score'].map(lambda x: x['rel_score']) corr_val = final_df['mov_score'].corr(final_df['rel_score']) return corr_val # answer_four()
class Bucket(object): """ Objects of this class simulate a memory limited list of numbers. It also proxies any other methods straight to the list implementation contained within. """ def __init__(self, size, seed_numbers=None): self.size = size if seed_numbers is None: seed_numbers = [] self.numbers = seed_numbers def insert_number(self, a_number): """ Insert a number in this bucket using the insertion-sort strategy """ # Due dilligence check. if self.is_full(): raise "Bucket is full!" i = 0 for number in self.numbers: if number > a_number: break else: i += 1 self.numbers.insert(i, a_number) def get_statistic(self, k=None): """ Get the k-th order statistic from the numbers in this bucket. Defaults to the median. """ if k is None: k = math.ceil(len(self.numbers) / 2) - 1 return self.numbers[k] def get_max(self): """ Get the maximum of the numbers in this bucket """ return self.numbers[len(self.numbers) - 1] def get_min(self): """ Get the minimum of the numbers in this bucket """ return self.numbers[0] def is_full(self): """ Returns if the bucket is at capacity """ return len(self.numbers) >= self.size def in_range(self, a_number): """ Predicate to check if `a_number` should belong to the `bucket` in `node` """ return a_number >= self.get_min() and a_number <= self.get_max() def __getattr__(self, name): """ Delegate all other methods to the conained list of numbers """ return getattr(self.numbers, name)
""" The permit predictor is an example application using a trained model to predict the confidence that a building permit is issued """ import numpy as np from data_io import restore_object from constants import CATEGORICAL_FEATURES, NUMERIC_FEATURES, PCA_PICKLE_FILE, ENCODER_PICKLE_FILE, MODEL_PICKLE_FILE def main(): print("""\n *%%. %%%#, .%%%%%%%, %%%%( %% .%%%%/ %% /%%%( %% /. .%%%%* *%/ #%%( %% /%%. %%%%( %%* .%( %% *%%%% %%%%%%%. *%%% %% %%% %%%%% %%%%. ,%%%%% %% (/ %% *%%%# # ,%%%%( %% (%%* #* %%%# %%%( %% ,%%%# % %%%, #%* %( %% #%%/ %%%%% %%% %% / .%%, %%%%% %%% /%( %% (% #%% *%%%% %%% /%( %% (%/ %%* %%%( #%%% /%( %% (%% %% %%%%%%%%%%%%%%%%%% /%( %% (%%. ( %%%%%%% %%% /%( %% (%%( .%%%%%% %%% /%( %% (%%. .%%%%% #%% /%( %% (. .%%, %%% /%( %% """) print('\nWelcome to the Seattle Building Permit Predictor') print('Please enter the permit details below') calc_confidence() def calc_confidence(): """ Calculates the confidence that a building permit is issued based on the feature values entered by the user """ permit = np.array([[ input('Permit class: '), input('Permit type: '), input('Type mapped: '), input('Housing Units: '), input('Year: '), input('Neighborhood: ') ]]) # Restore required objects encoder = restore_object(ENCODER_PICKLE_FILE) pca = restore_object(PCA_PICKLE_FILE) clf = restore_object(MODEL_PICKLE_FILE) # Transform permit application permit = np.concatenate((encoder.transform(permit[:, CATEGORICAL_FEATURES]).toarray(), permit[:, NUMERIC_FEATURES].astype(float)), axis=1) permit = pca.transform(permit) # Predict confidence that the permit will be issued confidence_issued = clf.predict_proba(permit)[0][1] print('The permit will be issued with a confidence of: ' + str(confidence_issued)) if input("Would you want to predict another permit? (y/n)") == 'y': calc_confidence() if __name__ == '__main__': main()
""" This program generates interesting graphviz game trees for Tic-Tac-Toe. Probably you want to use it in a pipeline: python gentree.py heuristic | dot -Tpdf -o heuristic.pdf """ import sys import ttt class Trees: def rational(): """Tree of all rational moves, up to symmetry. This is how all possible well-played games of Tic-Tac-Toe will go.""" return ttt.GameTree(levels=9,strategy='rational') def legal(): """Tree of all legal moves, up to symmetry. This is how all possible games Tic-Tac-Toe will go.""" return ttt.GameTree(levels=9,strategy='legal') def heuristic(): """Both players using the heuristic strategy (win, block, center, corner). Most games go like this.""" return ttt.GameTree(levels=9,strategy='heuristic') def beatChildren(): """X plays rational, O plays the heuristic strategy.""" return ttt.GameTree(levels=9,strategy={'x':'rational','o':'heuristic'}) def canHeuristicLose(): """X plays heuristic. Is it possible to lose?""" return ttt.GameTree(levels=9,strategy={'x':'heuristic','o':'legal'}) def centerThenWinblock(): """X plays in the center, then just plays winblock strategy.""" return ttt.GameTree(levels=8,strategy={'x':'winblock','o':'rational'}, positions = [ttt.Position( [(1,1)] )]) mytrees = [t for t in dir(Trees) if callable(Trees.__dict__[t])] def usage(): outstr = __doc__ + '\n' outstr += 'Select one of the following trees as a command line option' for t in mytrees: outstr += '\n* ' + t + '\n ' + Trees.__dict__[t].__doc__ print >> sys.stderr, outstr sys.exit(1) if len(sys.argv) != 2: usage() t = sys.argv[1] if t not in mytrees: usage() thetree = Trees.__dict__[t]() print thetree.dotrepr() print >> sys.stderr, t,':',Trees.__dict__[t].__doc__ for stat,value in thetree.stats().iteritems(): print >> sys.stderr, stat print >> sys.stderr, value
from turtle import Turtle ALIGNMENT = 'center' FONT = ('Courier', 13, "normal") class Scoreboard(Turtle): def __init__(self): super().__init__() self.hideturtle() self.color('white') self.penup() self.l_score = 0 self.r_score = 0 self.show_score() def show_score(self): self.goto(0, 280) self.clear() score = f"Score : {self.l_score} Score : {self.r_score}" self.write(score, align=ALIGNMENT, font=FONT)
""" 長方形の中に円が含まれるかを判定するプログラムを作成してください。次のように、長方形は左下の頂点を原点とし、右上の頂点の座標 (W,H) が与えられます。 また、円はその中心の座標 (x,y) と半径 r で与えられます。 """ W, H, x, y, r = map(int,input().split()) print("Yes" if x>=r and x+r<=W and y>=r and y+r<=H else "No")
import sys from socket import * # Get the server hostname and port as command line arguments argv = sys.argv host = argv[1] port = argv[2] sourceadd = argv[3] destadd = argv[4] subjekt = argv[5] text = argv[6] timeout = 1 # in second endmsg = '\r\n.\r\n' # Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET, SOCK_STREAM) # Port number may change according to the mail server # clientSocket.connect((mailserver, 25)) clientSocket.connect((host, int(port))) recv = clientSocket.recv(1024) if recv[:3] != '220': print '220 reply not received from server.' # Send HELO command and print server response. heloCommand = 'HELO '+ sourceadd +'\r\n' clientSocket.send(heloCommand) recv1 = clientSocket.recv(1024) #print recv1 if recv1[:3] != '250': print '250 reply not received from server.' # Send MAIL FROM command and print server response. mailfrom = 'MAIL FROM: <'+ sourceadd +'>\r\n' clientSocket.send(mailfrom) recv2 = clientSocket.recv(1024) #print recv2 if recv2[:3] != '250': print '250 reply not received from server.' # Send RCPT TO command and print server response. rcptto = 'RCPT TO: <'+destadd+'>\r\n' clientSocket.send(rcptto) recv3 = clientSocket.recv(1024) #print recv3 if recv3[:3] != '250': print '250 reply not received from server.' # Send DATA command and print server response. data = 'DATA\r\n' clientSocket.send(data) recv4 = clientSocket.recv(1024) #print recv4 if recv4[:3] != '354': print '354 reply not received from server.' # Send message header. clientSocket.send('SUBJECT: '+subjekt+'\r\n') clientSocket.send('From: <'+sourceadd+'>\r\n') clientSocket.send('To: <'+destadd+'>\r\n') clientSocket.send('Content-Type: text/plain; charset=ISO-8859-1\r\n') # Send message data. clientSocket.send('\r\n') clientSocket.send(text) # Message ends with a single period. clientSocket.send(endmsg) recv5 = clientSocket.recv(1024) #print recv5 if recv5[:3] != '250': print '250 reply not received from server.' # Send QUIT command and get server response. quitcommand = 'QUIT\r\n' clientSocket.send(quitcommand) recv6 = clientSocket.recv(1024) #print recv6 if recv6[:3] != '221': print '221 reply not received from server.'
# Create Allergy check code # then PASTE THIS CODE into edX # [ ] get input for input_test variable input_test = input("Categories of food eaten in the last 24 hours: ") # [ ] print "True" message if "dairy" is in the input or False message if not print("It is", "dairy".capitalize().lower().upper().swapcase() in input_test.capitalize().lower().upper().swapcase(),"that 'seafood, dairy, nuts, and chocolate cake' contains 'dairy'") # [ ] print True message if "nuts" is in the input or False if not print("It is", "nuts".capitalize().lower().upper().swapcase() in input_test.capitalize().lower().upper().swapcase(),"that 'seafood, dairy, nuts, and chocolate cake' contains 'nuts'") # [ ] Challenge: Check if "seafood" is in the input - print message print("It is", "seafood".capitalize().lower().upper().swapcase() in input_test.capitalize().lower().upper().swapcase(),"that 'seafood, dairy, nuts, and chocolate cake' contains 'seafood'") # [ ] Challenge: Check if "chocolate" is in the input - print message print("It is", "chocolate".capitalize().lower().upper().swapcase() in input_test.capitalize().lower().upper().swapcase(),"that 'seafood, dairy, nuts, and chocolate cake' contains 'chocolate'")
import tweepy from tweepy import Stream import StreamListenerClass as strm import time seeds = ["#disgusted", "#fearful", "#angry", "#surprised", "#scared", "#lonely", "#excited", "#wonderful", "#sleepy"] """ authenticates into the twitter API using the authentication handler and returns the authentication object For generating the keys follow link: https://www.apps.twitter.com 1.Generate the Consumer key and consumer secret 2.You will now find a button on screen below your consumer secret key that says generate "access token". 3.Go ahead and generate your access token. 4.Copy and paste those in your code. """ def authenticate(): consumer_key = "Di2t90Ru7HvBl02JqFhtt3SAE" consumer_secret = "s02nhrpmXE441MzWzEx5noYkc2V0zYBGvFuNPxtvPsxip8he7x" atoken = "3731913556-aDibg2miti6XsIHIIUanQCrQRBJBcv4FFcxd1sR" asecret = "fCmuUCy5pjyiyL6nPr2ANMk4hg3wuGl9m57KaWrXK4usa" auth = tweepy.OAuthHandler(consumer_key=consumer_key, consumer_secret=consumer_secret) auth.set_access_token(atoken, asecret) return auth """ use the auth object to initialize the stream and then specify the filter to extract data from twitter """ def listen_to_stream(auth): twitter_stream = Stream(auth,strm.listener(time.time(),20000)) twitter_stream.filter(track = seeds, languages = ['en']) if __name__ == '__main__': listen_to_stream(authenticate())
#getting current time and date from datetime import datetime now=datetime.now() print now #extracting information from datetime import datetime now=datetime.now() current_year=now.year current_month=now.month current_day=now.day print now.year print now.month print now.day #Hot Date from datetime import datetime now = datetime.now() print '%s/%s/%s' % (now.month, now.day, now.year) #pretty time from datetime import datetime now = datetime.now() print '%s:%s:%s' % (now.hour, now.minute, now.second)
givenNumber = int(input('Enter number: ')) def square_dictionary(given_number): dictionary = dict() for i in range(1, given_number+1): key, value = i, i*i new_data = {key: value} dictionary.update(new_data) return dictionary print(square_dictionary(givenNumber))
givenString = input('Enter string: ') def exchange_first_last_character(given_string): return given_string[-1] + given_string[1:-2] + given_string[0] print(exchange_first_last_character(givenString))
givenDictionary =[ {"name": "Sid", "age": 20}, {"name": "Sid", "age": 5}, {"name": "Ajay", "age": 20}, {"name": "Sam", "age": 20}, {"name": "Ram", "age": 22}, {"name": "Shyam", "age": 11} ] def sort_dictionary(given_string): sorted_list = sorted(given_string, key=lambda i: (i['name'], i['age'])) return sorted_list print(sort_dictionary(givenDictionary))
given_tuple = ('a','p','p','l','e') print(f"Old Tuple: {given_tuple}") string = ''.join(given_tuple) print(f"String: {string}")
dictionary = {'a': 100, 'b': 20, 'c': 50, 'd': -100} print(f"Sum of dictionary values are {sum(dictionary.values())}")
given_tuple = (1,2,3,4,5,6) print(f"Given Tuple: {given_tuple}") temp_list = list(given_tuple) to_remove = 3 print(f"To remove: {to_remove}") temp_list.remove(to_remove) new_tuple = tuple(temp_list) print(f"New Tuple: {new_tuple}")
givenString = input('Enter string: ') def reverse_string(given_string): answer = "" for i in reversed(given_string): answer += i return answer print(reverse_string(givenString))
givenString = input('Enter string: ') def remove_odd_index(given_string): return given_string[1::2] print(remove_odd_index(givenString))
import unittest from Counter import Counter class TestCounter(unittest.TestCase): def setUp(self): #Default Constructor Counter self.defaultCounter = Counter() def test_constructor(self): c = Counter(32, 10, 61, True) expected = [8, 10, 1, True] cValues = [c.getHour(), c.getMinute(), c.getSecond(), c.getFormat()] self.assertEqual(cValues, expected) def test_display2Digits(self): c = Counter(12, 10, 15, True) expected = "12:10:15 PM" self.assertEqual(c.displayCounter(), expected) def test_display1Digit(self): c = Counter(1, 2, 3, True) expected = "01:02:03 AM" self.assertEqual(c.displayCounter(), expected) def test_displayMilitary(self): c = Counter(23, 1, 15, False) expected = "23:01:15" self.assertEqual(c.displayCounter(), expected) #Test Second Changes def test_incrementSecond(self): self.defaultCounter.incrementSecond() expected = 1 self.assertEqual(self.defaultCounter.getSecond(), expected) def test_incrementSecondRollover(self): for i in range(0, 60): self.defaultCounter.incrementSecond() expected = 0 self.assertEqual(self.defaultCounter.getSecond(), expected) def test_decrementSecond(self): c = Counter(12, 10, 15, True) c.decrementSecond() expected = 14 self.assertEqual(c.getSecond(), expected) def test_decrementSecondRollunder(self): self.defaultCounter.decrementSecond() expected = 59 self.assertEqual(self.defaultCounter.getSecond(), expected) #Test Hour Changes def test_incrementHour(self): self.defaultCounter.incrementHour() expected = 1 self.assertEqual(self.defaultCounter.getHour(), expected) def test_incrementHourRollover(self): for i in range(0, 24): self.defaultCounter.incrementHour() expected = 0 self.assertEqual(self.defaultCounter.getHour(), expected) def test_decrementHour(self): c = Counter(12, 10, 15, True) c.decrementHour() expected = 11 self.assertEqual(c.getHour(), expected) def test_decrementHourRollunder(self): self.defaultCounter.decrementHour() expected = 23 self.assertEqual(self.defaultCounter.getHour(), expected) #Test Minute Changes def test_incrementMinute(self): self.defaultCounter.incrementMinute() expected = 1 self.assertEqual(self.defaultCounter.getMinute(), expected) def test_incrementMinuteRollover(self): for i in range(0, 60): self.defaultCounter.incrementMinute() expected = 0 self.assertEqual(self.defaultCounter.getMinute(), expected) def test_decrementMinute(self): c = Counter(12, 10, 15, True) c.decrementMinute() expected = 9 self.assertEqual(c.getMinute(), expected) def test_decrementMinuteRollunder(self): self.defaultCounter.decrementMinute() expected = 59 self.assertEqual(self.defaultCounter.getMinute(), expected) #Test Full Day Roll Under / Over def test_dayRollunder(self): self.defaultCounter.decrementSecond() expected = [23, 59, 59] cValues = [self.defaultCounter.getHour(), self.defaultCounter.getMinute(), self.defaultCounter.getSecond()] self.assertEqual(cValues, expected) def test_dayRollover(self): c = Counter(23, 59, 59, True) c.incrementSecond() expected = [0, 0, 0] cValues = [c.getHour(), c.getMinute(), c.getSecond()] self.assertEqual(cValues, expected) if __name__ == "__main__": unittest.main()
import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from scipy.io import loadmat import urllib import time class PerceptronLearningAlgorithm(object): def __init__(self, inputs, labels, epochs=1, test_amount=10000): self.inputs = self.prepare_input(inputs) # flattened data with 1 in the beginning, size inputs (number of images) x785 # self.y = self.transform_labels_to_hot_vector(labels) # matrix of hot vectors, size data (number of images) x 10 self.labels = labels self.inputs_train, self.inputs_test, self.labels_train, self.labels_test = train_test_split(self.inputs, self.labels, test_size=test_amount) self.epochs = epochs def prepare_input(self, inputs): inputs = np.true_divide(inputs, 255.0) # normalize all the inputs to be between 0-1 return self.add_bias(inputs) def add_bias(self, inputs): """Adds bias to the inputs. The bias is constant and is equal to 1""" a, b = np.shape(inputs) c = np.ones((a, 1)) return np.hstack((c, inputs)) def transform_labels_to_hot_vector(self, labels): hot_vectors = np.zeros((len(labels), 10)) # column vector, each row will have a hot vector of a label for i in range(len(labels)): label = int(labels[i]) hot_vectors[i, label] = 1 return hot_vectors def plot_image(self, image, predicted_class=None, actual_class=None): """Plots one image out of the images Parameters: image - a vector of size 1x785 with normalized values (all values between 0-1) This function is just for debugging or visualizing, it is not used in calculations""" image = image[:, 1:] # getting rid of the bias image = np.reshape(image, (28, 28)) # reshaping to size 288x28 image = np.multiply(image, 255) # Un-normalizing the image if predicted_class and actual_class: plt.xlabel("Predicted Class: {}\nActual Class: {}".format(predicted_class, actual_class)) plt.imshow(image, cmap='gray') plt.show() def initial_weights(self, number_of_inputs): """Initial weights, returns a vector of size 785x1 of random numbers between 0-1. we subtract 0.5 because the weights can be negative.""" return np.random.rand(number_of_inputs, 1) - 0.5 def sign_function(self, weights, one_input): """Returns the sign of the dot product of weights and inputs. Parameters: weights - a vector of size 785x1 inputs - a vector of size 785x1""" return np.sign(np.dot(weights.T, one_input)) def one_vs_all_labels(self, labels, number_to_classify): """One vs all means using a binary classifier with more than two available outputs The label of the wanted class will be 1 and the rest will be -1""" modified_labels = np.where(labels == number_to_classify, 1, -1) # modified labels is now 1 or -1 depending on the number to classify return modified_labels def update_weights(self, weights, x, y): """Update weights using the update rule""" return weights + y * x def predict(self, weights, one_input): """Predicts the output of the input Parameters: weights - a vector of size 785x1 one_input - a vector of size 785x1""" prediction = self.sign_function(weights=weights, one_input=one_input)[0] return prediction def test_classifier(self, weights, number_to_classify, inputs=None, labels=None): """Test the classifier and returns the true positive, true negative, false positive and false negative Parameters: inputs - size of 785 x test_set_size which each column has a different picture labels - size of 1 x test_set_size which each column has the label of the image weights - a vector of size 785 x 1""" if inputs is None: inputs = self.inputs_test.T # inputs is now in size of 785x10000 each column is an image if labels is None: labels = self.one_vs_all_labels(self.labels_test, number_to_classify=number_to_classify) # size 1 x 10000 true_pos = 0 true_neg = 0 false_pos = 0 false_neg = 0 test_set_size = inputs.shape[1] # number of images in the test set for i in range(test_set_size): # iterate through all images current_input = np.reshape(inputs[:, i], (785, 1)) current_label = labels[i] prediction = self.predict(weights=weights, one_input=current_input) # get the estimator if current_label == 1: if prediction == 1: true_pos += 1 if prediction == -1: false_neg += 1 if current_label == -1: if prediction == 1: false_pos += 1 if prediction == -1: true_neg += 1 return true_pos, true_neg, false_pos, false_neg def calculate_accuracy(self, confusion_matrix): """Claculates the accuracy of the classifier""" return np.trace(confusion_matrix)/np.sum(confusion_matrix) def calculate_sensitivity(self, true_pos, false_neg): """Calculate the sensitivity of a classifier""" return true_pos/(true_pos+false_neg) def plot_confusion_table(self, true_pos, true_neg, false_pos, false_neg, number_to_classify, show_plot=False): """Plots the confusion table of a specific class. Where the class is the number_to_classify""" sensitivity = self.calculate_sensitivity(true_pos, false_neg) table = np.array([[true_pos, false_pos], [false_neg, true_neg]]) axis_names = ["{}".format(number_to_classify), "Not {}".format(number_to_classify)] plt.figure(number_to_classify) ax = plt.gca() # fig, ax = plt.subplots() ax.matshow(table, cmap=plt.get_cmap('Blues')) for (i, j), z in np.ndenumerate(table): if i == 0: if j == 0: string = "True Positive" else: string = "False Positive" else: if j == 0: string = "False Negative" else: string = "True Negative" ax.text(i, j, string + '\n{}'.format(z), ha='center', va='center', bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3')) tick_marks = np.arange(len(axis_names)) plt.xticks(tick_marks, axis_names) plt.yticks(tick_marks, axis_names) plt.title("Confusion Table of number {}\n".format(number_to_classify)) plt.ylabel('Actual Class') plt.xlabel('Predicted Class\nsensitivity={:0.4f}'.format(sensitivity)) if show_plot: plt.show() def calculate_error(self, inputs, labels, weights): """Return the in-sample error This error is defined by the number of misclassified examples divided by the number of examples""" train_set_size = inputs.shape[1] # number of images in the training set wrong_predictions_counter = 0 for i in range(train_set_size): # iterate through all images current_input = np.reshape(inputs[:, i], (785, 1)) current_label = labels[i] prediction = self.predict(weights=weights, one_input=current_input) # get the estimator # if the prediction is wrong then add to counter of wrong predictions if prediction != current_label: wrong_predictions_counter += 1 return wrong_predictions_counter / train_set_size def train_binary_classifier(self, number_to_classify, epochs=None): """Trains one binary class out of all the 10 multi-class PLA number_to_clasify is the number that the classifier will train in one vs all method""" if epochs is None: epochs = self.epochs inputs = self.inputs_train.T # inputs is now in size of 785x60000 each column is a picture labels = self.one_vs_all_labels(self.labels_train, number_to_classify) # size 1x60000, labels are now 1 or -1 train_set_size = inputs.shape[1] # number of images in the training set weights = self.initial_weights(inputs.shape[0]) # weights is size 785x1 pocket = weights # for pocket algorithm pocket_error = self.calculate_error(inputs=inputs, labels=labels, weights=pocket) start_time = time.time() for _ in range(epochs): # go through all training set epoch times for i in range(train_set_size): # iterate through all images current_input = np.reshape(inputs[:,i], (785, 1)) current_label = labels[i] prediction = self.predict(weights=weights, one_input=current_input) # get the estimator # if the prediction is wrong then update the weights if prediction != current_label: weights = self.update_weights(weights, current_input, current_label) # calculating error and updating the pocket if (i+1) % 1000 == 0: error = self.calculate_error(inputs=inputs, labels=labels, weights=weights) if error < pocket_error: pocket_error = error pocket = weights elapsed_time = time.time() - start_time print("Finished training class {}\nThe training took {:0.3f} seconds\n" .format(number_to_classify, elapsed_time)) return pocket def train_all_classes(self, epochs=None): """Trains all 10 classes as part of multi-class PLA Returns an array of size 785x10 which each column is the optimal weights for a class. e.g returns np.array([w0, w1, ..., w9]) which each w is size 785x1""" print("Started training, this will take a few minutes...") if epochs is None: epochs = self.epochs start_time = time.time() weights = None for i in range(10): # Find the optimal weights of each class (weights i is size 785x1) weights_i = self.train_binary_classifier(number_to_classify=i, epochs=epochs) # save the optimal weights to form an array of optimal weights of each class if i == 0: weights = weights_i else: weights = np.hstack((weights, weights_i)) elapsed_time = time.time() - start_time print("*********\nFinished Training all classes.\nThe training took {:0.3f} seconds".format(elapsed_time)) return weights def test_all_classes(self, weights): """Test all the classes of the multi-class PLA Parameters: weights - an array of size 785x10, each column has the optimal weights of each class like the returned value of train_all_classes""" # resulting_test... is in format [[true_pos0, true_neg0, false_pos0, false_neg0], [true_pos1, true_neg1, false_pos1, false_neg1],...] resulting_test_of_all_classes = [] for i in range(10): weights_i = np.reshape(weights[:,i], (785, 1)) true_pos, true_neg, false_pos, false_neg = self.test_classifier(weights_i, i) resulting_test_of_all_classes.append([true_pos, true_neg, false_pos, false_neg]) return resulting_test_of_all_classes def plot_confusion_table_of_all_classes(self, test_results, show_table=False): for i in range(10): true_pos, true_neg, false_pos, false_neg = test_results[i] self.plot_confusion_table(true_pos=true_pos, true_neg=true_neg, false_pos=false_pos, false_neg=false_neg, number_to_classify=i) if show_table: plt.show() def predict_multiclass(self, weights, one_input): """Predicts the output of the multi-class PLA Parameters: weights - a vector of size 785x10 which is column is the optimal weights of each class one_input - a vector of size 785x1 (one image)""" predicted_labels = [] for i in range(10): # iterate through all optimal weights current_weights = np.reshape(weights[:,i], (785, 1)) # take weights i prediction = np.dot(current_weights.T, one_input) # and get the dot product with the input predicted_labels.append(prediction) # save the result predictions_array = np.array(predicted_labels) return np.argmax(predictions_array) # the predicted label is the argmax of the labels predicted by each optimal weights def test_multiclass(self, weights, inputs=None, labels=None): """Test the classifier and returns confusion matrix Parameters: inputs - size of 785 x 10000 which each column has a different picture labels - size of 1 x 10000 which each column has the label of the image weights - a vector of size 785 x 10 which is column has the optimal weights of each class""" if inputs is None: inputs = self.inputs_test.T # inputs is now in size of 785x10000 each column is an image if labels is None: labels = self.labels_test # size 1 x 10000 # initialize the confusion matrix to zeros # rows are predicted class and columns are actual class confusion_matrix = np.zeros((10,10), dtype="int32") test_set_size = inputs.shape[1] # number of images in the test set for i in range(test_set_size): current_input = np.reshape(inputs[:, i], (785, 1)) current_label = int(labels[i]) prediction = self.predict_multiclass(weights=weights, one_input=current_input) confusion_matrix[prediction][current_label] += 1 return confusion_matrix def plot_confusion_matrix(self, confusion_matrix, show_plot=False): """Plots the confusion table of the multi-class PLA. Parameters: confusion_matrix - size 10x10 Rows are predicted class and columns are actual class as returned from test_multiclass""" accuracy = self.calculate_accuracy(confusion_matrix=confusion_matrix) axis_names = list(range(10)) plt.figure(10) ax = plt.gca() ax.matshow(confusion_matrix, cmap=plt.get_cmap('Blues')) # Putting the value of each cell in its place and surrounding it with a box so you could see the text better for (i, j), z in np.ndenumerate(confusion_matrix): ax.text(i, j, '{}'.format(z), ha='center', va='center', fontsize=12, bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3')) # setting x and y axis to be the class numbers tick_marks = np.arange(len(axis_names)) plt.xticks(tick_marks, axis_names) plt.yticks(tick_marks, axis_names) # setting title and labels for the axis plt.title("Confusion Matrix of the Multi-Class PLA\n") plt.ylabel('Predicted Class') plt.xlabel('Actual Class\naccuracy={:0.4f} %'.format(accuracy*100)) if show_plot: plt.show() def plot_confusion_matrix_and_tables(self, confusion_matrix, test_results): """Plots the confusion matrix and the confusion table of each class Parameters: confusion_matrix - size 10x10 as returned from test_multiclass test_results - and array of tp, tn, fp, fn as returned from test_all_classes_part_a""" self.plot_confusion_table_of_all_classes(test_results) self.plot_confusion_matrix(confusion_matrix) plt.show() def save_weights(self, weights, path=r"./multiclass_weights_part_a.npy"): """Save weights for further use""" np.save(path, weights) def get_weights_from_file(self, path=r"./multiclass_weights_part_a.npy"): """Load weights previously saved in a file""" return np.load(path) def import_mnist(): mnist_alternative_url = r"https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat" mnist_path = "./mnist-original.mat" response = urllib.request.urlopen(mnist_alternative_url) with open(mnist_path, "wb") as f: content = response.read() f.write(content) mnist_raw = loadmat(mnist_path) mnist = { "data": mnist_raw["data"].T, "target": mnist_raw["label"][0], "COL_NAMES": ["label", "data"], "DESCR": "mldata.org dataset: mnist-original", } print("Success in loading MNIST data set") return mnist def main(save_weights=False, use_weights_from_file=False): # Get the mnist data set mnist = import_mnist() # instantiate a class of the PLA with the mnist data set pla = PerceptronLearningAlgorithm(inputs=mnist["data"], labels=mnist["target"], epochs=1) # Train all the 10 classes of the multi-class PLA # 10 classes, one for each digit of the mnist data set # Training is on the training set which is 60,000 images if use_weights_from_file: optimal_weights_of_all_classes = pla.get_weights_from_file() else: optimal_weights_of_all_classes = pla.train_all_classes() # size 785x10 which each column is the optimal weights for a class. if save_weights: pla.save_weights(weights=optimal_weights_of_all_classes) # Testing each separate class # Testing is on the testing set which is 10,000 images test_results = pla.test_all_classes(optimal_weights_of_all_classes) # See pla.test_all_classes_part_a for return value # Get the confusion matrix # Rows are predicted class and columns are actual class # size 10x10 confusion_matrix = pla.test_multiclass(optimal_weights_of_all_classes) # Plot the confusion matrix and confusion table of each class pla.plot_confusion_matrix_and_tables(confusion_matrix=confusion_matrix, test_results=test_results) if __name__ == '__main__': # Entry point of the script main(save_weights=False, use_weights_from_file=False)
#Python program to get the difference between a given number and 17, if #the number is greater than 17 return double the absolute difference. def difference(n): diff=n-17 if(diff>=17): return diff*2 return abs(diff) print(difference(14)) print(difference(34))
#Python program to get the n (non-negative integer) copies of the first 2 #characters of a given string. Return the n copies of the whole string if the #length is less than 2 n=int(input("enter number")) def string(str1): lenght=len(str1) if lenght >2: return str1[0:2]*n return str1*n print(string("renu")) print(string("re"))
#Write a Python program that accepts an integer (n) and computes the value of #n+nn+nnn. Go to the editor #Sample value of n is 5 #Expected Result : 615 n=int(input("enter the number")) no1=n no2=(n*10)+no1 no3=(n*100)+no2 total=no1+no2+no3 print(total)
# Python program to calculate the sum over a containe sum=0 lis1=[1,4,5,2] for elements in lis1: sum=sum+elements print(sum)
# Write a Python program to get a string which is n (non-negative integer) # copies of a given string def string(str1): n=int(input("enter num")) return n*str1 print(string("renu"))
#To find the given value is in the list or not def grp_data(elements,n): for values in elements: if values==n: return True return False print(grp_data([2,4,6,7],2)) print(grp_data([2,4,6,7],8))
#This program is used to find reverse the the name first_name=(input("")) sec_name=(input("")) #This print is print the sec_name #in reverse manner and first_name as like sec_name print(sec_name[-1::-1] ,first_name[-1::-1]) #This print is uded to print the sec_name and first_name print(sec_name,first_name)
#Greatest of the Three numbers: a, b, c = map(int, input().split()) if(a>b and a>c): print("a is Greatest") elif(b>a and b>c): print("b is Greatest") elif(c>a and c>b): print("c is Greatest") else: print("all are equal")
import string def create_cypher_dict(cypher_key): cypher_key = int(cypher_key) alphabet = string.ascii_lowercase alphabet_offset = alphabet[cypher_key:] + alphabet[0:cypher_key] return alphabet_offset def caesar(text_str, cypher_key) : alphabet = string.ascii_lowercase alphabet_offset = create_cypher_dict(cypher_key) text_secured = "" for element in text_str: if element.lower() in alphabet: n = list(alphabet).index(element.lower()) text_secured += alphabet_offset[n] else: text_secured += element print(text_secured) key = input("Input key: ") text_input = input("Input your text: ") str(text_input) caesar(text_input,key)
# Создание файла учетных записей import shelve import QuestandAnsw ######################################## ''' Создаю функцию, в ней пишу код добавления новых учетных записей. Введенные значения записываю как ключ и значение соответственно в файл. ''' def add_account(): while True: add_account = input('Хотите добавить аккаунт?\n' 'Да (добавить)\n' 'Enter (не добавлять)\n').lower() if add_account == 'да': account = input('Введите логин: ') password = input('Введите пароль: ') Account_File[account] = password print('---------------------------') elif add_account != 'да': print('---------------------------') break ######################################## ''' Тоже самое только удаляю данные из файла. Удаляю ключ, а вместе с ним удаляется значение. ''' def pop_account(): while True: pop_account = input('Хотите удалить аккаунт?\n' 'Да (удалить)\n' 'Enter (не удалять)\n').lower() if pop_account == 'да': account = input('Введите логин: ') Account_File.pop(account, 'Такого логина уже нет') print('Аккаунт успешно удалён.') elif pop_account != 'да': print('---------------------------') break ######################################## '''Выбираем аккаунт из списка''' ######################################## def choose_login(): while True: print('---------------------------') print(list(Account_File.keys())) print('---------------------------') choose_login = input('Выберите логин: ') if choose_login in Account_File.keys(): print(str(Account_File[choose_login])) print('---------------------------') elif choose_login == '': print('Идем дальше.') print('---------------------------') break elif choose_login not in Account_File.keys(): print('///////////////////////////') print('Такого логина нет.') print('///////////////////////////') continue ####################################### # # ####################################### Account_File = shelve.open('Account') user_dict = {} final_dict = {} answer = QuestandAnsw.answ() #Проверка пользователя для доступа к базе учетных записей(файлу). while True: test = input('Введите ответ на вопрос или Enter, чтобы выйти: ') if test == answer: while True: choose_login() #подключаю написанные выше функции add_account() pop_account() stop = input('Хотите закрыть программу? ') if stop == 'да': break elif test == '': print('Выход из общего цикла') break elif test != answer: test = input('Попробуйте ещё раз: ') print('---------------------------') continue Account_File.close() exit_input = input('Нажмите Enter чтобы закрыть окно. ') del exit_input
import sys def deleteContent(fName): with open(fName, "w"): pass def file_len(): count = (len(listOfTasks) + 1) return count listOfTasks = [] listOfMarkedItems = [] f = open("marked.list","r") d = open("tasks.list","r") for line in f: listOfMarkedItems.append(bool(line)) for line in d: if line not in listOfTasks: listOfTasks.append(line) f.close() d.close() deleteContent("marked.list") deleteContent("tasks.list") def main(): #Menu command = input("Please specify a command: [list, add, mark, archive,exit]: ") commands = ["list","add","mark","archive"] if command == "list": ListTask() elif command == "add": AddTask() elif command == "mark": print("You saved the following to-do items:") ListTask() choose = input("Which one you want to mark as completed: ") MarkAsComplete(choose) elif command == "archive": Archive() elif command == "exit": ExitProgram() def ListTask(): for i in range(0,len(listOfTasks)): print("{}. {}".format(i+1,listOfTasks[i])) def AddTask(): #adding a new task counter = file_len() tempItem = input("Add an item: ") listOfMarkedItems.append(False) listOfTasks.append("[{}] {}".format(listOfMarkedItems[counter-1], tempItem)) print("Item added.") def MarkAsComplete(number): number = int(number) tempString = listOfTasks[number - 1] tempString = tempString.replace("False","True") listOfTasks[number - 1] = tempString listOfMarkedItems[number-1] = True def Archive(): for i in range(len(listOfMarkedItems)-1): if(listOfMarkedItems[i-1] == True): del listOfMarkedItems[i-1] del listOfTasks[i-1] print("All completed tasks got deleted.") def ExitProgram(): f = open("marked.list","a") d = open("tasks.list","a") for i in range(0,len(listOfMarkedItems)): f.write(str(listOfMarkedItems[i])+"\n") for i in range(0,len(listOfTasks)): d.write(listOfTasks[i]+"\n") f.close() d.close() sys.exit(0) while True: main()
import numpy as np def derivative(x, y): dy_dx = np.zeros(y.shape,np.float) dy_dx[0:-1] = np.diff(y)/np.diff(x) dy_dx[-1] = (y[-1] - y[-2])/(x[-1] - x[-2]) return dy_dx
"""You know these Create a new password forms? They do a lot of checks to make sure you make a password that is hard to guess and you will surely forget. In this Bite you will write a validator for such a form field. Complete the validate_password function below. It takes a password str and validates that it: is between 6 and 12 chars long (both inclusive) has at least 1 digit [0-9] has at least two lowercase chars [a-z] has at least one uppercase char [A-Z] has at least one punctuation char (use: PUNCTUATION_CHARS) Has not been used before (use: used_passwords) If the password matches all criteria the function should store the password in used_passwords and return True. Have fun, keep calm and code in Python!""" import re def validate_password(password): used_passwords = [] length_re = re.compile(r'.{8,}') uppercase_re = re.compile(r'.*[A-Z]') lowercase_re = re.compile(r'.*[a-z].*[a-z]') number_re = re.compile(r'.*\d.*\d') punctuation_re = re.compile(r'[\!\@\#\$\%\&]') if (length_re.search(password) is not None and uppercase_re.search(password) is not None and lowercase_re.search(password) is not None and number_re.search(password) is not None and punctuation_re.search(password) is not None and password not in used_passwords): used_passwords.append(password) return True else: return False print (validate_password("a4a4Aa3!@#$%&"))
mypizzas=['margherita','hawaii','pepperoni'] friendpizzas=mypizzas[:] mypizzas.append('cheese') friendpizzas.append('ham') print("My favorite pizzas are:") for pizza in mypizzas: print(pizza) print("\nMy friend's favorite pizzas are:") for pizza in friendpizzas: print(pizza)
""" My Product class """ class Product: def __init__(self, name="", price=0.0, is_on_sale=False): self.name = name self.price = price self.is_on_sale = is_on_sale def __str__(self): on_sale_string = "" if self.is_on_sale: on_sale_string = " On Sale" return "Name: {} Price: ${:.2f}{}".format(self.name, self.price, on_sale_string) def _repr_(self): return str(self)
""" Word Occurrences """ words_str = str(input("Enter string of words: ")) words_list = words_str.split() words_list_sorted = words_list.sort() word_count_dict = {} for word in words_list: if word in word_count_dict: word_count_dict[word] += 1 else: word_count_dict[word] = 1 print() print("Text: ", words_str) for key,val in word_count_dict.items(): print("{}: {:>5d}".format(key, val)) #def get_max_column_width(column_number, table): # max_width = 0 # for row in table: # current_width = len(row[column_number]) # if current_width > max_width # max_width = current_width # return max_width + 5
""" CP1404/CP5632 - Practical Program to determine grade from score """ def decide_score(score): # function to decide grade from score if score > 100 or score < 0: return "Invalid score" elif score > 90 <= 100: return "Excellent" elif score >= 50 < 90: return "Passable" else: return "Bad" score = float(input("Enter score: ")) print("Grade: ", decide_score(score))
import collections class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Tree: def __init__(self, base): self.base = base def levelOrder(self, root): if not root:return res=[] queue=collections.deque([root]) while queue: tmp=collections.deque() for _ in range(len(queue)): node=queue.popleft() if len(res)%2: tmp.appendleft(node.val) else:tmp.append(node.val) if node.left:queue.append(node.left) if node.right:queue.append(node.right) res.append(list(tmp)) return res base = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6), Node(7))) # 树的根节点 tree = Tree(base) result = tree.levelOrder(tree.base) print(result) res='' for i in result: for j in i: res=res+str(j)+' ' print(res)
import datetime def car(user_input): _running = False while(user_input != "quit"): if(user_input == "help"): print(f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} >", "Commands:\n", "<START> - starts the engine\n", "<STOP> - stops the engine\n", "<HELP> - shows engine commands\n", "<QUIT> - exits\n") elif(user_input == "start"): if(not _running): _running = True print( f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} > START ENGINE\n") else: print( f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} > INVALID COMMAND. ENGINE already started.\n") elif(user_input == "stop"): if(_running): _running = False print( f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} > STOP ENGINE\n") else: print( f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} > INVALID COMMAND. ENGINE already stopped.\n") else: print(f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} >", "INVALID COMMAND. Type 'HELP' for engine commands or 'QUIT' to exit\n") user_input = input().lower() print(f"{datetime.datetime.now().strftime('%B %d %Y %H:%M:%S')} > Exit") if(__name__ == "__main__"): car(input().lower())
# two dimensional plotting import pylab as p # three dimensional plotting import mpl_toolkits.mplot3d.axes3d as p3 def visualize(R): # can only plot 2D or 3D if R.shape[0] > 3: print('can only plot 2D or 3D') return fig = p.figure() # scatter3D requires a 1D array for x, y, and z if R.shape[0] == 3: ax = p3.Axes3D(fig) ax.scatter3D(R[0, :], R[1, :], R[2, :]) else: # ax = p.Axes(fig) p.scatter(R[0, :], R[1, :]) p.show()
# CTI-110 # Converts kilometers to miles # Eihab Ghanim # 10/26/2017 # Converting kilometers to miles. CONVERSION_FACTOR = 0.6214 # The distance in kilometers. def main(): kilometers = float (input('Enter a distance in kilometers: ')) show_miles(kilometers) def show_miles (km): miles = km * CONVERSION_FACTOR # Display the miles print(km, 'kilometers equales',miles, 'miles.') main()
# Напишите по одному позитивному тесту для каждого метода калькулятора from app.calculator import Calculator class TestCalc: def setup(self): self.calc = Calculator def test_multiply_calculator_correctly(self): assert self.calc.multiply(self, 2, 2) == 4 def test_division_calculator_correctly(self): assert self.calc.division(self, 6, 2) == 3 def test_subtraction_calculator_correctly(self): assert self.calc.subtraction(self, 6, 2) == 4 def test_adding_calculator_correctly(self): assert self.calc.adding(self, 6, 2) == 8
# Assume s is a string of lower case characters. # Write a program that prints the longest substring of s in which the letters occur in alphabetical order. # In the case of ties, print the first substring s = 'azcbobobegghakl' # s = 'abcbcd' compare_str = ' ' final_str = '' length = 0 for letter in s: if letter >= compare_str[-1]: if compare_str[-1] == ' ': compare_str = letter else: compare_str += letter else: compare_str = letter if len(compare_str) > length: final_str = compare_str length = len(compare_str) print("Longest substring in alphabetical order is: {}".format(final_str))
a = input ("Enter your text: ") #enter the text to convert it's first letter capital. print (a.capitalize())
#imports import random import sys loopnum = 0 many = input("How many to generate: ") # asks for how many links to generate f= open("output.txt","w+") # creating output.txt while loopnum < int(many): # loop result_str = ''.join((random.choice('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890') for i in range(16))) # generate link print("https://discord.gift/" + result_str) # show link f.write("https://discord.gift/" + result_str + "\n") # adding links to output.txt loopnum += 1 input("ok? (press any button)")
from listas import lista_ligada from mapas import associacao # 0: ("primos", 3) ("par", 20) # 1: 15, 25, 35, # 2: 16, 26, 36 # 3 (150:200): class Mapa(): def __init__(self): self.__elementos = lista_ligada.ListaLigada() self.__numero_categorias = 10 for i in range(self.__numero_categorias): self.__elementos.inserir(lista_ligada.ListaLigada()) def gerar_numero_espalhamento(self, chave): return hash(chave) % self.__numero_categorias def contem_chave(self, chave): numero_espalhamento = self.gerar_numero_espalhamento(chave) categoria = self.__elementos.recuperar_elemento_no(numero_espalhamento) for i in range(categoria.tamanho): associacao = categoria.recuperar_elemento_no(i) if associacao.chave == chave: return True return False def remover(self, chave): numero_espalhamento = self.gerar_numero_espalhamento(chave) categoria = self.__elementos.recuperar_elemento_no(numero_espalhamento) for i in range(categoria.tamanho): associacao = categoria.recuperar_elemento_no(i) if associacao.chave == chave: categoria.remover_elemento(associacao) return True return False def adicionar(self, chave, valor): if self.contem_chave(chave): self.remover(chave) numero_espalhamento = self.gerar_numero_espalhamento(chave) categoria = self.__elementos.recuperar_elemento_no(numero_espalhamento) categoria.inserir(associacao.Associacao(chave, valor)) def recuperar(self, chave): numero_espalhamento = self.gerar_numero_espalhamento(chave) categoria = self.__elementos.recuperar_elemento_no(numero_espalhamento) for i in range(categoria.tamanho): associacao = categoria.recuperar_elemento_no(i) if associacao.chave == chave: return associacao.valor return False def __str__(self): temp = self.__elementos.__str__() return temp
def longestPalindromic(s): if len(s) == 1 or s == '': return str(len(s)) else: if s == s[::-1]: return s else: for i in range(len(s)-1, 0, -1): for j in range(len(s)-i+1): temp = s[j:j+i] if temp == temp[::-1]: return temp longestPalindromic("artrartrt") == "rtrartr" longestPalindromic("abacada") == "aba" longestPalindromic("aaaa") == "aaaa" s = "12345" s[::-1] str(len(s))
cipher_grille = ( 'X...' , '..X.' , 'X..X' , '....' ) letters = ('itdf', 'gdce', 'aton', 'qrdi') def recall_password(cipher_grille, letters): """ returns password based upon cipher_grille, the cipher_grille is rotated 3 times 90 degrees to right """ coordinates = [] len_cipher_grille = len(cipher_grille) # loop through cipher_grill and store coordinates of X's for i in range(len_cipher_grille): for j in range(len_cipher_grille): if cipher_grille[i][j] == 'X': coordinates.append((i,j)) password = '' for x,y in coordinates: password = password + letters[x][y] for i in range(3): coordinates = sorted((y, 3 - x) for (x, y) in coordinates) for x,y in coordinates: password = password + letters[x][y] return password
def most_frequent(data: list) -> str: """ determines the most frequently occurring string in the sequence. """ frq_dict = {} for lt in data: if lt not in frq_dict: frq_dict[lt] = 1 else: frq_dict[lt] += 1 max_val = max(frq_dict.values()) for key, value in frq_dict.items(): if value == max_val: max_key = key return max_key # faster solution on checkio def most_frequent2(data: list) -> str: """ determines the most frequently occurring string in the sequence. """ # your code here return max(set(data), key=data.count) # paar probeerseltjes data =['a', 'a', 'b', 'b'] x= set(data) type(x) y = {'a','b','a','c'} print(data.count)
# -*- coding: utf-8 -*- """ Created on Mon Oct 29 21:16:59 2018 @author: JOOST """ nums = [1,2,3] nums.__iter__() print(dir(nums)) print(next(nums)) i_nums = nums.__iter__() # is the same as i_nums = iter(nums) next(i_nums) print(i_nums) print(dir(i_nums)) sentence = ' joost is gek' class Sentence: def __init__(self, sentence): self.sentence = sentence self.index = 0 self.words = self.sentence.split() def __iter__(self): return self def __next__(self): if self.index >= len(self.words): raise StopIteration index = self.index self.index += 1 return self.words[index] my_sentence = Sentence('Joost is gek' ) for word in my_sentence: print(word) def sentence(sentence): for word in sentence.split(): yield word my_sentence = sentence('Joost is gek' ) for word in my_sentence: print(word) next(my_sentence) def outer_function(msg): message = msg def inner_function(): print(message) return inner_function hi_func = outer_function('Hi') bye_func = outer_function('Bye') hi_func() bye_func() # a decorator is a function that takes another function # as an argument and adds some kind of function # and returns this as a function def decorator_function(message): def wrapper_function(): print(message) return wrapper_function hi_func = decorator_function('Hi') bye_func = decorator_function('Bye') hi_func() bye_func() def decorator_function(original_function): def wrapper_function(): return original_function() return wrapper_function hi_func = decorator_function('Hi') bye_func = decorator_function('Bye') hi_func() bye_func() def fibonacci(n): if n == 1: return 1 elif n == 2: return 2 elif n > 2: return fibonacci(n-1) + fibonacci(n-2) for n in range(1,11): print(n, ":", fibonacci(n)) # memoization fibonacci_cache = {} def fibonacci(n): # if we have cached the value, then return it if n in fibonacci_cache: return fibonacci_cache[n] if n == 1: value = 1 elif n == 2: value = 2 elif n > 2: value = fibonacci(n-1) + fibonacci(n-2) fibonacci_cache[n] = value return value from functools import lru_cache @lru_cache(maxsize=1000) def fibonacci(n): if n == 1: return 1 elif n == 2: return 2 elif n > 2: return fibonacci(n-1) + fibonacci(n-2)
import sys def flatten_with_precedence(arr, parenthise=False): """ Creates a string representation for the types created as arrays. """ # if the type is already a str, leave it as it is. if isinstance(arr, str): return arr result = [] for x in range(len(arr)): elem = arr[x] # if the element is a str, no need to do more if isinstance(elem, str): result.append(elem) else: # if it isn't, you need to flatten the type taking into consideration the # parenthisation. if x == len(arr) - 1: result.append(flatten_with_precedence(elem, False)) else: result.append(flatten_with_precedence(elem, True)) # add parenthesis when asked for if parenthise: return f"({' '.join(result)})" else: return ' '.join(result) def amplify_expr_spaces(expr): """ Cleans a little bit the input string from the user. This version of the interpreter is really basic, so several wrong inputs can break the program execution. """ # add spaces after and before the parenthesis splittable_cmd = expr.replace('(', ' ( ') splittable_cmd = splittable_cmd.replace(')', ' ) ') tokens = splittable_cmd.split(' ') # remove white spaces produces by multiple spaces while ('' in tokens): tokens.remove('') return tokens def get_expr_type(expr, types): """ Evaluates recursively the type of an expression. """ # parse the input expr to get the tokens plain_cmd = ' '.join(expr) tokens = amplify_expr_spaces(plain_cmd) i = 0 # first token needs always to be defined, if it isn't the expr isn't valid token = tokens[i] if not token in types: print(f'ERROR, el nombre "{token}" no ha sido definido.') return result = types[token] if isinstance(types[token], str) else types[token].copy() # iterate over the tokens to check the type of every sub-expr while i < len(tokens) - 1: i += 1 token = tokens[i] # catch sub-expr and get its type if token == '(': k = i + 1 count = 0 # check if there's a sub-expr inside the current sub-expr while k < len(tokens): if tokens[k] == '(': count += 1 if tokens[k] == ')': if count == 0: final = k else: count -= 1 k += 1 # compute type for subexpr tokens (i+1, final-1) subexpr_type = get_expr_type(tokens[i+1:final], types) if not subexpr_type: return None token_type = subexpr_type # replace the chunk of the tokens that were contained in the sub-expr. # a token is left to emulate the space of the sub expr. # example # after: ['t1', '(', 't2', 't3', ')', 't4'] # before: ['t1', '(', 't4'] # even though '(' alone doesn't make sense, it fills the space of the sub-expr. tokens = tokens[:i] + tokens[final:] else: # check if the token is not defined if not token in types: print(f'ERROR, el nombre "{token}" no ha sido definido.') return # if the type is an array, make a deep copy token_type = types[token] if isinstance(types[token], str) else types[token].copy() # if the result is a str because the type was so, do the computations quicker. if isinstance(result, str): # constant type if result[0].isupper(): # constant type is correct if result == token_type: return token_type else: str_token_type = flatten_with_precedence(token_type) print(f'ERROR, No se pudo unificar {result} con {str_token_type}') return else: # variable type return token_type j = 0 # check if is a constant type if result[j][0].isupper(): # check that the type is exactly the same # if it is, can be removed from the remaining tree if token_type == result[j]: # IMPORTANT: this is the notion of a binary tree, a better implementation # will be parsing the input as a tree and evaluating. del result[j+1] del result[j] else: str_token_type = flatten_with_precedence(token_type) print(f'ERROR, No se pudo unificar {result[j]} con {str_token_type}') return else: # set variable type for the remaining instances replace_token = result[j] for k in range(len(result)): if result[k] == replace_token: result[k] = token_type # remove type that has been satisfied del result[j+1] del result[j] result = flatten_with_precedence(result) return result def define_name(cmd_tokens, types): """ Define a name and its type. """ # little parsing of the input str plain_cmd = ' '.join(cmd_tokens) tokens = amplify_expr_spaces(plain_cmd) type_name = cmd_tokens[0] # check if it is single or multi token if len(cmd_tokens[1:]) == 1: types[type_name] = cmd_tokens[1] created_type = cmd_tokens[1] else: types[type_name] = cmd_tokens[1:] created_type = ' '.join(cmd_tokens[1:]) print(f'Se definió "{type_name}" con el tipo {created_type}') def main(): """ Executes the main client with the infinite loop. """ print('\nBienvenido al manejador de tipos de datos polimórficos!') types = {} # infinite loop while True: cmd = input('$> ') tokens = cmd.split(' ') # option define by the first token if tokens[0] == 'DEF': define_name(tokens[1:], types) elif tokens[0] == 'TIPO': typ = get_expr_type(tokens[1:], types) if typ: print(typ) elif tokens[0] == 'SALIR': sys.exit(0) else: print('Por favor, utilice un comando válido.') main()
# Project Euler problem 51 # Find the smallest prime which, by replacing part of the number (not necessarily # adjacent digits) with the same digit, is part of an eight prime value family. import math import time primes = {} def is_prime(n): for i in range(2, int(math.sqrt(n))+1): if n%i == 0 : return 0 return 1 def build(): for i in range(2, 1000000): primes[i] = is_prime(i) def test_nr(n): # how many primes can be obtained by replacing all 0's, all 1's and all 2's if primes[n] == 0 : return 0 list_d = [] while n>0: list_d.append(n%10) n /= 10 list_d.reverse() f_sum = lambda x,y: x*10+y max_cnt = 1 for i in range(0,3): cnt_primes = 1 for j in range(i+1, 10): # replace all 'i' with 'j' n_j=map(lambda x:x if x!=i else j, list_d) if n_j == list_d: break nj = reduce(f_sum, n_j) if primes[nj] == 1: cnt_primes += 1 if cnt_primes>max_cnt: max_cnt = cnt_primes return max_cnt def solve(): build() nbr = 2 while test_nr(nbr) < 8 : nbr += 1 print nbr if __name__=="__main__": start = time.time() solve() print "Elapsed Time:", (time.time() - start), "sec"
# Project Euler problem 67 # Similar with problem 18 # Solution 1 : bottom up. Build maximum path from bottom. So initial triangle becomes: # 3 # 7 4 # 2 4 6 #9 5 9 3 # # 3 # 7 4 # 11 13 15 #9 5 9 3 # # 3 # 20 19 # 11 13 15 #9 5 9 3 # # 23 # 20 19 # 11 13 15 #9 5 9 3 # Solution 2 : top down. Build maximum path from top vertex. So initial triangle becomes: # 3 # 7 4 # 2 4 6 #9 5 9 3 # # 3 # 10 7 # 2 4 6 #9 5 9 3 # # 3 # 10 7 # 12 14 13 #9 5 9 3 # # 3 # 10 7 # 12 14 13 #21 19 23 16 #Solve using first solution def get_numbers(): #lines = open("tri_small.txt", "r") lines = open("tri.txt", "r") listOfRows = [] for line in lines: currRow = [int(x) for x in line.split()] listOfRows.append(currRow) return listOfRows def solve(): row_list = get_numbers() length = len(row_list) for i in xrange(length-2, -1, -1) : len_row = len(row_list[i]) for j in range(0, len_row) : row_list[i][j] += max(row_list[i+1][j], row_list[i+1][j+1]) print row_list[0] return 0 if __name__ == "__main__": max = solve()
# Project Euler problem 21 # returns the sum of proper divisors of n def d(n): sum = 0 for i in range(1, n/2+1): if(n%i == 0): sum += i return sum def solve(): sum = 0 divs_sum = {} for i in range(1, 10000+1): divs_sum[i] = d(i) for i in range(1, 10000+1): for j in range(1, 10000+1): if(i != j) and (divs_sum[i]==j) and (divs_sum[j]==i) : print "pair: " + str(i) + " " + str(j) sum += i return sum if __name__ == "__main__": sum = solve() print sum
class Student(object): def __init__(self,name): self.name=name def show(self): print(f'姓名:{self.name}') def pr(): print('1') #print(__name__) if __name__=='__main__': pr() stu=Student('张三') stu.show()
array = [] total = 0 print ('MENGHITUNG NILAI RATA-RATA') n = int(input("Masukkan banyaknya siswa: ")) for x in range(n-1): nilai = float(input("Masukkan nilai siswa ke-{} : ".format(x+1))) array.append(nilai) kamu = int(input("Masukkan nilai kamu: ")) rata = (sum(array) + kamu)/ n print("Hasil rata-rata adalah : ",rata) if kamu < rata: print ('nilaimu dibawah rata-rata') elif kamu == rata : print ('nilaimu sama dengan rata-rata') else: print ('nilaimu diatas rata-rata')
from Animal import Animal from Tail import Tail class Fish(Animal): def __init__(self, type): self.tail = Tail(type) def __str__(self): return "Fish tail: %s" % self.tail
import zipfile, os def backup(folder): folder = os.path.abspath(folder) n = 1 while True: zip1 = os.path.basename(folder) + '_' + str(n) + '.zip' #Name of the zip file = nameOfThebackedUpFolder_<backupcount>.zip if not os.path.exists(zip1): break n = n + 1 print('Creating %s...' % (zip1)) backupZip = zipfile.ZipFile(zip1, 'w') for f, subf, filen in os.walk(folder): print('Adding files in %s...' % (f)) # Add the current folder to the ZIP file. backupZip.write(f) # Add all the files in this folder to the ZIP file. for filename in filen: if filename.endswith('.mp3'): print(filename) newBase = os.path.basename(folder) + '_' # Remember: Do not back up the zip files if filename.startswith(newBase) and filename.endswith('.zip'): continue backupZip.write(os.path.join(f, filename)) backupZip.close() print('Done.') backup('C:\\Test') #Enter the path of the directory which you want to back up
user_input = input("WHat is your Name? ") User_age = input("What is your age? ") hobby = input("What is favorite thing to do ") print(f"Hello {user_input}, you really are {User_age}, I didnt know your hobby was {hobby}") print(f"I HOPE YOU ENJOY BASE CAMP {user_name}!!!!!")
#!/usr/bin/env python # -*- coding: utf-8 -*- import click import glob # Command line tool to search for files by type @click.command() # Option to specify the file path @click.option( "--path", default=".", prompt="Enter the file path to search in!!", help="Path to search for files", ) # Option to specify the file type @click.option( "--ftype", default="*", prompt="Enter the file type to search for!", help="File type to search for", ) def search(path, ftype): """ Search for files by type """ # Get all files in the path files = glob.glob(path + "/*." + ftype) click.echo(click.style("Found matches:", fg="red")) # Print the files for file in files: click.echo(click.style(file, bg="white", fg="black")) if __name__ == "__main__": search()
"""Additional click types used in the project""" import json import click class StringListParamType(click.ParamType): """Converts a comma-separated list of strings and returns a list of strings.""" name = 'string list' def convert(self, value, param, ctx): return value.split(',') class JsonParamType(click.ParamType): """Converts a json string as input and returns a dict.""" name = 'json' def convert(self, value, param, ctx): try: return json.loads(value) except json.JSONDecodeError: self.fail(f'{value} is not a valid json value', param, ctx) STRING_LIST = StringListParamType() DICT = JsonParamType()
# coding=utf-8 ''' 定义一个学生类,用来形容学生 ''' # 定义一个空类 class Student(): # 一个空类,pass代表直接跳过 #此处pass必须有 pass # 定义一个对象 mingyue = Student() ''' #再定义一个类用于描述听Python的学生 class PythonStudent(): #用None给不确定的值赋值 name = None age = 18 course = "python" #需要注意 #1,def doHomework的缩进层级 #2,系统默认有一个self参数 def doHomework(self): print("做作业") return None #实例化一个叫yueyue的学生,是一个具体的人 #yueyue = PythonStudent() #print(yueyue.name) #print(yueyue.__dict__) #print(PythonStudent.__dict__) # 注意成员函数的调用没有传递进入参数 #yueyue.doHomework() class A(): name = "dana" age = 18 def say(self): self.name = "aaa" self.age = 200 #此时 a 称为类的实例 print(A.name) print(A.age) print("*"*20) print(id(A.name)) print(id(A.age)) print("*"*20) a = A() print(a.name) print(a.age) print(id(a.name)) print(id(a.age)) #此例说明类实例的属性和其对象的实例的属性在不对对象的实例属性赋值的前提下。指向同一变量 ''' ''' class A(): name = "dana" age = 18 def say(self): self.name = "aaa" self.age = 200 #此时 a 称为类的实例 print(A.name) print(A.age) print("*"*20) print(id(A.name)) print(id(A.age)) print("*"*20) a = A() a.name = "asd" a.age = 10 print(a.name) print(a.age) print(id(a.name)) print(id(a.age)) ''' ''' class Student(): name = "da" age = 18 def say(self): self.name = "aaa" self.age = 200 print("my name is {0},age{1}".format(self.name,self.age)) return None def sayAgain(s): print("my name {0}".format(s.name)) return None yy = Student() yy.say() yy.sayAgain() ''' class Teacher(): name = "d" age = 19 def say(self): self.name = "aaa" self.age = 200 print("my name is {0},age{1}".format(self.name, __class__.age)) return None def sayA(): print("asdf") print(__class__.name) print(__class__.age) return None t = Teacher() t.say() Teacher.sayA()
file = open('input.txt') lines = file.readlines() file.close() def part_1(lines): questions = set() total = 0 for line in lines: if line == '\n': total += len(questions) questions = set() for char in line.strip(): questions.add(char) total += len(questions) return total def part_2(lines): sets = [] total = 0 for line in lines: if line == '\n': intersect_set = set.intersection(*sets) total += len(intersect_set) sets = [] continue line_set = set() for char in line.strip(): line_set.add(char) sets.append(line_set) intersect_set = set.intersection(*sets) total += len(intersect_set) return total print(part_1(lines)) print(part_2(lines))
#This program will automatically load from a csv file into a database, prompting the user for the servername, a database name and a tablename. When you supply these, and select a file, it will do the rest. import os import sys from sys import argv import pyodbc from sqlalchemy import create_engine import pandas as pd import tkinter as tk from tkinter import * from tkinter import filedialog class Frame1(tk.Frame): def __init__(self, master, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.greetinglabel = tk.Label(text = 'SQL Server Database Auto Loader', font = ("Arial Bold", 12)) self.greetinglabel.pack(side = TOP, padx = 10, pady = 3) self.lbl1 = tk.Label(text = 'Server Name: ', font =("Arial", 12)) self.lbl1.pack(side = TOP, padx = 10, pady = 3) self.entry1 = tk.Entry(root, width = 32) self.entry1.pack(side = TOP, padx = 10, pady = 3) self.lbl2 = tk.Label(text = 'Database Name: ', font =("Arial", 12)) self.lbl2.pack(side = TOP, padx = 10, pady = 3) self.entry2 = tk.Entry(root, width = 32) self.entry2.pack(side = TOP, padx = 10, pady = 3) self.lbl3 = tk.Label(text = 'Table Name: ', font =("Arial", 12)) self.lbl3.pack(side = TOP, padx = 10, pady = 3) self.entry3 = tk.Entry(root, width = 32) self.entry3.pack(side = TOP, padx = 10, pady = 3) self.button1 = tk.Button(root, text = 'Submit', font = ("Arial", 12), command = self.onok) self.button1.pack() def onok(self): servername = self.entry1.get() database = self.entry2.get() tablename = self.entry3.get() c = sqlserverconnection(servername) infile = fileselect() df1 = pd_fileprep(infile) createdatabase(df1, database, c) createtable(df1, database, tablename, c) eng = sqlalch(database) alchload(df1, tablename, eng) root.quit() def fileselect(): root = tk.Tk() root.filename = filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("all files","*.*"),("jpeg files","*.jpg"))) infile = root.filename return infile #Fills all missing data with a zero. def pd_fileprep(infile): l1 = [] with open(infile, 'r') as f: l1 = [] for ele in f: line = ele.split('\n') l1.append(line) header = l1[0] del header[1:] header = [x.replace(" ","_")for x in header] header = str(header) headerstring = header.replace("[",'').replace("]",'').replace("'",'') l2 = headerstring.split(",") rest_of_rows = l1[1:] l3 = [] for ele in rest_of_rows: ele = str(ele) elestring = ele.replace("[",'').replace("]",'').replace("'",'') elestring = elestring.split(",") l3.append(elestring) for ele in l3: del ele[-1] df1 = pd.DataFrame(l3, columns = l2, index = None) df1.fillna(0, inplace = True) return df1 def sqlserverconnection(servername): conn = pyodbc.connect( "Driver={SQL Server Native Client 11.0};" "Server=" + servername + ";" "Trusted_Connection=yes;" ) conn.autocommit = True c = conn.cursor() return c def createdatabase(df1, database, c): c.execute("create database " + database) def createtable(df1, database, tablename, c): hlist = list(df1.columns.values) allpieces = [] for elements in hlist: sqlpiece = str(elements) + " VARCHAR(50)" allpieces.append(sqlpiece) fullstring = ",".join(allpieces) c.execute("USE " + database + ";") c.execute("CREATE TABLE " + tablename + " (" + fullstring + ");") def sqlalch(database): #Enter your servername, and choose your driver below(default: Native Client 11.0) DB = {'servername': 'ENTER_YOUR_SERVERNAME_HERE','database': database, 'driver': 'driver=SQL Server Native Client 11.0'} eng = create_engine('mssql+pyodbc://' + DB['servername'] + '/' + DB['database'] + "?" + DB['driver']) return eng def alchload(df1, tablename, eng): df1.to_sql( name = tablename, con = eng, index = False, if_exists = 'append' ) if __name__ == "__main__": root = tk.Tk() root.title('SQL Server Database Auto Loader') root.geometry("400x250") win1 = Frame1(root).pack(fill="both", expand=True) root.mainloop()
# -*- coding: utf-8 -*- print '%4.2f'%(100000/3.0) print 2*3 print 2**100 #乘方 print len(str(2**100)) #长度 import math,random print math.pi #math 常用的数学模块 print math.sqrt(9) print math.floor(2.5) print math.trunc(3.4) print random.random() print random.randint(0,9) #随机0-9自然数 print random.choice(['+','-','*','/']) print sum((1,2,3,4)) print max((1,2,3,4)) import decimal d=decimal.Decimal('3.141') d+=1 print d decimal.getcontext().prec=3 #精确到小数点后两位 print decimal.Decimal('1')/decimal.Decimal('3') from fractions import Fraction f=Fraction(2,3) # f+=1 print f+Fraction(1,2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 18 14:43:17 2021 @author: shivakesh """ T = int(input()) for i in range(T): a = input() A = set(input().split()) b = int(input()) B = set(input().split()) print(A.issubset(B))
def formatcoord(coord): col = ord(coord[0])-ord('a') row = 8- int(coord[1]) return (row,col) def pawn_move_tracker(moves): print(moves) board = [ [".",".",".",".",".",".",".","."], ["p","p","p","p","p","p","p","p"], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], [".",".",".",".",".",".",".","."], ["P","P","P","P","P","P","P","P"], [".",".",".",".",".",".",".","."] ] turn=-1 piece = {-1:"P", 1:"p"} for move in moves: if(len(move)==2): row, col = formatcoord(move[:2]) if(board[row][col] != "."): return move + " is invalid" oldrow = row-turn if(board[row-turn][col]=='.'): if(((row-turn*2)in (1, 6)) and board[row-turn*2][col]!='.'): oldrow = row-turn*2 else: return move + " is invalid" board[oldrow][col] = "." board[row][col]=piece[turn] elif(len(move)==4): row,col = formatcoord(move[2:4]) offset = ord(move[2])-ord(move[0]) if(board[row][col] == "." or board[row-turn][col-offset] == "."): return move + " is invalid" board[row-turn][col-offset] = "." board[row][col]=piece[turn] = piece[turn] turn = turn * -1 return board
#Asks the user to enter a cost and either a country or state tax. #It then returns the tax plus the total cost with tax. print('What is the cost?') cost = input() print('What is the tax rate? (in %)') rate = input() rate = float(rate) / 100 tax = float(rate) * float(cost) tc = tax + float(cost) print('Tax cost: ' + str(tax)) print('Total cost: ' + str(tc))
""" 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 """ # 对于有序数组,要么从小到大,要么从大到小 # 所以只需要判断相邻的值是否一样 class Solution: @staticmethod def remove_duplicates(nums): # 从数组下标0开始 i = 0 # 如果数组下标小于(数组长度-1),也就是数组最大的下标 while i < len(nums) - 1: # 如果值一样,就删除第一个 if nums[i] == nums[i + 1]: nums.remove(nums[i]) # 如果不一样,就看下一个 else: i = i + 1 return nums, len(nums) if __name__ == '__main__': count = Solution.remove_duplicates([1, 1, 2]) print(count)
import random import time player = random.randint(1,6) print("You rolled " + str(player) ) ai = random.randint(1,6) print("The computer ross...." ) time.sleep(2) print("The computer rolled " + str(ai) ) if player > ai : print("You Win.") #notice indentation elif player == ai : print("Tie Game.") else: print("You Lose.")
#Time Complexity: O(n) #Space Complexity:O(n) #Ran successfully on Leetcode: Yes # Algorithm : # traverse the string, # Traverse the string given # Whenever we encounter '[', we append currdtring and currnum in to the stack # if we encounter closing bracket, we pop out num and the char in string and evaluate curr string as sum of previous string + num*currstring # if the encounter element is number, we multiply it by 1- and add to the character. # If the encountered element is a character, we just add it to the currstring. class Solution(object): def decodeString(self, s): stack = []; curNum = 0; curString = '' for c in s: if c == '[': stack.append(curString) stack.append(curNum) curString = '' curNum = 0 elif c == ']': num = stack.pop() prevString = stack.pop() curString = prevString + num*curString elif c.isdigit(): curNum = curNum*10 + int(c) else: curString += c return curString
import random def play(): user = input("What's your Choice? 'r' for rock, 'p' for papper, 's' for scissors\n") computer = random.choice(['r', 'p', 's']) if user == computer: return "It's a tie" if is_win(user, computer): return "You won!" return " You lost!" # r > s, s > p, p >r def is_win(player, opponent): # return true if player wins # r > s, s > p, p >r if (player == "r" and opponent == "s") or (player == "s" and opponent == "p") or (player == "p" and opponent == "r"): return True print(play())
from tkinter import * root = Tk() v = IntVar() Radiobutton(root,text='One',variable=v,value=1).pack(anchor= W) Radiobutton(root,text='Two',variable=v,value=2).pack(anchor= W) Radiobutton(root,text='Three',variable=v,value=3).pack(anchor= W) mainloop()
from tkinter import * root = Tk() ''' listbox = Listbox(root) listbox.pack(fill=BOTH,expand=True) for i in range(10): listbox.insert(END,str(i)) ''' Label(root,text='red',bg="red",fg="white").pack(side=LEFT) Label(root,text='green',bg="green",fg="black").pack(side=LEFT) Label(root,text='red',bg="blue",fg="white").pack(side=LEFT) mainloop()