blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
205d757e0e6aa561f8a9ab0a42e6d0e74247a7a3 | georgebzhang/Python_LeetCode | /310_minimum_height_trees.py | 1,227 | 3.71875 | 4 | import sys
from collections import defaultdict
class Solution(object):
def findMinHeightTrees(self, n, edges):
def max_height(v):
if v in visited:
return 0
visited.add(v)
n_heights = []
for n in g[v]: # for neighbor of vertex
n_heights.append(max_height(n))
return max(n_heights)+1
if n == 1:
return [0]
g = defaultdict(list)
for e in edges:
g[e[0]].append(e[1])
g[e[1]].append(e[0])
visited = set()
v_heights = {}
min_height = sys.maxsize
for v in g: # for vertex in graph
h = max_height(v)
v_heights[v] = h
min_height = min(min_height, h)
visited.clear()
result = []
for v in g:
if v_heights[v] == min_height:
result.append(v)
return result
def print_ans(self, ans):
print(ans)
def test(self):
n = 6
edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
ans = self.findMinHeightTrees(n, edges)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
98f137239463f7aac4534ed3a594111572727ded | georgebzhang/Python_LeetCode | /39_combination_sum_2.py | 844 | 3.8125 | 4 | class Solution:
def combinationSum(self, candidates, target):
def backtrack(candidates, nums, rem):
# print(nums) # uncomment this to understand how backtrack works
if rem == 0:
result.append(nums)
for i, cand in enumerate(candidates):
if rem >= cand:
backtrack(candidates[i:], nums+[cand], rem-cand) # candidates[i:] guarantees no duplicate lists in result
candidates.sort()
result = []
backtrack(candidates, [], target)
return result
def print_answer(self, ans):
print(ans)
def test(self):
candidates = [2, 3, 6, 7]
target = 7
ans = self.combinationSum(candidates, target)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
6d6d97e0070e2d0177c2a35d8d39fb636eec391a | georgebzhang/Python_LeetCode | /200_number_of_islands_2.py | 1,313 | 3.625 | 4 | class Solution(object):
def numIslands(self, grid):
dirs = ((-1, 0), (1, 0), (0, -1), (0, 1))
def neighbors(i0, j0):
result = []
for di, dj in dirs:
i, j = i0 + di, j0 +dj
if 0 <= i < N and 0 <= j < M and grid[j][i] == '1':
result.append((i, j))
return result
def sink(i, j):
if (i, j) in visited:
return
visited.add((i, j))
grid[j][i] = '0'
for n in neighbors(i, j):
sink(*n)
if not grid:
return 0
M, N = len(grid), len(grid[0])
visited = set()
result = 0
for j in range(M):
for i in range(N):
if grid[j][i] == '1':
result += 1
sink(i, j)
return result
def print_grid(self, grid):
for row in grid:
print(row)
def print_ans(self, ans):
print(ans)
def test(self):
grid = [["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"]]
self.print_grid(grid)
ans = self.numIslands(grid)
self.print_ans(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
41fe3b7409fb596692851d7887d4750795996189 | georgebzhang/Python_LeetCode | /29_divide_two_integers.py | 714 | 3.765625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
sign_dividend = -1 if dividend < 0 else 1
sign_divisor = -1 if divisor < 0 else 1
dividend = abs(dividend)
divisor = abs(divisor)
result = 0
while True:
dividend -= divisor
if dividend >= 0:
result += 1
else:
break
return sign_dividend * sign_divisor * result
def print_answer(self, ans):
print(ans)
def test(self):
dividend = 10
divisor = 3
ans = self.divide(dividend, divisor)
self.print_answer(ans)
if __name__ == '__main__':
s = Solution()
s.test()
|
4ccdd7851dc2177d6a35e72cb57069685d75f72c | echo001/Python | /python_for_everybody/exer9.1.py | 706 | 4.21875 | 4 | #Exercise 1 Write a program that reads the words in words.txt and stores them as
# keys in a dictionary. It doesn’t matter what the values are. Then you
# can use the in operator as a fast way to check whether a string is
# in the dictionary.
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('Ther is no this file %s ' % fname)
exit()
word = dict()
for line in fhand:
line = line.rstrip()
# if line not in word:
# word[line] = 1
# else:
# word[line] = word[line] + 1 #count how many times the same word appear
word[line] = word.get(line,0) + 1 # the same as if.... else...
print(word)
|
19e74e3bc318021556ceec645597199996cfba98 | echo001/Python | /python_for_everybody/exer10.11.3.py | 1,251 | 4.40625 | 4 | #Exercise 3 Write a program that reads a file and prints the letters in
# decreasing order of frequency. Your program should convert all the
# input to lower case and only count the letters a-z. Your program
# should not count spaces, digits, punctuation, or anything other than
# the letters a-z. Find text samples from several different languages
# and see how letter frequency varies between languages. Compare your
# results with the tables at wikipedia.org/wiki/Letter_frequencies.
import string
fname = input('Enter a file name : ')
try:
fhand = open(fname)
except:
print('This file can not be opened. ')
exit()
letterCount = dict()
for line in fhand:
line = line.rstrip()
line = line.translate(line.maketrans('','',string.punctuation)) #delete all punctuation
linelist = line.lower()
for letter in linelist:
if letter.isdigit(): #delete all digit
continue
letterCount[letter] = letterCount.get(letter,0) + 1 #count letters from files
letterCountList = list(letterCount.items())
letterCountList.sort() #sort letters from a to z
for letter,count in letterCountList:
print(letter,count)
|
4d2c3cc265f440b827c555747ed6df82b811ebac | noamm19-meet/meet2017y1lab6 | /part4.py | 1,123 | 4.03125 | 4 | import turtle
UP_ARROW='Up'
LEFT_ARROW='Left'
DOWN_ARROW='Down'
RIGHT_ARROW='Right'
SPACEBAR='space'
UP=0
LEFT=1
DOWN=2
RIGHT=3
direction=UP
def up():
global direction
direction=UP
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x , y+10)
print(turtle.pos())
print('you pressed up')
def left():
global direction
direction=LEFT
print('you pressed left')
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x-10 , y)
print(turtle.pos())
def down():
global direction
direction=DOWN
print('you pressed down')
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x , y-10)
print(turtle.pos())
def right():
global direction
direction=RIGHT
print('you pressed right')
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x+10 , y)
print(turtle.pos())
turtle.onkeypress(up, UP_ARROW)
turtle.onkeypress(down, DOWN_ARROW)
turtle.onkeypress(left, LEFT_ARROW)
turtle.onkeypress(right, RIGHT_ARROW)
turtle.listen()
turtle.mainloop()
|
76f3d4905ac4e6d1900f10595b2988390317f54e | Himanshu1222/Perceptronalgorithm | /perceptron.py | 9,272 | 4.09375 | 4 | #Daniel Fox
#Student ID: 201278002
#Assignment 1: COMP527
import numpy as np
import random #redundant unless random.seed/random shuffle is used
class Data(object):
"""Main class which focuses on reading the dataset and sorting the data into samples,features.
filleName = name of file in string format.
Using dictionary and arrays to store the split the data between output feature y and sample x.
Dictionary makes it easy to select what classes to use when it comes to classification discrimination.
Using random to shuffle on the file data will help determine how well the algorithm performs when it is not fed with the data,
it has been commented out to make it easier to test the program.
"""
def __init__(self,fileName):
#open the file and split \n lines
self.fileData = open(fileName).read().splitlines()
self.data=[]#store all final data in the list
# randomise data set
random.seed(2)
random.shuffle(self.fileData)
temp=[]#sort out y values while looping
for i,j in enumerate(self.fileData):
#split the data between x and y
split=j.split(',class-')#split the class labels [0]=x , [1]=y
#sample data parsed out as float instead of string
x=np.array(split[0].split(',')).astype(float)#couldnt split data using numpy
y=split[1]
if y not in temp:
np.append(temp,y)
#append the samples and features into a data list.
self.data.append({'x': x, 'class-id': y})#append the dictionary
#samples
self.row = len(self.data[0]["x"]) #calculate length of each row = (4)
class Perceptron(object):
""" Create Perceptron for Assignment
Implimenting the perceptron is part of Question 2
pos is the positive class (+1)
neg is the negative class (-1) neg is set default at false so if user doesnt select a negative class number then it performs the 1 vs rest approach for question 3 and 4.
maxIter= max iteration loop to train the perceptron
D=Data class which will pass the relative information into the perceptron functions. Train data / Test data
regularisationFactor= regularisation coefficent allows user to input regularisation coefficent for question 4. It is default set to 0 for questions 2,3,4.
perceptronTrain = Uses the trianing data and calculate the weights
perceptronTest= Once training is complete test the trained perceptron with the training data using the new weights calculated.
"""
def __init__(self, pos, neg=None,maxIter=20):
self.pos = pos #positive class
self.neg = neg #negative class
self.maxIter=maxIter
def perceptronTrain(self,D,regularisationFactor = 0):
weights = np.zeros(D.row)#adding bias value and create weigths set to zero
bias=1
y = parseClassLabels(D,self.pos,self.neg)#call class function which returns the expected output values
#loop through iterations which is at 20 for assignment
for j in range(self.maxIter):
correct,incorrect=0,0 #used to find testing accuracy
#loop through the lengths of dataset
for i in range(len(D.data)):
x = D.data[i]["x"]#go through each x values
activation=np.sign(np.dot(weights,x)+bias)#activation function to determine if weights need updating
if y[i]==0: pass #first look to ignore any outputs which are set at 0
elif activation==y[i]:#then check if activation and expected output match
correct+=1
elif y[i]* activation <= 0:#update condition
#update weights formula added (1-2*regularisationFactor) cancels out while set to 0
weights=(1- 2*regularisationFactor)*weights + y[i]*x
bias+=y[i]
incorrect+=1
else:
incorrect+=1
self.weights=weights
self.accuracy=correct/(correct+incorrect)*100 #working out accuracy
return self.accuracy #return accuracy for printing data in terminal
def perceptronTest(self, D):
# get labels for test dataset
y = parseClassLabels(D,self.pos,self.neg)#get expected outputs for testing data
correct,incorrect = 0,0
#loop through the lengths of dataset
for i in range(len(D.data)):
x = D.data[i]['x']#go through each x values
activation=np.sign(np.dot(self.weights,x))#activation function to determine output
if y[i]==0:pass #check if the expected output values are 0 then dont do anything
elif y[i]==activation:#activation and expected output match
correct += 1
else:
incorrect += 1
self.accuracy=correct/(correct+incorrect)*100#calc accuracy
return self.accuracy#return accuracy for printing data in terminal
#Used to sort class labels and allow 1vs all approach
#note didnt work while in data class
def parseClassLabels(D,pos,neg):
#sets the class label relating to the dataset D.
y = {}#Store the classes in dictionary
for i in range(len(D.data)):
classNum = D.data[i]["class-id"]
if classNum == pos: #as user inputs a pos value this will become +1
y[i] = 1 #key i and value 1
elif neg: #as user inputs a neg value this will become -1
y[i] = -1 if classNum == neg else 0
else:y[i] = -1 #fix for 1vsall method , saved remaking a new function
return y
def main():
"""The main function runs all questions and prints accuracy to user.
Question 2:
Impliment the Perceptron class.
Question 3 compare:
class 1 and 2
class 2 and 3
class 1 and 3
Question 4:
Compare 1 vs all
Question 5:
add regularisation coefficent values to the 1 vs all appoach
regularisation coefficent:
[0.01, 0.1, 1.0, 10.0, 100.0]
"""
print("-------------Question 2 and 3-------------------")
train_data = Data("train.data")
train_1 = Perceptron("1","2")
train_2 = Perceptron("2","3")
train_3 = Perceptron("1","3")
print("Training Perceptron")
train_1.perceptronTrain(train_data)
train_2.perceptronTrain(train_data)
train_3.perceptronTrain(train_data)
train=[train_1,train_2,train_3]
for i in train:
print("Training Accuracy rate:%.2f%%"%i.accuracy)
test_data = Data("test.data")
print("\nTesting data")
train_1.perceptronTest(test_data)
train_2.perceptronTest(test_data)
train_3.perceptronTest(test_data)
for i in train:
print("Testing Accuracy rate:%.2f%%"%i.accuracy)
print("-----------------------------------------------")
print("----------------Question 4---------------------")
train_data = Data("train.data")
train_1 = Perceptron("1")
train_2 = Perceptron("2")
train_3 = Perceptron("3")
print("Training Perceptron")
train_1.perceptronTrain(train_data)
train_2.perceptronTrain(train_data)
train_3.perceptronTrain(train_data)
train=[train_1,train_2,train_3]
for i in train:
print("Training Accuracy rate:%.2f%%"%i.accuracy)
test_data = Data("test.data")
print("\nTesting data")
train_1.perceptronTest(test_data)
train_2.perceptronTest(test_data)
train_3.perceptronTest(test_data)
for i in train:
print("Testing Accuracy rate:%.2f%%"%i.accuracy)
print("-----------------------------------------------")
print("--------------Question 5-----------------------")
train_data = Data("train.data")
regularisation = [0.01, 0.1, 1.0, 10.0, 100.0]
train_1 = Perceptron("1")
train_2 = Perceptron("2")
train_3 = Perceptron("3")
test_data = Data("test.data")
print("Testing data")
for i in (regularisation):
print("\nRegularisation factor:%.2f\n"%i)
train_1.perceptronTrain(train_data,i)
#print("Training Accuracy rate:%.2f%%"%train_1.accuracy)#testing the training accuracy
train_1.perceptronTest(test_data)
print("Testing Accuracy rate:%.2f%%"%train_1.accuracy)
train_2.perceptronTrain(train_data,i)
#print("Training Accuracy rate:%.2f%%"%train_2.accuracy)#testing the training accuracy
train_2.perceptronTest(test_data)
print("Testing Accuracy rate:%.2f%%"%train_2.accuracy)
train_3.perceptronTrain(train_data,i)
#print("Training Accuracy rate:%.2f%%"%train_3.accuracy)#testing the training accuracy
train_3.perceptronTest(test_data)
print("Testing Accuracy rate:%.2f%%"%train_3.accuracy)
print("-----------------------------------------------")
if __name__ == '__main__':
main() |
170ba09d016d552111884a9a8802caf57c38d5a7 | gvsurenderreddy/software | /wprowadzenie_python/lotto.py | 187 | 3.75 | 4 | #!/usr/bin/env python
from random import randint
lista = []
def lotto():
a = randint(1,49)
if a not in lista:
lista.append(a)
else:
lotto()
for x in range(6):
lotto()
print lista
|
884c0ecc5e544b25657765b55c64c13b6b22ed96 | randyLobb/Rock-Ppapper-Scissors | /RPS.py | 1,577 | 4.09375 | 4 | import random
from random import randint
repeat = True
cursewords = ['fuckyou','fuck you', 'FuckYou', 'fuck','shit','fucker']
while repeat:
user_choice = input("Rock(1), Paper(2), Scisors(3): Type 1, 2, or 3. type exit to close the game: ")
Comp_choice = randint(1,3)
if user_choice == "exit":
break
if user_choice in cursewords:
print("well " + user_choice + " too!!!")
elif user_choice not in['1','2','3']:
print("I told you to type 1, 2 , or 3!")
elif int(user_choice) == 1 and Comp_choice == 1:
print("both chose Rock.it's a tie!")
elif int(user_choice) == 2 and Comp_choice == 2:
print("both chose Paper.it's a tie!")
elif int(user_choice) == 3 and Comp_choice == 3:
print("both chose scissors. It's a tie!")
elif int(user_choice) == 1 and Comp_choice == 2:
print("Computer chose paper, computer wins!")
elif int(user_choice) == 1 and Comp_choice == 3:
print("Computer chose scissors. you win!")
elif int(user_choice) == 2 and Comp_choice == 1:
print("Computer chose Rock. you win!")
elif int(user_choice) == 2 and Comp_choice == 3:
print("Computer chose sciccors. Computer wins!")
elif int(user_choice) == 3 and Comp_choice == 1:
print("Computer chose Rock. Computer Wins")
elif int(user_choice) == 3 and Comp_choice == 2 :
print("Computer chose paper. you Win!")
else:
print("I guess you can't follow simple instructions...")
print("Thanks for playing!")
|
688ef8d0f61313d828492d10031c888a65187803 | bonaert/NeuralNet | /xor.py | 876 | 3.5 | 4 | import random
from NeuralNet import NeuralNet
data = {
(0, 0): 0,
(0, 1): 1,
(1, 0): 1,
(1, 1): 0
}
TRAINING_SAMPLES = 10000
network = NeuralNet(input_size=2, hidden_layer_size=3, output_size=1, learning_rate=0.75, momentum=0.4)
# Step 1: training
samples = list(data.items())
errors = []
for i in range(TRAINING_SAMPLES):
neural_net_input, result = random.choice(samples)
error = network.train(neural_net_input, result)
errors.append(abs(error))
# Step 2: test
final_errors = []
for neural_net_input, result in data.items():
prediction = network.predict(neural_net_input)[0]
print("Input: ", neural_net_input, " -> Output: ",prediction)
final_errors.append(abs(result - prediction))
avg_error = sum(final_errors) / len(final_errors)
print("Average error: ", avg_error)
import matplotlib.pyplot as plt
plt.plot(errors)
plt.show() |
5648e2935a971992a4ccb03aae3c7b474318fb39 | uriyapes/VCL_DC | /my_utilities.py | 3,186 | 3.765625 | 4 | import os
import logging
from datetime import datetime
def set_a_logger(log_name='log', dirpath="./", filename=None, console_level=logging.DEBUG, file_level=logging.DEBUG):
"""
Returns a logger object which logs messages to file and prints them to console.
If you want to log messages from different modules you need to use the same log_name in all modules, by doing so
all the modules will print to the same files (created by the first module).
By default, when using the logger, every new run will generate a new log file - filename_timestamp.log.
If you wish to write to an existing file you should set the dirpath and filename params to the path of the file and
make sure you are the first to call set_a_logger with log_name.
:param log_name: The logger name, use the same name from different modules to write to the same file. In case no filename
is given the log_name will used to create the filename (timestamp and .log are added automatically).
:param dirpath: the logs directory.
:param filename: if value is specified the name of the file will be filename without any suffix.
:param console_level: logging level to the console (screen).
:param file_level: logging level to the file.
:return: a logger object.
"""
assert type(log_name) == str
assert type(dirpath) == str or type(dirpath) == unicode
assert type(console_level) == int
assert type(file_level) == int
if filename:
assert type(filename) == str
else:
timestamp = "_" + str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
filename = log_name + timestamp + ".log"
filepath = os.path.join(dirpath, filename)
# create logger
logger = logging.getLogger(log_name)
logger.setLevel(level=logging.DEBUG)
if not logger.handlers:
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(console_level)
fh = logging.FileHandler(filepath)
fh.setLevel(file_level)
# create formatter
formatter = logging.Formatter('%(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
logger.addHandler(fh)
# 'application' code
logger.critical('Logging level inside file is: {}'.format(logging._levelNames[file_level]))
return logger
if __name__ == '__main__':
# Test the logger wrap function - write inside log.log
logger_name = 'example'
dirpath = "./Logs"
logger = set_a_logger(logger_name, dirpath)
logger.debug('log')
# Test the logger wrap function - create a different log file and write inside it
logger_name = 'example2'
logger2 = set_a_logger(logger_name, dirpath)
logger2.debug('log2')
# Test that getting the logger from different module is possible by writing to the same file the logger used.
logger2_diff_module = set_a_logger(logger_name)
logger2_diff_module.debug('example2_diff_module')
|
e43348c97ff6d6b0ce16c9cb90d133038eb9b2a5 | optirg-39/dailycode | /F_450_58.py | 182 | 4.125 | 4 | Print all the duplicates in the input string?
#Using Hashing
r="Rishabhrishabh"
def strigduplcate(S):
d={}
for i in S:
d[i]=S.count(i)
print(strigduplcate(r))
|
6b17a0b06b3d25f439cc2951da7c0bf2528e7ffc | marialui/ADS | /quick sort.py | 674 | 3.703125 | 4 | def partition(lista,p,r):
x=lista[r]
i= p-1
for j in range (p,r):
if lista[j]< x:
i=i+1
estremo=lista[i]
lista[i] = lista[j]
lista[j]= estremo
lista[i+1], lista[r] = lista[r] , lista[i+1]
return (i+1)
#x, y = y, x is a good way to exchange variables values.
def quick_sort(lista,p,r):
if p<r:
q= partition(lista,p,r)
print('sortint on', lista[p:q - 1])
quick_sort(lista,p,q-1)
print(lista[p:q - 1])
print('sortint on', lista[q + 1:r])
quick_sort(lista, q+1,r)
array=[2,8,7,1,3,5,6,4]
quick_sort(array,0,len(array)-1)
print(array) |
f30b7b68b9b3fbfa14adc4bd4981e2b7a5bdc492 | nav-bajaj/python-course | /Intro Course/counting in a loop.py | 159 | 3.9375 | 4 | #counting in a loop
i = 0
print("Before",i)
for counter in [5,21,34,5,4,6,12,3445,4432]:
i=i+1
print(i,counter)
print("Done, total items:", i)
|
d52a1639d49854a0bc7846e74faa1d0051768da3 | CarlosTrejo2308/TestingSistemas | /ago-dic-2019/practicas/practica.py | 321 | 3.546875 | 4 | import math
def v_cilindro(radio = None, altura = None):
if radio == None:
radio = float( input("Radio: ") )
if altura == None:
altura = float( input("Volumen: ") )
volumen = math.pi * (math.pow(radio, 2)) * altura
return volumen
print(v_cilindro())
|
86a414b4486661edeca46d5b53e76d00704861c0 | marcluettecke/programming_challenges | /python_scripts/floor_puzzle.py | 2,170 | 4.09375 | 4 | """
Function to solve the following puzzle with a generator.
------------------
User Instructions
Hopper, Kay, Liskov, Perlis, and Ritchie live on
different floors of a five-floor apartment building.
Hopper does not live on the top floor.
Kay does not live on the bottom floor.
Liskov does not live on either the top or the bottom floor.
Perlis lives on a higher floor than does Kay.
Ritchie does not live on a floor adjacent to Liskov's.
Liskov does not live on a floor adjacent to Kay's.
Where does everyone live?
Write a function floor_puzzle() that returns a list of
five floor numbers denoting the floor of Hopper, Kay,
Liskov, Perlis, and Ritchie.
"""
# imports
import itertools
def is_adjacent(floor1, floor2):
"""
Function to determine if two floors are adjacent.
Args:
floor1: [int] level of floor 1
floor2: [int] level of floor 2
Returns:
[bool] if two floors are adjacent
"""
return abs(floor1 - floor2) == 1
def floor_puzzle():
"""
Function to include a bunch of restrictions on 5 inhabitants and find the solution by brute force or possible
permutations.
Returns:
[List] of the five floor numbers for the five people in the order: [Hopper, Kay, Liskov, Perlis, Ritchie]
"""
floors = bottom, _, _, _, top = [1, 2, 3, 4, 5]
orderings = list(itertools.permutations(floors))
return next([Hopper, Kay, Liskov, Perlis, Ritchie]
for [Hopper, Kay, Liskov, Perlis, Ritchie] in orderings
# Hopper does not live on the top floor.
if Hopper is not bottom
# Kay does not live on the bottom floor.
if Kay is not bottom
# Liskov does not live on either the top or the bottom floor.
if Liskov not in [bottom, top]
# Perlis lives on a higher floor than does Kay.
if Perlis > Kay
# Ritchie does not live on a floor adjacent to Liskov's.
if is_adjacent(Ritchie, Liskov) == False
# Liskov does not live on a floor adjacent to Kay's.
if is_adjacent(Liskov, Kay) == False)
|
3168d9379b4ff8064b60ed5e6db65d504c91f5a0 | marcluettecke/programming_challenges | /python_scripts/rot13_translation.py | 482 | 4.125 | 4 | """
Function to shift every letter by 13 positions in the alphabet. Clever use of maketrans and translate.
"""
trans = str.maketrans('ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
def rot13(message):
"""
Translation by rot13 encoding.
Args:
message: string such as 'Test'
Returns:
translated string, such as 'Grfg'
"""
return message.translate(trans)
|
9694eb43b3219502319ca40dbf580a88bf309c85 | khaleeque-ansari/CodeChef-Problem-Solutions-Python | /Python Codes/HS08TEST.py | 255 | 3.671875 | 4 |
amount, balance = [float(x) for x in raw_input().split()]
if amount%5 != 0:
print '%.2f' %balance
elif amount > balance - 0.50:
print '%.2f' %balance
else :
print '%.2f' % (balance - amount - 0.50)
|
ae038beb027640e3af191d24c6c3abbb172e398e | mihaidobri/DataCamp | /SupervisedLearningWithScikitLearn/Classification/02_TrainTestSplit_FitPredictAccuracy.py | 777 | 4.125 | 4 | '''
After creating arrays for the features and target variable, you will split them into training and test sets,
fit a k-NN classifier to the training data, and then compute its accuracy using the .score() method.
'''
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
# Create feature and target arrays
X = digits.data
y = digits.target
# Split into training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=42, stratify=y)
# Create a k-NN classifier with 7 neighbors: knn
knn = KNeighborsClassifier(n_neighbors = 7)
# Fit the classifier to the training data
knn.fit(X_train,y_train)
# Print the accuracy
print(knn.score(X_test, y_test))
|
e03ee23d27385f92bde5067aa3158823807ac747 | ismael-lopezb/employee_class_project | /data_cleaning.py | 2,303 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 23:20:36 2021
@author: ismaellopezbahena
"""
#import usefull libraries
import pandas as pd
import numpy as np
#read csv file and get the info
df = pd.read_csv('aug_train.csv')
df.info()
#let's replace the gender missing data with the mode
gmode = df.gender.mode()[0]
df['gender'].fillna(gmode, inplace=True)
#fill missing data in enrolled university with the mode
df['enrolled_university'].fillna(df.enrolled_university.mode()[0], inplace=True)
#fill eduaction level missing values with the mode
df['education_level'].fillna(df.education_level.mode()[0], inplace=True)
#let's do the same with major discipline, experience, company size, company type, last new job
for column in df.columns:
df[column].fillna(df[column].mode()[0], inplace=True)
#make sure we don't have more missing data
df.info()
#let's see relevent experience values
df['relevent_experience'].value_counts()
#we have two values so let's make 'yes'=relevent experience and 'no'= no relevet experince
df['relevent_experience'] = df['relevent_experience'].apply(lambda x: 'Yes' if 'Has relevent experience' in x else 'No')
#let's see the unique values of enrolled_university
df['enrolled_university'].value_counts()
#we have 3 categories so leave it like that. Education level and major values
df['education_level'].value_counts()
df['major_discipline'].value_counts()
#we have 4 categories leave it as well with major discipline. We want experince to be int
#remove the < and > from experince
df['experience'] = df['experience'].apply(lambda x: x.replace('<', ''))
df['experience'] = df['experience'].apply(lambda x: x.replace('>', ''))
df['experience'] = df['experience'].astype(int)
#lets put compani size in the same format n-m
df['company_size'] = df['company_size'].apply(lambda x: x.replace('/', '-'))
#we want last-new job be an int
df['last_new_job']=df['last_new_job'].apply(lambda x: x.replace('+',''))
df['last_new_job']=df['last_new_job'].apply(lambda x: x.replace('>',''))
df['last_new_job']=df['last_new_job'].apply(lambda x: x.replace('never','0'))
df['last_new_job'] = df['last_new_job'].astype(int)
df.info()
#we don't have missing values and we get numerical and categorical data. Save it
df.to_csv('data_cleaned.csv', index=False)
|
34880def1217c10482dbbd3c637552fff0035ef3 | mishra-ankit-dev/tkinter-chat-automation | /chatApp/gui_chat.py | 1,659 | 3.625 | 4 | # -*- coding:utf-8 -*-
import sys
import time
import signal
import socket
import select
import tkinter
from tkinter import *
from threading import Thread
class client():
""" This class initializes client socket
"""
def __init__(self, server_ip = '0.0.0.0', server_port = 8081):
if len(sys.argv) != 3:
print("Correct usage: script, IP address, port number")
self.server_ip = server_ip
self.server_port = server_port
else:
self.server_ip = str(sys.argv[1])
self.server_port = int(sys.argv[2])
self.client_socket = socket.socket()
self.client_socket.connect((self.server_ip, self.server_port))
self.client_name = input('Enter your NAME : ')
#self.client_password = input('Enter your PASSWORD : ')
#self.client_info = {}
#self.client_info['client_name'] = self.client_name
#self.client_info['client_password'] = self.client_password
self.client_socket.sendall(self.client_name.encode())
def receive_data(self):
""" Receives data continously
"""
print('Starting receive thread')
while True:
self.data = self.client_socket.recv(1000)
print('server:', self.data)
def send_data(self):
""" This method sends the message to the server
"""
while True:
self.send_message = input()
self.client_socket.sendall(self.send_message.encode())
print('you :', self.send_message)
s = client()
t = Thread(target = s.receive_data)
t.start()
s.send_data()
|
52b60e4bba09587fefd57678440a8afe275b955c | chiachunho/NTNU_OOAD_Homework | /Homework1/Homework1-2/main.py | 1,133 | 3.703125 | 4 | from Triangle import Triangle
from Square import Square
from Circle import Circle
from ShapeDatabse import ShapeDatabase
# construct shapes
shape1 = Triangle(0, 1, 6)
shape2 = Square(2, 2, 4, side_length=2)
shape3 = Circle(3, 3, 5, radius=3)
shape4 = Circle(2, 3, 3, radius=4)
shape5 = Square(1, 2, 1, side_length=5)
shape6 = Triangle(3, 1, 2, side_length=6)
# construct database
db = ShapeDatabase()
# append shapes to database
db.append(shape1)
db.append(shape2)
db.append(shape3)
db.append(shape4)
db.append(shape5)
db.append(shape6)
# print amount to console
print(f'Shape amount in database: {len(db)}')
print('')
# iterate the database to get shape and print its info out
print('Print shape in database:')
for shape in db:
print(shape)
# sort the database
print('\nSort shapes in database by z-value.\n')
db.sort()
print('Print shape in database:')
for shape in db:
print(shape)
# clear database
print('\nClear database.\n')
db.clear()
print(f'Shape amount in database: {len(db)}')
if len(db) == 0:
print('Database is empty.')
# print(db.__shape_list) # shape_list is private variable can't direct access
|
f0d679d573068b5fc1f2d66b2f0d2c17824c22ed | mdzierzecki/algorithms | /binarytree/Node.py | 370 | 3.53125 | 4 | class Node:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def __str__(self):
return "{}".format(self.key)
|
cc0c510075db7641bd5ae83e88c52b248473d999 | nik-panekin/pyramid_puzzle | /button.py | 1,238 | 4.09375 | 4 | """Module for implementation the Button class.
"""
import pygame
from blinking_rect import BlinkingRect
class Button(BlinkingRect):
"""The Button class implements visual rectangular element with a text
inside. It can be used for GUI.
Public attributes:
caption: str (read only) - stores button caption as an identifier.
"""
def __init__(self, width: int, height: int, color: tuple, text: str,
text_color: tuple, font: pygame.font.Font):
"""Input:
width, height, color are the same as for RoundedRect constructor;
text - string value for button caption;
text_color - tuple(r: int, g: int, b: int) for button caption
color representation;
font - pygame.font.Font object for drawing text caption.
"""
super().__init__(width, height, color)
self.caption = text
self.text_surf = font.render(text, True, text_color)
self.text_rect = self.text_surf.get_rect()
def draw(self):
"""Draws the button.
"""
super().draw()
ds = pygame.display.get_surface()
self.text_rect.center = self.rect.center
ds.blit(self.text_surf, self.text_rect)
|
1bb64c12a5738bc206746e547ed525089aaf0742 | lux563624348/Python_Learn | /basic/OI.py | 965 | 3.796875 | 4 | ########################################################################
#### Reading and Writing Files
###### Xiang Li Feb.18.2017
########################################################################
########################################################################
##Module
########################################################################
# f = open(filename, mode)
def f_read (filename):
f = open (filename, 'r')
read_data = float( f.read())
f.close()
#print (read_data)
return read_data
#Mode: 'r' only be read, 't' text mode
# 'w' for only writing '+' a disk file for updating (Reading and writing)
# 'a' for appending 'U' universal newlines mode ???
# 'r+'reading and writing.
# 'b' binary mode For example, 'w+b'
# 2D data, t-x
def f_write (filename,t,x):
#print(len(t))
f = open (filename, 'w')
for i in range (len(t)):
f.write('%10.5f' % (t[i]))
f.write('%10.5f' % (x[i]))
f.close()
|
5ce316ef78144c1268521a913a494eead0b2baee | Yanhenning/python-exercises | /one/test_first_exercise.py | 1,213 | 3.65625 | 4 | from unittest import TestCase
from one.first_exercise import return_duplicated_items
class FirstExerciseTests(TestCase):
def test_return_empty_list_given_an_empty_list(self):
duplicated_items = return_duplicated_items([])
self.assertEqual([], duplicated_items)
def test_return_empty_list_given_an_array_without_duplicated_items(self):
duplicated_items = return_duplicated_items(list(range(20)))
self.assertEqual([], duplicated_items)
def test_should_return_the_duplicated_items(self):
duplicated_items = return_duplicated_items([1, 2, 1, 2, 3, 4])
self.assertEqual([1, 2], duplicated_items)
def test_return_duplicated_item_if_it_is_a_dict(self):
a = {'a': 1}
b = {'b': 2}
duplicated_items = return_duplicated_items([a, b, a])
self.assertEqual([a], duplicated_items)
def test_return_duplicated_item_if_it_is_a_object(self):
class foo:
def __init__(self):
self.a = 1
self.b = 2
a = {'a': 1}
b = {'b': 2}
c = foo()
duplicated_items = return_duplicated_items([a, b, a])
self.assertEqual([a], duplicated_items)
|
735e3a6325d2805d14e72615163138df6e79679f | Akawi85/Tiny-Python-Project | /03_picnic/picnic.py | 1,477 | 4.09375 | 4 | #!/usr/bin/env python3
"""
Author : Me <ifeanyi.akawi85@gmail.com>
Date : 31-10-2020
Purpose: A list of food for picnic!
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Picnic game',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('items',
metavar='str',
help='Item(s) to bring',
nargs='+')
parser.add_argument('-s',
'--sorted',
action='store_true',
help='sort the items',
default=False)
return parser.parse_args()
# --------------------------------------------------
def main():
"""The main program goes here"""
args = get_args()
items_arg = args.items
num_items = len(items_arg)
items_arg.sort() if args.sorted else items_arg
items_in_picnic = str()
if num_items == 1:
items_in_picnic = items_arg[0]
elif num_items == 2:
items_in_picnic = ' and '.join(items_arg)
elif num_items > 2:
items_arg[-1] = 'and ' + items_arg[-1]
items_in_picnic = ', '.join(items_arg)
print(f'You are bringing {items_in_picnic}.')
# --------------------------------------------------
if __name__ == '__main__':
main()
|
e650ddccebf0c6e1e97ee8c934e7c12948d299ab | BoHyeonPark/test1 | /028.py | 393 | 3.546875 | 4 | #!/usr/bin/python3
seq1 = "ATGTTATAG"
new_seq = ""
seq_dic = {"A":"T","T":"A","C":"G","G":"C"}
for i in seq1:
new_seq += seq_dic[i]
print(seq1)
print(new_seq)
new_seq1 = ""
for i in seq1:
if i == "A":
new_seq1 += "T"
elif i == "T":
new_seq1 += "A"
elif i == "C":
new_seq1 += "G"
elif i == "G":
new_seq1 += "C"
print(seq1)
print(new_seq1)
|
c18490e52668ed9fc558ab7e4c1438dccd72427c | BoHyeonPark/test1 | /029.py | 207 | 3.53125 | 4 | #!/usr/bin/python3
seq1 = "ATGTTATAG"
print("C" in seq1)
for s in seq1:
b = (s == "C") #s == "C" -> False
print(s,b)
if b:
break
import re
p = re.compile("C")
m = p.match(seq1)
print(m)
|
cf7706deabaa3e1f59c8bb31bf34980cee4ea881 | BoHyeonPark/test1 | /014.py | 112 | 3.890625 | 4 | #!/usr/bin/python3
a = input("Enter anything: ")
if a.isalpha():
print("alphabet")
else:
print("digit")
|
cb8c1db76f1c7184635920f5811c56141929dbbf | BoHyeonPark/test1 | /034.py | 378 | 3.96875 | 4 | #!/usr/bin/python3
l = [3,1,1,2,0,0,2,3,3]
print(max(l))
print(min(l))
for i in range(0,len(l),1):
if i == 0: #set max_val, min_val
max_val = l[i]
min_val = l[i]
else:
if max_val < l[i]:
max_val = l[i] #max_val change
if min_val > l[i]:
min_val = l[i] #min_val change
print("max:",max_val)
print("min:",min_val)
|
c891cd0f585b21859cfde5ffc0ef3aa77dbf2401 | BoHyeonPark/test1 | /assignment1_3.py | 111 | 3.515625 | 4 | #!/usr/bin/python3
try:
n = input("Enter number: ")
print(10/n)
except TypeError:
print("no zero")
|
3cada4756c6fd7259becea52725a3b85a0d7c25d | maxalbert/micromagnetic-standard-problem-ferromagnetic-resonance_v3_rewrite | /src/postprocessing/util.py | 1,478 | 3.96875 | 4 | def get_conversion_factor(from_unit, to_unit):
"""
Return the conversion factor which converts a value given in unit
`from_unit` to a value given in unit `to_unit`.
Allowed values for `from_unit`, `to_unit` are 's' (= second), 'ns'
(= nanosecond), 'Hz' (= Hertz) and 'GHz' (= GigaHertz). An error
is raised if a different unit is given.
Example:
>>> get_conversion_factor('s', 'ns')
1e9
"""
allowed_units = ['s', 'ns', 'Hz', 'GHz']
if not set([from_unit, to_unit]).issubset(allowed_units):
raise ValueError("Invalid unit: '{}'. Must be one of " + ", ".join(allowed_units))
return {('s', 's'): 1.0,
('s', 'ns'): 1e9,
('ns', 's'): 1e-9,
('ns', 'ns'): 1.0,
('Hz', 'Hz'): 1.0,
('Hz', 'GHz'): 1e-9,
('GHz', 'Hz'): 1e9,
('GHz', 'GHz'): 1.0}[(from_unit, to_unit)]
def get_index_of_m_avg_component(component):
"""
Internal helper function to return the column index for the x/y/z component
of the average magnetisation. Note that indices start at 1, not zero,
because the first column contains the timesteps.
(TODO: This may be different for other data types, though!)
"""
try:
idx = {'x': 1, 'y': 2, 'z': 3}[component]
except KeyError:
raise ValueError(
"Argument 'component' must be one of 'x', 'y', 'z'. "
"Got: '{}'".format(component))
return idx
|
34c657d098bd5e80640c4da17189022219528c7e | zhangchuan92910/cmpt419 | /k_nearest_neighbor.py | 2,899 | 3.609375 | 4 | import numpy as np
from math import log10, floor
from collections import defaultdict
import os
from utils import *
def round_to_1(x):
return round(x, -int(floor(log10(abs(x)))))
def compute_distances(X1, X2, name="dists"):
"""Compute the L2 distance between each point in X1 and each point in X2.
It's possible to vectorize the computation entirely (i.e. not use any loop).
Args:
X1: numpy array of shape (M, D) normalized along axis=1
X2: numpy array of shape (N, D) normalized along axis=1
Returns:
dists: numpy array of shape (M, N) containing the L2 distances.
"""
M = X1.shape[0]
N = X2.shape[0]
assert X1.shape[1] == X2.shape[1]
dists = np.zeros((M, N))
print("Computing Distances")
if os.path.isfile(name+".npy"):
dists = np.load(name+".npy")
else:
benchmark = int(round_to_1(M)//10)
for i in range(len(X1)):
for j in range(len(X2)):
dists[i,j] = np.linalg.norm(X1[i] - X2[j])
if i % benchmark == 0:
print(str(i//benchmark)+"0% complete")
np.save(name, dists)
print("Distances Computed")
return dists
def predict_labels(dists, y_train, y_val, k=1):
"""Given a matrix of distances `dists` between test points and training points,
predict a label for each test point based on the `k` nearest neighbors.
Args:
dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives
the distance betwen the ith test point and the jth training point.
Returns:
y_pred: A numpy array of shape (num_test,) containing predicted labels for the
test data, where y[i] is the predicted label for the test point X[i].
"""
num_test, num_train = dists.shape
y_pred = defaultdict(list)
for i in range(num_test):
closest_y = y_train[np.argpartition(dists[i], k-1)[:k]]
occur = np.bincount(closest_y)
top = sorted(enumerate(occur), key=lambda a: a[1], reverse=True)
y_pred[y_val[i]].append([cat for cat, _ in top[:3]])
return y_pred
def predict_labels_weighted(dists, y_train, y_val, k=1):
num_test, num_train = dists.shape
y_pred = defaultdict(list)
idx_to_cat, _ = get_category_mappings()
for i in range(num_test):
indices = np.argpartition(dists[i], k-1)[:k]
closest = sorted([(y_train[j], dists[i][j]) for j in indices], key=lambda a: a[1])
weights = np.linspace(1.0, 0.0, k)
votes = defaultdict(float)
for j in range(k):
votes[closest[j][0]] += 1.0/np.sqrt(1.0*j+1.0) #1.0/closest[j][1] #1.0/np.sqrt(1.0*j+1.0) #weights[j]
top = [(j, votes[j]) for j in sorted(votes, key=votes.get, reverse=True)]
y_pred[idx_to_cat[y_val[i]]].append([idx_to_cat[cat] for cat, _ in top[:3]])
return y_pred
|
56df42f25fc0a3dddd57a8d70c63d7a3a4754900 | devmadhuu/Python | /assignment_01/check_substr_in_str.py | 308 | 4.34375 | 4 | ## Program to check if a Substring is Present in a Given String:
main_str = input ('Enter main string to check substring :')
sub_str = input ('Enter substring :')
if main_str.index(sub_str) > 0:
print('"{sub_str}" is present in main string - "{main_str}"'.format(sub_str = sub_str, main_str = main_str))
|
92d2b840f03db425aaaedf22ad57d0b291bb79e6 | devmadhuu/Python | /assignment_01/odd_in_a_range.py | 505 | 4.375 | 4 | ## Program to print Odd number within a given range.
start = input ('Enter start number of range:')
end = input ('Enter end number of range:')
if start.isdigit() and end.isdigit():
start = int(start)
end = int(end)
if end > start:
for num in range(start, end):
if num % 2 != 0:
print('Number {num} is odd'.format(num = num))
else:
print('End number should be greater than start number !!!')
else:
print('Enter valid start and end range !!!') |
020278f3785bb409de5cd0afd67c4ccaf295e011 | devmadhuu/Python | /assignment_01/three_number_comparison.py | 1,464 | 4.21875 | 4 | ## Program to do number comparison
num1 = input('Enter first number :')
if num1.isdigit() or (num1.count('-') == 1 and num1.index('-') == 0) or num1.count('.') == 1:
num2 = input('Enter second number:')
if num2.isdigit() or (num2.count('-') == 1 and num2.index('-') == 0) or num2.count('.') == 1:
num3 = input('Enter third number:')
if num3.isdigit() or (num3.count('-') == 1 and num3.index('-') == 0) or num3.count('.') == 1:
if num1.count('.') == 1 or num2.count('.') == 1 or num3.count('.') == 1:
operand1 = float(num1)
operand2 = float(num2)
operand3 = float(num3)
else:
operand1 = int(num1)
operand2 = int(num2)
operand3 = int(num3)
if operand1 > operand2 and operand1 > operand3:
print('{operand1} is greater than {operand2} and {operand3}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3))
elif operand2 > operand1 and operand2 > operand3:
print('{operand2} is greater than {operand1} and {operand3}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3))
else:
print('{operand3} is greater than {operand1} and {operand2}'.format(operand1 = operand1, operand2 = operand2, operand3 = operand3))
else:
print('Enter valid numeric input')
else:
print('Enter valid numeric input') |
bca391936ad2f918c4700dc581de7558dd081f41 | devmadhuu/Python | /assignment_01/ljust_rjust_q18.py | 409 | 3.6875 | 4 | my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.'
sub_str = 'Peck'
index = 0
str_index = -1
replaced_str = ''
while my_str[index:]:
check_str = my_str[index:index + len(sub_str)]
if check_str == sub_str:
replaced_str = sub_str.rjust(index+1, '*')
replaced_str+=sub_str.ljust(len(my_str) - (index + 1 + len(sub_str)), '*')[len(sub_str):]
break
index+=1
print(replaced_str) |
66c8afbcdd793b3817993abfb904b4ec0111f666 | devmadhuu/Python | /assignment_01/factorial.py | 410 | 4.4375 | 4 | ## Python program to find the factorial of a number.
userinput = input ('Enter number to find the factorial:')
if userinput.isdigit() or userinput.find('-') >= 0:
userinput = int(userinput)
factorial = 1
for num in range (1, userinput + 1):
factorial*=num
print('Factorial of {a} is {factorial}'.format(a = userinput, factorial = factorial))
else:
print('Enter valid numeric input') |
83c5184a88d030bfd7d873e728653ac1f0248245 | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio04.py | 1,195 | 4.28125 | 4 | '''
Tenemos que decidir entre 2 recetas ecológicas.
Los ingredientes para cada tipo de receta aparecen a continuación.
Ingredientes comunes: Verduras y berenjena.
Ingredientes Receta 1: Lentejas y apio.
Ingredientes Receta 2: Morrón y Cebolla..
Escribir un programa que pregunte al usuario que tipo de receta desea,
y en función de su respuesta le muestre un menú con los ingredientes
disponibles para que elija. Solo se puede eligir 3 ingrediente
(entre la receta elegida y los comunes.) y el tipo de receta.
Al final se debe mostrar por pantalla la receta elegida y todos los ingredientes.
'''
ingredientes_receta1 = "Lenjetas y Apio"
ingredientes_receta2 = "Morrón y Cebolla"
print ("""
*******************************
Menu:
Receta 1: Lentejas y Apio.
Receta 2: Morrón y Cebolla.
*******************************
""")
receta = int(input("Indique si quiere la receta (1) o (2): "))
comun = int(input("Queres agregar Verduras (1) o Berenjenas (2)?"))
if comun == 1:
comun = "Verduras"
else:
comun = "Berenjenas"
if receta == 1:
receta = ingredientes_receta1
else:
receta = ingredientes_receta2
print(f"Su plato tiene los siguientes ingredientes: {comun}, {receta}.") |
e4fe2f3a2fcb0f61de0a04aa746de174b64c9256 | alee86/Informatorio | /Practic/Estructuras de control/Complementarios/Complementarios4.py | 325 | 3.90625 | 4 | """
Realizar un programa que sea capaz de, habiéndose ingresado dos números m y n, determine si n es divisor de m.
"""
m = int(input("Ingrese el valor para el numerador "))
n = int(input("Ingrese el valor para el denominador "))
if m%n == 0:
print(f"{n} es DIVISOR de {m}")
else:
print(f"{n} es NO es DIVISOR de {m}")
|
213dab8cccc5a3d763c4afd329e6a461bb920b01 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio04.py | 973 | 4.03125 | 4 | '''
DESAFÍO 4
Escriba un programa que permita imprimir un tablero Ecológico (verde y blanco) de
acuerdo al tamaño indicado. Por ejemplo el gráfico a la izquierda es el resultado
de un tamaño: 8x6
import os
os.system('color')
columna = int(input("ingrese columnas: "))
fila = int(input("ingrese filas: "))
for fila in range(fila):
for i in range(columna):
if i%2 != 0:
print("I", end=" ")
else:
print("P", end=" ")
print()
'''
import os
os.system('color')
columna = int(input("Ingrese numero de columnas: "))
filas = int(input("Ingrese numero de filas : "))
for f in range(filas):
if f%2 == 0: #Evaluo que las filas pares inicien con P
for c in range(columna):
if c%2 == 0:
print("\033[1;32;40m[V]", end ="")
else:
print("\033[93m[B]",end ="")
else: #Evaluo que las filas impares inicien con I
for c in range(columna):
if c%2 == 0:
print("\033[1;37;44m[V]", end ="")
else:
print("\033[91m[B]",end ="")
print() |
55efa3a71c684d8f68040ef917434b00a2bb589d | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio01.py | 793 | 4.09375 | 4 | '''
En nuestro rol de Devs (Programador o Programadora de Software), debemos elaborar un programa
en Python que permita emitir un mensaje de acuerdo a lo que una persona ingresa como
cantidad de años que viene usando insecticida en su plantación. Si hace 10 o más añoss,
debemos emitir el mensaje "Por favor solicite revisión de suelos en su plantación".
Si hace menos de 10 años, debemos emitir el mensaje "Intentaremos ayudarte con un nuevo
sistema de control de plagas, y cuidaremos el suelo de tu plantación".
'''
tiempo = float(input("Ingresa la cantidad de años:"))
if tiempo >= 10:
print("Por favor solicite revisión de suelos en su plantación")
else:
print("Intentaremos ayudarte con un nuevo sistema de control de plagas, y cuidaremos el suelo de tu plantación")
|
90965bb42e72a97fbea66ed53de0feff2eecc19c | alee86/Informatorio | /Practic/Listas/complementarios16.py | 1,164 | 4.03125 | 4 | '''
f. Se tiene una lista con los datos de los clientes de una compañía de telefonía celular,
los cuales pueden aparecer repetidos en la lista, si tienen registrado más de un número
telefónico. La compañía para su próximo aniversario desea enviar un regalo a sus clientes,
sin repetir regalos a un mismo cliente. En una lista se almacenan los regalos disponibles en
orden. Se desea un programa que cree una nueva lista con los clientes, sin repetir y ordenada.
que al final muestre el regalo que le corresponde a cada cliente.
'''
lista = ['Ale', 'Edu', 'Ari', 'Car', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada', 'Mauri', 'Dami',
'Fer', 'Guada', 'Mauri', 'Dami', 'Fer', 'Ari', 'Car', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada',
'Mauri', 'Ari', 'Car', 'Guada', 'Mauri', 'Dami', 'Fer', 'Guada', 'Mauri']
usuarios = []
delivery = []
regalos = ['birra', '$200', '4gb','abrazo', '$500', '2gb','Siga participando', '$200']
for i, element in enumerate(lista):
if element not in usuarios:
usuarios.append(element)
usuarios.sort()
for i in usuarios:
aux = usuarios[usuarios.index(i)] , regalos[usuarios.index(i)]
delivery.append(aux)
print(delivery) |
e23daf79dd41f1bce58bbaab7858941562be66ef | alee86/Informatorio | /Practic/Listas/complementarios12.py | 437 | 3.9375 | 4 | '''
b. Leer una frase y luego invierta el orden de las palabras en la frase. Por Ejemplo:
“una imagen vale por mil palabras” debe convertirse en “palabras mil por vale imagen una”.
'''
frase = str(input('Ingrese una frase para verla invrertida: '))
lista = frase.split()
#el metodo split toma un string y lo divide segun lo que pongas en () creando una lista
lista.reverse()
for i in lista:
print(i, end=" ")
#print(palabra) |
77329d1eb28a5d3565a346a30047871d2306abc6 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio01.py | 1,484 | 4.21875 | 4 | '''
DESAFÍO 1
Nos han pedido desarrollar una aplicación móvil para reducir comportamientos inadecuados para el ambiente.
a) Te toca escribir un programa que simule el proceso de Login. Para ello el programa debe preguntar
al usuario la contraseña, y no le permita continuar hasta que la haya ingresado correctamente.
b) Modificar el programa anterior para que solamente permita una cantidad fija de intentos.
'''
enter_pass ="1"
true_pass = "123"
user_name = ""
intento = 1
enter_user_name = input("Ingresa tu usuario: ")
enter_pass = str(input("Ingresa tu pass: "))
if enter_pass == true_pass:
print("""
#########################################
Pass correcto... Ingresando a tu cuenta
#########################################""")
else:
print(f"El pass ingresado no es correcto. Tenes 2 intentos más")
enter_pass = str(input("Ingresa tu pass: "))
if enter_pass == true_pass:
print("""
#########################################
Pass correcto... Ingresando a tu cuenta
#########################################""")
else:
print(f"El pass ingresado no es correcto. Tenes 1 intentos más")
enter_pass = str(input("Ingresa tu pass: "))
if enter_pass == true_pass:
print("""
#########################################
Pass correcto... Ingresando a tu cuenta
#########################################""")
else:
print("""
#########################
No tenes mas intentos.
Tu cuenta esa bloqueada.
#########################""") |
dd112a464e3c0ad07c28a31b94b693d533f758b3 | alee86/Informatorio | /Practic/06distribucionEstudiantes.py | 470 | 3.84375 | 4 | name = ""
while name != "quite":
name = input("Ingresa tu nombre completo: ").upper()
turn = input("ingresa si sos del TT (Turno Tarde) o del TN (Turno Noche): ").upper()
letters = "ABCDEFGHIJKLMNÑOPQRSTUVWYZ"
ft_letra = name[0]
if (letters[0:13].find(ft_letra) >= 0 and turn == "TT") or (letters[13:25].find(ft_letra) >= 0 and turn == "TN"):
print(f"El estudiante",name,"pertenece al grupo A")
else :
print(f"El estudiante",name,"pertenece al grupo B") |
5112700bd8249864e978ed76dd52f85586fe848c | alee86/Informatorio | /Practic/Profe y compañeros/Desafio3.py | 1,400 | 4.09375 | 4 | '''Para el uso de fertilizantes es necesario medir cuánto abarca un determinado compuesto en el suelo el cual debe existir en una cantidad
de al menos 10% por hectárea, y no debe existir vegetación del tipo MATORRAL. Escribir un programa que determine si es factible la
utilización de fertilizantes.'''
print("Iniciando programa para calculo de utilización de fertilizantes.")
hectarea = bool(int(input("¿Usted ya midio el suelo?\n\t 1- Verdadero \n\t 0- Falso\n")))
if hectarea:
compuesto = bool(int(input("¿El compuesto existe en al menos de 10% por hectarea?\n\t 1- Verdadero \n\t 0- Falso\n")))
vegetacion = bool(int(input("¿Existe vegetacion del tipo Matorral?\n\t 1- Verdadero \n\t 0- Falso\n ")))
if compuesto and vegetacion:
print("El uso de del fertilizante es factible.")
elif compuesto and vegetacion:
print("Debe exterminar la vegetacion del tipo Matorral para que el fertilizante sea factible. ")
elif compuesto and vegetacion:
print("Procure que almenos usar el fertilizante cubra un 10", "% " ,"de la hectarea para que sea factible usarlo. ")
else:
print("Procure que almenos usar el fertilizante cubra un 10", "% " ,"de la hectarea para que sea factible usarlo." ,"\n\t y ", "\n Debe exterminar la vegetacion del tipo Matorral para que el fertilizante sea factible. ")
else:
print("Mida el suelo primero y luego vuelva a iniciar el programa. ")
|
2649df22c828074a1eff5bcace5a2bf86dc5db98 | alee86/Informatorio | /Practic/numerosPrimos.py | 216 | 3.890625 | 4 | num = int(input("Numero para evaluar: "))
contador = 0
for x in range(num):
if num%(x+1) == 0:
contador += 1
if contador > 2:
print(f"El número {num} NO es primo")
else:
print(f"El número {num} SI es primo")
|
dd1eb3db497541007cb6abc22addb58838732c45 | bp345sa/Fizz | /Ex 5.py | 553 | 3.53125 | 4 | name = 'Zed A. Shaw'
age = 23 # not a lie
height = 74 # inches
h1 = height * 2.54
weight = 180 # lbs
w1 = weight * 0.456
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %f centimetres tall." % h1
print "He's %f kilograms heavy." % w1
print "Actually that's not too heavy."
print "He's got %r eyes and %r" % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
# this line is tricky, try to get it exactly right
print "If I add %d, %f, and %f I get %f." % (age, h1, w1, age + h1 + w1)
|
edff8364358f12b7248f2adb0d61cf18a97c349b | dds-utn/patrones-comunicacion | /corutinas/generator.py | 165 | 3.6875 | 4 | def productor():
n = 0
while True:
yield n
n += 1
def consumidor(productor):
while True:
println(productor.next())
consumidor(productor())
|
372fb0a40da5ea72d757f22ca8ed239abc52910d | CompAero/Genair | /geom/aircraft.py | 2,040 | 3.78125 | 4 | from part import Part
__all__ = ['Aircraft']
class Aircraft(Part, dict):
''' An Aircraft is a customized Python dict that acts as root for
all the Parts it is composed of.
Intended usage
--------------
>>> ac = Aircraft(fuselage=fus, wing=wi)
>>> ac.items()
{'wing': <geom.wing.Wing at <hex(id(wi))>,
'fuselage': <geom.fuselage.Fuselage at <hex(id(fus))>}
>>> del ac['wing']
>>> ac['tail'] = tail
'''
def __init__(self, *args, **kwargs):
''' Form an Aircraft from Part components.
Parameters
----------
args, kwargs = the Parts to constitute the Aircraft with
'''
dict.__init__(self, *args, **kwargs)
if not all([isinstance(p, Part) for p in self.values()]):
raise NonPartComponentDetected()
def __repr__(self):
''' Override the object's internal representation. '''
return ('<{}.{} at {}>'
.format(self.__module__,
self.__class__.__name__,
hex(id(self))))
def __setitem__(self, k, v):
''' Make sure v is a Part. '''
if not isinstance(v, Part):
raise NonPartComponentDetected()
super(Aircraft, self).__setitem__(k, v)
def __delitem__(self, k):
''' Unglue the Part before deleting it. '''
self[k].unglue()
super(Aircraft, self).__delitem__(k)
def blowup(self):
''' Blow up the Aircraft's Parts in the current namespace. '''
IP = get_ipython()
for k, v in self.items():
IP.user_ns[k] = v
return self.items()
def _glue(self):
''' See Part._glue. '''
return [o for P in self.values() for o in P._glue(self)]
def _draw(self):
''' See Part._draw. '''
if hasattr(self, 'draw'):
return self.draw
return [P for P in self.values()]
# EXCEPTIONS
class AircraftException(Exception):
pass
class NonPartComponentDetected(AircraftException):
pass
|
1ee513ff7f5aac3fd043c7a907f7339a2348224a | vinvaid1989/training | /datecheck.py | 613 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 14:20:10 2018
@author: RPS
"""
import datetime
print(datetime.datetime.now().hour)
def cutoff(amount):
currtime=datetime.datetime.now().hour;
if(currtime > 17):
print ("tomorrow")
else:
print ("ok")
cutoff(56)
# for (key,value) in datelist.items():
# print(("->").join(str(key)+str(value))
# print(key,"=",value)
#holidaydates()
#import holidays
#from datetime import date
#holidays(date.today().strftime("%d/%m/%Y"));
#holidays('1/1/2018') |
a877604bf5f4ed8a8ebb23c4a5e123113084a9cf | Tyshkevichvyacheslav/Lr3 | /22.4.py | 1,435 | 4.09375 | 4 | print("Уравнения степени не выше второй — часть 2")
def solve(*coefficients):
if len(coefficients) == 3:
d = coefficients[1] ** 2 - 4 * coefficients[0] * coefficients[2]
if coefficients[0] == 0 and coefficients[1] == 0 and coefficients[2] == 0:
x = ["all"]
elif coefficients[0] == 0 and coefficients[1] == 0:
x = ''
elif coefficients[0] == 0:
x = [-coefficients[2] / coefficients[1]]
elif coefficients[1] == 0:
x = [(coefficients[2] / coefficients[0]) ** 0.5]
elif coefficients[2] == 0:
x = [0, -coefficients[1] / coefficients[0]]
else:
if d == 0:
x = [-coefficients[1] / (2 * coefficients[0])]
elif d < 0:
x = ''
else:
x = [float((-coefficients[1] + d ** 0.5) / (2 * coefficients[0])),
float((-coefficients[1] - d ** 0.5) / (2 * coefficients[0]))]
return x
elif len(coefficients) == 2:
return [-coefficients[1] / coefficients[0]]
elif len(coefficients) == 1:
if coefficients[0] == 0:
return ["all"]
else:
return []
else:
return ["all"]
print(sorted(solve(1, 2, 1)))
print("___________")
print(sorted(solve(1, -3, 2)))
input("Press any key to exit")
exit(0) |
5cb27604af3a7a610dd5c6f0c072d10254141496 | Tyshkevichvyacheslav/Lr3 | /23.1.py | 282 | 3.625 | 4 | print("Мимикрия")
transformation = lambda x: x
values = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
transformed_values = list(map(transformation, values))
if values == transformed_values:
print('ok')
else:
print('fail')
input("Press any key to exit")
exit(0) |
e2a854d1e492f741a8eb5746d76e51532edf5e68 | Tyshkevichvyacheslav/Lr3 | /21.4.py | 332 | 4.09375 | 4 | print("Фрактальный список – 2")
def defractalize(fractal):
return [x for x in fractal if x is not fractal]
fractal = [2, 5]
fractal.append(3)
fractal.append(9)
print(fractal)
print("____________")
fractal = [2, 5]
fractal.append(3)
print(fractal)
input("Press any key to exit")
exit(0)
|
bb02d54d7e24832e5fac78aed4fc6ae2ab765dc6 | CognitiveNetworking/IOT-Malware | /ScoringAndPerformance/stats_calcutaion.py | 7,994 | 3.5 | 4 | '''
Program name : stats_calculation.py
Author : Manjunath R B
This program Calcutes the statistics and generate statistical features.
The program calculates statistics per class per feature basis.
The program accepts three command line arguments
1. input file name
2. output file name
3. Quartile step value
The stats are calculated with and without duplicates.
'''
import pandas as pd
import numpy as np
import sys
import matplotlib.pyplot as plt
#filename ='C:\\Users\\manjuna\\Desktop\\netmate_files\\CTU-files_9\\csv_files\\42-1\\CTU-IoT-Malware-Capture-42-1.csv'
in_filename = sys.argv[1]
out_filename = sys.argv[2]
perc_step = int(sys.argv[3])
# Reading data from CSV(ignore columns such as srcip,srcport,dstip,dtsport,proto)
df = pd.read_csv(in_filename, index_col=0, usecols=lambda column: column not in ['srcip', 'srcport ', 'dstip ', 'dstport ', 'proto '])
newList = list(range(0, 100, perc_step))
perc = [i/100 for i in newList]
print(perc)
print("Printing the shape of the dataset\n")
print(df.shape)
print("Printing the index columns\n")
print(df.columns)
print("printing Classes from the CSV\n")
print(df['local-label'].unique().tolist())
#separate out data based on per class basis
dict_of_classes = dict(tuple(df.groupby("local-label")))
# for calculating statistics per class per feature with duplicates per column.
per_class_data_with_dup=pd.DataFrame()
for key,value in dict_of_classes.items():
per_class_stats_data_with_dup = pd.DataFrame(value)
i = 0
while i < len(per_class_stats_data_with_dup.columns) -2:
#get per column stats using iloc and store with column name as index
per_class_data_with_dup[per_class_stats_data_with_dup.columns[i]]=per_class_stats_data_with_dup.iloc[:,i].describe(percentiles = perc)
per_class_data_with_dup.loc['range',per_class_stats_data_with_dup.columns[i]] = per_class_data_with_dup.loc['max',per_class_stats_data_with_dup.columns[i]] - per_class_data_with_dup.loc['min',per_class_stats_data_with_dup.columns[i]]
per_class_data_with_dup.loc['midrange',per_class_stats_data_with_dup.columns[i]] = (per_class_data_with_dup.loc['max',per_class_stats_data_with_dup.columns[i]] + per_class_data_with_dup.loc['min',per_class_stats_data_with_dup.columns[i]])/2
if per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]] != 0:
per_class_data_with_dup.loc['coefVar',per_class_stats_data_with_dup.columns[i]] = per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]] / per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]
else:
per_class_data_with_dup.loc['coefVar',per_class_stats_data_with_dup.columns[i]] = 0
per_class_data_with_dup.loc['count_of_min-(mean-sd)',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between(per_class_data_with_dup.loc['min',per_class_stats_data_with_dup.columns[i]], (per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]- per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]])).values)
per_class_data_with_dup.loc['count_of_(mean-sd)-mean',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between((per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]- per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]]),per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]]).values)
per_class_data_with_dup.loc['count_of_mean-(mean+sd)',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between(per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]], (per_class_data_with_dup.loc['mean',per_class_stats_data_with_dup.columns[i]] + per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]])).values)
per_class_data_with_dup.loc['count_of_std-max',per_class_stats_data_with_dup.columns[i]]= np.count_nonzero(per_class_stats_data_with_dup.iloc[:,i].between(per_class_data_with_dup.loc['std',per_class_stats_data_with_dup.columns[i]], per_class_data_with_dup.loc['max',per_class_stats_data_with_dup.columns[i]]).values)
i = i +1
# add label column at the end
per_class_data_with_dup['label'] = key
per_class_data_with_dup.to_csv(out_filename, mode='a')
# for calculating statistics per class per feature after removing duplicates per column.
per_class_data_without_dup = pd.DataFrame()
for key,value in dict_of_classes.items():
per_class_stats_data_without_dup = pd.DataFrame(value)
i = 0
while i < len(per_class_stats_data_without_dup.columns) -2:
#get per column stats using iloc and store with column name as index
per_class_data_without_dup[per_class_stats_data_without_dup.columns[i]]=per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().describe(percentiles = perc)
per_class_data_without_dup.loc['range',per_class_stats_data_without_dup.columns[i]] = per_class_data_without_dup.loc['max',per_class_stats_data_without_dup.columns[i]] - per_class_data_without_dup.loc['min',per_class_stats_data_without_dup.columns[i]]
per_class_data_without_dup.loc['midrange',per_class_stats_data_without_dup.columns[i]] = (per_class_data_without_dup.loc['max',per_class_stats_data_without_dup.columns[i]] + per_class_data_without_dup.loc['min',per_class_stats_data_without_dup.columns[i]])/2
if per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]] != 0:
per_class_data_without_dup.loc['coefVar',per_class_stats_data_without_dup.columns[i]] = per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]] / per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]
else:
per_class_data_without_dup.loc['coefVar',per_class_stats_data_without_dup.columns[i]] = 0
per_class_data_without_dup.loc['count_of_min-(mean-sd)',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between(per_class_data_without_dup.loc['min',per_class_stats_data_without_dup.columns[i]], (per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]- per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]])).values)
per_class_data_without_dup.loc['count_of_(mean-sd)-mean',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between((per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]- per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]]),per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]]).values)
per_class_data_without_dup.loc['count_of_mean-(mean+sd)',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between(per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]], (per_class_data_without_dup.loc['mean',per_class_stats_data_without_dup.columns[i]] + per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]])).values)
per_class_data_without_dup.loc['count_of_std-max',per_class_stats_data_without_dup.columns[i]]= np.count_nonzero(per_class_stats_data_without_dup.iloc[:,i].drop_duplicates().between(per_class_data_without_dup.loc['std',per_class_stats_data_without_dup.columns[i]], per_class_data_without_dup.loc['max',per_class_stats_data_without_dup.columns[i]]).values)
i = i +1
# add label column at the end
per_class_data_without_dup['label'] = key
per_class_data_without_dup.to_csv(out_filename, mode='a')
print("DONE\n") |
96ee7f84b68f60c999e8450ade3f30ad667b89e8 | amark02/ICS4U-Classwork | /Classes/Encapsulation_1.py | 665 | 3.84375 | 4 |
class Person:
def __init__(self, name: str, age: int):
self.set_name(name)
self._age = age
def get_age(self):
#age = time_now - self.date_of_birth
return self._age
def set_age(self, value: int):
self._age = value
def get_name(self):
return self._first_name + " " + self._last_name
def set_name(self, value: str):
first, last = value.split(" ")
self._first_name = first
self._last_name = last
# /\ library author's code /\
# \/ OUR CODE \/
VOTING_AGE = 18
p = Person(name = "Jeff Foxworthy", age = 35)
if p.get_age() >= VOTING_AGE:
print(f"{p.get_name()} can vote") |
6d030f79eb3df2a3572eaadb0757401d3a330326 | amark02/ICS4U-Classwork | /Quiz2/evaluation.py | 2,636 | 4.25 | 4 | from typing import Dict, List
def average(a: float, b: float, c:float) -> float:
"""Returns the average of 3 numbers.
Args:
a: A decimal number
b: A decimal number
c: A decimal number
Returns:
The average of the 3 numbers as a float
"""
return (a + b + c)/3
def count_length_of_wood(wood: List[int], wood_length: int) -> int:
"""Finds how many pieces of wood have a specific
board length.
Args:
wood: A list of integers indicating length of
a piece of wood
wood_length: An integer that specifices what length
of wood a person is looking for
Returns:
How many pieces of wood there are for a specific
board length
e.g.,
wood = [10, 5, 10]
wood_length = 10
return 2
"""
total = 0
for piece in wood:
if piece == wood_length:
total += 1
else:
None
return total
def occurance_of_board_length(board_length: List[int]) -> Dict:
"""Returns a diciontary of the occurances of the length of a board.
Args:
board_length: A list of integers indicating the length
of a piece of wood
Returns:
Dictionary with the key being the length, and the value
being the number of times the length appeares in the list
e.g.,
board_length = [10, 15, 20, 20, 10]
return {10: 2, 15: 1, 20: 2}
"""
occurances = {}
for wood_length in board_length:
if wood_length in occurances.keys():
occurances[wood_length] += 1
else:
occurances[wood_length] = 1
return occurances
def get_board_length(board_length: Dict, wood_length: int) -> int:
"""Finds out how many pieces of wood have a specific
board length.
Args:
board_length: A dictionary with the keys being the board
length and the values being the number of boards with that
specific length
wood_length: An integer that specfies what length of wood
a person is looking for
Returns:
How many pieces of wood there are for a specific board length
"""
#correct answer
for key in board_length.keys():
if key == wood_length:
return board_length[key]
else:
return 0
"""
wrong answer:
list_of_wood = []
for key in board_length.keys():
list_of_wood.append(key)
total = 0
for piece in list_of_wood:
if piece == wood_length:
total += 1
else:
None
return total
"""
|
5b632636066e777092b375219a7a6cd571619157 | amark02/ICS4U-Classwork | /Classes/01_store_data.py | 271 | 4.1875 | 4 |
class Person:
pass
p = Person()
p.name = "Jeff"
p.eye_color = "Blue"
p2 = Person()
print(p)
print(p.name)
print(p.eye_color)
"""
print(p2.name)
gives an error since the object has no attribute of name
since you gave the other person an attribute on the fly
""" |
4a1e0cd10aa31c063f1b38f2197e6c640ab0e1d9 | robotBaby/linearAlgebrapython | /HW3.py | 608 | 3.671875 | 4 | from numpy import linalg as LA
import numpy as np
#Question 1
def get_determinant(m):
return LA.det(m)
##### Examples
#Eg: 1
#a = np.array([[4,3,2], [1,2,6], [5,8,1]])
#print get_determinant(a)
#b = np.array([[1, 2], [1, 2]])
#print get_determinant(b)\
#Question 2
def find_area(three_points):
m = np.array(three_points)
return 0.5 * get_determinant(m)
#### Examples
#three_points = [[1,0,0], [1,3,0], [1,0,4]]
#print find_area(three_points)
#Question 3
a = np.array([[4,3,2], [1,2,6], [5,8,1]])
E = LA.eig(a)
print "Eigenvalues are " , E[0]
print "Corresponding eigenvectors are ", E[1]
|
012b65d8534f8d52d843fb52bed3e2827ff2d605 | doranbae/shinko | /images/playShinko_vanilla.py | 6,761 | 3.640625 | 4 | # +--------------------------+
# | SHINKO |
# | Play the mobile game |
# +--------------------------+
import numpy as np
# set random seed
np.random.seed(84)
# define variables
matrix_min = 1
matrix_max = 5
matrix_width = 5
level_num = 2
shinko_goal = 5
handicap = 1
nox_pre_watch_size = 3
flat_matrix_length = matrix_width * level_num
class Play:
def __init__(self):
"""
:self.game_over : Boolean value to determine whether game is over or not
:self.reward : Every time you successfully make an addition 5, you gain a reward
:self.num_moves : Number of noxes you use to play the game. Given you beat the game,
you want to use the smallest possible number of noxes
:self.matrix : Initial set of boxes you need to play on
:self.flat_matrix : Flattened form of the matrix
:self.valid_actions: Simplifying feature not to allow the splitting of the matrix
:self.init_nox_list: At the start of each game, you see next noxes up to 3
"""
self.game_over = False
self.reward = 0
self.num_moves = 0
self.matrix = np.random.randint( low = matrix_min,
high = matrix_max,
size = (level_num, matrix_width) )
self.flat_matrix = self.matrix.reshape( -1, flat_matrix_length )
self.valid_actions = np.arange( start = flat_matrix_length/2,
stop = flat_matrix_length,
step = 1,
dtype = 'int')
self.init_nox_list = np.random.randint( low = matrix_min,
high = matrix_max-handicap,
size = (nox_pre_watch_size) )
self.win_game = False
def gen_nox(self):
"""
You will be abel to see future noxes up to 3.
:return: new additional nox
"""
new_nox = np.random.randint( low = matrix_min,
high = matrix_max-handicap,
size = (1) )
return new_nox
def find_best_action(self, nox):
"""
:return: updates self.valid_action_ranking, a list of actions
in the order of most reward given
"""
valid_pairs = []
for valid_action in self.valid_actions:
remainder = shinko_goal - self.flat_matrix[0][valid_action] - nox
action_remainder_pair = ( valid_action, remainder )
valid_pairs.append(action_remainder_pair)
sorted_valid_pairs = sorted(valid_pairs, key = lambda tup: tup[1], reverse = False)
self.valid_action_ranking = [pos for (pos, remainder) in sorted_valid_pairs if remainder >= 0]
def update_valid_actions(self, action):
"""
:return: Update self.valid_actions which keeps track of
list of list of playable matrix indices
"""
curr_valid_actions = self.valid_actions
# delete the index of the flat matrix which has a value of 5
# (--> not possible to play anymore)
del_idx = np.where( curr_valid_actions == action )[0][0]
updated_valid_actions = np.delete( curr_valid_actions, del_idx )
# add new index of the flat matrix which became available to play
# (--> for example, when one of the box in matrix disappears,
# the number underneath becomes playable)
new_valid_action = action - matrix_width
if new_valid_action >= 0:
updated_valid_actions = np.append( updated_valid_actions, new_valid_action )
self.valid_actions = updated_valid_actions
def update_matrix(self, nox):
"""
Updates the matrix based on nox and the best action
Updates reward and num_moves
Updates self.valid_actions (based on the current action)
"""
if len( self.valid_action_ranking ) == 0:
print( '' )
print( '##################' )
print( ' GAME OVER' )
print( '##################' )
print( ' No more moves_____' )
print( self.flat_matrix.reshape(-1, matrix_width) )
print( ' nox: ', nox )
print( ' Total moves: ', self.num_moves )
self.game_over = True
else:
# best action is the first action from self.valid_action_ranking
best_action = self.valid_action_ranking[0]
print( 'Your action: ', best_action )
self.num_moves += 1
self.flat_matrix[ 0, best_action ] = self.flat_matrix[0][ best_action ] + nox
if self.flat_matrix[ 0, best_action ] == 5:
self.reward += 1
self.update_valid_actions( best_action )
def startGame(self):
nox_list = []
nox_list.extend( self.init_nox_list )
print( 'Initializing the matrix________' )
print( self.flat_matrix.reshape(-1, matrix_width) )
print( '-------------------------------' )
while self.game_over == False:
print( '( Num moves: {} ) Beat the game when next noxes are: {}'.format( self.num_moves, nox_list ))
print( self.flat_matrix.reshape(-1, matrix_width) )
# rank the valid options by reward in self.valid_action_ranking
nox = nox_list[0]
self.find_best_action(nox)
# the machine will always play the best move based on a simple arithmetic rule
self.update_matrix(nox)
# update nox_list
nox_list.extend( list(self.gen_nox()) )
nox_list = nox_list[1: ]
if np.all( self.flat_matrix == 5):
print( '' )
print( '##################' )
print( ' YOU WIN' )
print( '##################' )
# print( 'Final score: ', self.reward * ( flat_matrix_length /self.num_moves) )
print( 'Total num of moves: ', self.num_moves )
self.game_over = True
self.win_game = True
print('~*~*~*~*~*~*~*~*~*~*~*~*~*~*')
return self.win_game
# if __name__ == "__main__":
# print( 'Lets play Shinko!' )
# shinko = Play()
# shinko.startGame()
win_cnt = 0
win_idx = []
for x in range(300):
np.random.seed(x)
shinko = Play()
win = shinko.startGame()
if win == True:
win_cnt += 1
win_idx.append(x)
print( 'Testing done' )
print( 'Win count: {}'.format(win_cnt) ) |
72f64a3b98ee883737a0ea668eda1151365d72b6 | MorHananovitz/CSCI-315-Artificial-Intelligence-through-Deep-Learning | /Assignment2/perceptron.py | 1,034 | 3.515625 | 4 | import numpy as np
#Part 1 - Build Your Perceptron (Batch Learning)
class Perceptron:
def __init__(self,n, m):
self.input = n
self.output = m
self.weight = np.random.random((n+1,m))-0.5
def __str__(self):
return str( "This is a Perceptron with %d inputs and %d outputs" % (self.input, self.output))
def test(self, J):
return(np.dot(np.transpose(np.append(J, [1])), self.weight) > 0)
def train(self,I,T, t=1000):
Itrain = np.hstack((I, np.split(np.ones(len(I)), len(I))))
for i in range(t):
if i %100 == 0:
print("Complete %d / %d Iterations" % (i, t))
dW = np.zeros((self.input + 1, self.output))
for row_I, row_T in zip(Itrain, T):
O = np.dot(row_I, self.weight) > 0
D = row_T - O
dW = dW + np.outer(row_I, D)
self.weight = self.weight + dW / len(Itrain)
print()
print("Complete %d Iterations" % t)
|
e2fc0eb8047bbe73f5be60371a03ad388bc7f388 | ClaeysKobe/Kobeehhh | /Thuis 3.py | 520 | 3.609375 | 4 | print("*** Welkom bij het kassasysteem ***")
broeken = int(input("Hoeveel broeken werden er verkocht? "))
tshirts = int(input("Hoeveel T-shirts werden er verkocht? "))
vesten = int(input("Hoeveel vesten werden er verkocht? "))
prijs_broeken = broeken * 70.5
prijs_tshirts = tshirts * 20.89
prijs_vesten = vesten * 100.3
totaal = prijs_broeken + prijs_tshirts + prijs_vesten
print(f"U Kocht: \n\tBroeken: {broeken} stuk(s) \n\tT-Shirts: {tshirts} stuk(s) \n\tVesten: {vesten} stuk(s) \nTotaal te betalen: {totaal: .2f}") |
23ee2c8360e32e0334a31da848043cf6187cd636 | cosinekitty/astronomy | /demo/python/gravity.py | 1,137 | 4.125 | 4 | #!/usr/bin/env python3
import sys
from astronomy import ObserverGravity
UsageText = r'''
USAGE:
gravity.py latitude height
Calculates the gravitational acceleration experienced
by an observer on the surface of the Earth at the specified
latitude (degrees north of the equator) and height
(meters above sea level).
The output is the gravitational acceleration in m/s^2.
'''
if __name__ == '__main__':
if len(sys.argv) != 3:
print(UsageText)
sys.exit(1)
latitude = float(sys.argv[1])
if latitude < -90.0 or latitude > +90.0:
print("ERROR: Invalid latitude '{}'. Must be a number between -90 and +90.".format(sys.argv[1]))
sys.exit(1)
height = float(sys.argv[2])
MAX_HEIGHT_METERS = 100000.0
if height < 0.0 or height > MAX_HEIGHT_METERS:
print("ERROR: Invalid height '{}'. Must be a number between 0 and {}.".format(sys.argv[1], MAX_HEIGHT_METERS))
sys.exit(1)
gravity = ObserverGravity(latitude, height)
print("latitude = {:8.4f}, height = {:6.0f}, gravity = {:8.6f}".format(latitude, height, gravity))
sys.exit(0)
|
6d0702099e71e5065cc3a1bdfeb152995fccdc81 | loki2236/Python-Practice | /src/Ej2.py | 439 | 3.71875 | 4 | #
# Dada una terna de números naturales que representan al día, al mes y al año de una determinada fecha
# Informarla como un solo número natural de 8 dígitoscon la forma(AAAAMMDD).
#
dd = int(input("Ingrese el dia (2 digitos): "))
mm = int(input("Ingrese el mes (2 digitos): "))
yyyy = int(input("Ingrese el año (4 digitos): "))
intdate = (yyyy*10000) + (mm*100) + dd
print("La fecha en formato entero es: ", intdate)
|
c5c9ed70accfeafc3d4ec07f8e9b9a556ec7143c | Dibyadarshidas/py4e | /open_files and big_count.py | 449 | 3.671875 | 4 | name = input("Enter file:")
handle = open(name)
counts = dict()
bigcount = None
bigword = None
smallcount = None
smallword = None
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
#print(counts)
for p,q in counts.items():
print(p,q)
if bigcount is None or q > bigcount:
bigword = p
bigcount = q
print("Highest Occurrence:",bigword,bigcount)
|
11575571fe85a08533ad8cfaffcdbd1c4936a8d8 | Dibyadarshidas/py4e | /19.09.2020.py | 640 | 3.640625 | 4 | # Sort by values instead of key
#c = {'a':10, 'b':1, 'c':22 }
#tmp = []
#for k, v in c.items() :
# tmp.append((v, k))
#print(tmp)
#tmp = sorted(tmp, reverse=True)
#print(tmp)
# Long Method
#fhand =open('words.txt')
#counts = {}
#for line in fhand:
# words = line.split()
# for word in words:
# counts[word] = counts.get(word, 0) + 1
#lst = []
#for k,v in counts.items():
# newtup = (v, k)
# lst.append(newtup)
#lst = sorted(lst,reverse=True)
#for v,k in lst[:10]:
# print(k,v)
# Shorter Version
#c = {'a': 10 , 'b' : 1 , 'c': 22}
#print(sorted([(v,k) for k,v in c.items()],reverse=True))
|
a7f2d4a9a20c2eb58a04861708ac895baa6156ee | abeltomvarghese/Data-Analysis | /Learning/DataFrames.py | 724 | 3.765625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use("fivethirtyeight")
web_stats = {"Day":[1,2,3,4,5,6],
"Visitors":[43,34,65,56,29,76],
"Bounce Rate": [65,67,78,65,45,52]}
#CONVERT TO DATAFRAME
df = pd.DataFrame(web_stats)
#PRINT THE FIRST FEW VALUES
print(df.head())
#PRINT LAST FEW LINES
print(df.tail())
#SPECIFY HOW MANY OF THE LAST ITEMS YOU WANT
print(df.tail(2))
#SET INDEX FOR THE DATA USING A DATA COLUMN THAT CONNECTS ALL OTHER COLUMNS
df.set_index("Day", inplace=True) #INPLACE HELPS US TO MODIFY THE DATAFRAME
df[["Visitors", "Bounce Rate"]].plot() #YOU CAN PLOT THE ENTIRE DICTIONARY (VISITORS AND BOUNCE RATE) BY DOING df.plot()
plt.show()
|
b8aa70ebee9c3db49bbc8905f88f0e604734894d | pureforwhite/ToyEncryptionAlgorithm | /main.py | 1,729 | 4.09375 | 4 | #PureForWhite create a string encryption program with Toy Encryption Algorithm
#The source code will be in the link description below
#Follow me on reddit, subscribe my youtube channel, like this video and share it thanks!
#creating decryption function
def decryption(s):
s = list(s)
for i in range(len(s)):
if s[i] == "_":
s[i] = " "
first = s[:len(s)//2]
second = s[len(s)//2:]
second = second[::-1]
result = [" "] * (len(s) + 1)
for i in range(len(first)):
result[i * 2] = first[i]
for j in range(len(second)):
result[j * 2 + 1] = second[j]
print("".join(result))
#creating encryption function
def encryption(s):
s = list(s)
first = []
second = []
for i in range(len(s)):
if s[i] == " ":
s[i] = "_"
if i % 2 == 0:
first.append(s[i])
else:
second.append(s[i])
second = second[::-1]
print("".join(first) + "".join(second))
#creating the main function
def main():
themode = "off"
while True:
try:
print("Current themode:", themode)
if themode == "off":
themode = input("themode(dec - decryption, enc - encryption)> ")
else:
s = input("String> ")
if s == "#c":
themode = "off"
elif s == "#q":
break
elif themode == "dec":
print(decryption(s))
elif themode == "enc":
print(encryption(s))
print()
if themode == "#q":
break
except:
break
if __name__ == "__main__":
main()
|
de463c40b80011fd725e2675aa1ab0c4a16cf8c6 | joshinihal/dsa | /recursion/basic_problems.py | 1,146 | 3.828125 | 4 | # Write a recursive function which takes an integer
# and computes the cumulative sum of 0 to that integer
def rec_sum(n):
if n == 0:
return 0
return n + rec_sum(n-1)
rec_sum(10)
#-------------------------------------------------
# Given an integer, create a function which returns the sum of all the individual digits in that integer.
def sum_func(n):
if n<1:
return 0
return n%10 + sum_func(int(n/10))
sum_func(6577)
#--------------------------------------------------
# Create a function called word_split() which takes in a string phrase and a set list_of_words.
# The function will then determine if it is possible to split the string in a way in which
# words can be made from the list of words.
# You can assume the phrase will only contain words found in the dictionary if it is completely splittable.
def word_split(s,l,output = None):
if output == None:
output = []
for word in l:
if s.startswith(word):
output.append(word)
return word_split(s[len(word):],l,output)
return output
word_split('themanran',['the','ran','man'])
|
e27d035e4e5e2cb1a95204bcdbccae9237d70eda | joshinihal/dsa | /trees/binary_heap_implementation.py | 2,258 | 3.796875 | 4 | # min heap implementation
# https://en.wikipedia.org/wiki/Binary_heap
# list has a '0' element at first index(0) i.e. [0,.....]
class BinHeap():
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def perUp(self, i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
# insert by appending at the end of the list
def insert(self,k):
self.heapList.append(k)
self.currentSize = self.currentSize + 1
# since inserting at the end disturbs the heap property,
# use percUp to push the newly added element upwards to satisy the heap property
self.percUp(self.currentSize)
# find the min child for an index ,
# if min child is smaller than the parent percdown the parent
def percDown(self, i):
while (i*2) <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[i]
self.heapList[i] = self.heapList[mc]
self.heapList[mc] = tmp
i = mc
def minChild(self,i):
if i * 2 + 1 > self.currentSize:
return i * 2
else:
if self.heapList[i*2] < self.heapList[i*2+1]:
return i * 2
else:
return i * 2 + 1
# delete by removing the root since in min heap root is the minimum.
def delMin():
rootVal = self.heapList[1]
# restore the size
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize = self.currentSize - 1
self.heapList.pop()
# since deleting disturbs the heap size, use percDown to put the min at root
self.percDown(1)
return rootVal
def buildHeap(self,alist):
i = len(alist) // 2
self.currentSize = len(alist)
self.heapList = [0] + alist[:]
while (i > 0):
self.percDown(i)
i = i - 1
|
e79076cd45b6280c2046283d9a349620af0f8d70 | joshinihal/dsa | /trees/tree_implementation_using_oop.py | 1,428 | 4.21875 | 4 | # Nodes and References Implementation of a Tree
# defining a class:
# python3 : class BinaryTree()
# older than python 3: class BinaryTree(object)
class BinaryTree():
def __init__(self,rootObj):
# root value is also called key
self.key = rootObj
self.leftChild = None
self.rightChild = None
# add new as the left child of root, if a node already exists on left, push it down and make it child's child.
def insertLeft(self,newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t
# add new as the right child of root, if a node already exists on right, push it down and make it child's child.
def insertRight(self,newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def setRootValue(self,obj):
self.key = obj
def getRootValue(self):
return self.key
r = BinaryTree('a')
r.getRootValue()
r.insertLeft('b')
r.getLeftChild().getRootValue()
|
4999709b618b6edca8a2e462c4575a56f81a580c | Amit998/python_software_design | /Intro/guess_game.py | 1,036 | 3.78125 | 4 | class GuessNumber:
def __init__(self,number,min=0,max=100):
self.number = number
self.guesses=0
self.min=min
self.max=max
def get_guess(self):
guess=input(f"Please guess a Number ({self.min} - {self.max}) : ")
if (self.valid_number(guess)):
return int(guess)
else:
print("please enter a valid number")
return self.get_guess()
def valid_number(self,str_number):
try:
number=int(str_number)
except :
return False
return self.min <= number <= self.max
def play(self):
while True:
self.guesses=self.guesses+1
guess=self.get_guess()
if (guess < self.number):
print("Your Guess Was Under")
elif guess > self.number:
print("your guess was over")
else:
break
print(f"You guessed it in {self.guesses} guesses")
game=GuessNumber(56,0,100)
game.play() |
2e41ccaf34b9b6d8083df766a3a578418bbf6db0 | Khizanag/algorithms | /FooBar/Level 3/Bunny Prisoner Locating/Bunny Prisoner Locating.py | 186 | 3.796875 | 4 | def solution(x, y):
H = x + y - 1
n = 1 # value when x = 1
temp = 0 # n increases by temp
for i in range(H):
n += temp
temp += 1
print(n + x - 1)
print(solution(3, 2)) |
6d67c92e324e39b17788d860548bfd23059ca5af | domzhaomathematics/Competitive-Coding-8 | /minimum_window_substring.py | 2,246 | 3.53125 | 4 | #Time Complexity: O(s+t), traversal and building hashmaps
#Space complexity: O(s+t),length of S and T
'''
Evertime we encounter a letter that belongs to T, we append it to a queue and
increment the hashmap with that key. We keep a hashmap to check how many times
the letter appear in T. If we've found all the letter of T, we check the
indices [slow,fast] and check if the length is better than our previous valid
window. Then we pop from the queue to get the next position of slow, while decrementing
the value that moved from in the hashmap. If the letter count goes below
the number of that letter in T, we decrement found, since we need to find that letter
again. When fast goes out, we're done. We return the string from the optimal window
'''
class Solution:
def minWindow(self, s: str, t: str) -> str:
if len(t)>len(s):
return ''
if len(t)==1:
for c in s:
if c==t: return t
return ''
letters={c:0 for c in t}
letters_freq={c:0 for c in t}
for l in t: letters_freq[l]+=1
queue=collections.deque()
slow=0
min_=float("inf")
window=None
while slow<len(s) and s[slow] not in letters:
slow=slow+1
if slow==len(s): return ''
fast=slow+1
found=1
letters[s[slow]]+=1
was_found=False
while fast<len(s):
if s[fast] in letters and not was_found:
queue.append((fast,s[fast]))
if letters[s[fast]]<letters_freq[s[fast]]:
found+=1
letters[s[fast]]+=1
if found==len(t):
if fast-slow<min_:
window=[slow,fast]
min_=fast-slow
next_slow,next_slow_val=queue.popleft()
letters[s[slow]]-=1
if letters[s[slow]]<letters_freq[s[slow]]:
found-=1
slow=next_slow
was_found=True
continue
else:
was_found=False
fast+=1
if not window:
return ''
return s[window[0]:window[1]+1]
|
20ac70eaf04d544691436bbd5c6c0f5323ba40f8 | rizveeredwan/UID-Generation-Based-On-Polynomial-Hashing | /PhoneticMeasurePerformance/name_generator.py | 1,631 | 3.65625 | 4 | import csv
"""
### SEGMENT 1: Name collection
### Taking input of all the names ######
names=[]
with open('/home/student/Desktop/PhoneticAccuracyMeasure3/UID-Generation-Based-On-Polynomial-Hashing/TrainingData.csv') as csvFile:
csvReader = csv.DictReader(csvFile)
for row in csvReader:
v=row['name'].split(' ')
print(v)
for n in v:
if(n.strip().upper() not in names):
names.append(n.strip().upper())
v=row['father_name'].split(' ')
for n in v:
if(n.strip().upper() not in names):
names.append(n.strip().upper())
v=row['mother_name'].split(' ')
for n in v:
if(n.strip().upper() not in names):
names.append(n.strip().upper())
print(len(names))
names = sorted(names)
with open('nameFile.csv','w') as csvFile:
csvWriter = csv.writer( csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csvWriter.writerow(['name'])
for i in names:
print(i)
csvWriter.writerow([i])
"""
### SEGMENT 2: AFTER REMOVING UNNECESSARY SYMBOLS
names=[]
with open('nameFile.csv','r') as csvFile:
csvReader=csv.DictReader(csvFile)
for row in csvReader:
n=row['name'].split(' ')
for i in n:
#WONT' TAKE NUMBER
sp=i.strip()
mainName=""
for j in sp:
if(ord(j)>=ord('A') and ord(j)<=ord('Z')):
mainName=mainName+j
if(len(mainName)>0 and (mainName not in names)):
names.append(mainName)
print(mainName)
names=sorted(names)
with open('nameFile.csv','w') as csvFile:
csvWriter = csv.writer( csvFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csvWriter.writerow(['name'])
for i in names:
print(i)
csvWriter.writerow([i])
print(len(names))
|
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7 | AGriggs1/Labwork-Fall-2017 | /hello.py | 858 | 4.125 | 4 | # Intro to Programming
# Author: Anthony Griggs
# Date: 9/1/17
##################################
# dprint
# enables or disables debug printing
# Simple function used by many, many programmers, I take no credit for it WHATSOEVER
# to enable, simply set bDebugStatements to true!
##NOTE TO SELF: in Python, first letter to booleans are Capitalized
bDebugStatements = True
def dprint(message):
if (bDebugStatements == True):
print(message)
#Simple function with no specific purpose
def main():
iUsr = eval(input("Gimme a number! Not too little, not too big... "))
dprint("This message is for debugging purposes")
for i in range(iUsr):
#Hmmmm, ideally we don't want a space between (i + 1) and the "!"
#GH! Why does Python automatically add spaces?
print("Hello instructor", i + 1, "!")
print("Good bye!")
dprint("End")
main()
|
dbf03069fac82c54e3a158dae1d62b0589440176 | jphilippou27/kingmakers_capstone | /data/os2/load_cmte_advanced.py | 1,002 | 3.640625 | 4 | import csv, sqlite3, sys
if __name__ == "__main__":
conn = sqlite3.connect("os2.db")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS cmte_advanced;")
conn.commit()
cur.execute("""CREATE TABLE cmte_advanced (
id TEXT(9),
name TEXT(50),
parent TEXT(50),
cand_id TEXT(9),
type TEXT(2),
party TEXT(1),
interest TEXT(5),
sensitive TEXT(1)
);"""
)
conn.commit()
with open("cmte_advanced.txt", errors="ignore") as input:
counter = 0
reader = csv.reader(input, delimiter=",", quotechar="|")
rows = [(row[1], row[2], row[4], row[7], row[6], row[8], row[9], row[11]) for row in reader]
cur.executemany("""INSERT INTO cmte_advanced (
id,
name,
parent,
cand_id,
type,
party,
interest,
sensitive
) VALUES (?, ?, ?, ?, ?, ?, ? ,?);""", rows )
conn.commit()
conn.close()
|
4188c44dda65c2849f1ae89fd19eb46b7efffd14 | dancing-elf/add2anki | /add2anki/add2anki.py | 2,805 | 3.734375 | 4 | """Interactively translate and add words to csv file if needed"""
import argparse
import sys
import tempfile
import urllib
import colorama
import pygame
import add2anki.cambridge as cambridge
def add2anki():
"""Translate and add words to csv file if needed"""
parser = argparse.ArgumentParser()
parser.add_argument('-from', dest='src_lang',
help='Source language', required=True)
parser.add_argument('-to', dest='dst_lang',
help='Destination language', required=True)
parser.add_argument('-out', dest='output',
help='Destination csv file')
args = parser.parse_args()
colorama.init(autoreset=True)
note = None
_print_invitation()
for line in sys.stdin:
word = line.strip()
if not word:
pass
elif word == 'h':
_handle_help()
elif word == 'q':
sys.exit(0)
elif word == 'a':
_handle_add(note, args.output)
elif word == 's':
_handle_sound(note)
else:
note = _handle_word(word, args.src_lang, args.dst_lang)
_print_invitation()
def _print_invitation():
"""Print invitation for user input"""
print()
print('Type command or word for translation. '
'Type "h" for list of possible commands')
print('>>> ', end='')
def _handle_help():
"""Display help"""
print('h display this help')
print('q exit from add2anki')
print('a add note to csv file')
print('s play sound for last word')
def _handle_add(note, csv_file):
"""Add note to csv file"""
if not note:
_warn_none_note()
return
if not csv_file:
print(colorama.Fore.YELLOW + 'csv file not selected')
return
with open(csv_file, 'a+') as output_file:
print(note.word + "\t" + cambridge.to_html(note),
file=output_file)
def _handle_sound(note):
"""Play sound for note"""
if not note:
_warn_none_note()
return
with tempfile.NamedTemporaryFile() as temp:
urllib.request.urlretrieve(note.pronunciation, temp.name)
_play_audio(temp.name)
def _handle_word(word, src_lang, dst_lang):
"""Translate word and print it to terminal"""
note = None
try:
note = cambridge.translate(word, src_lang, dst_lang)
cambridge.print_note(note)
except:
print(colorama.Fore.RED + 'Error while handle {}: '.format(word),
sys.exc_info())
return note
def _play_audio(path):
"""Play sound with pygame"""
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
audio = pygame.mixer.Sound(path)
audio.play()
def _warn_none_note():
print('There is no successfully translated word') |
29855d475c40a99d9c99896389b0129981d29131 | ochuerta/bolt | /docs/_includes/lesson1-10/Boltdir/site-modules/exercise8/tasks/great_metadata.py | 853 | 3.53125 | 4 | #!/usr/bin/env python
"""
This script prints the values and types passed to it via standard in. It will
return a JSON string with a parameters key containing objects that describe
the parameters passed by the user.
"""
import json
import sys
def make_serializable(object):
if sys.version_info[0] > 2:
return object
if isinstance(object, unicode):
return object.encode('utf-8')
else:
return object
data = json.load(sys.stdin)
message = """
Congratulations on writing your metadata! Here are
the keys and the values that you passed to this task.
"""
result = {'message': message, 'parameters': []}
for key in data:
k = make_serializable(key)
v = make_serializable(data[key])
t = type(data[key]).__name__
param = {'key': k, 'value': v, 'type': t}
result['parameters'].append(param)
print(json.dumps(result))
|
243f97a94733bea6491fda338ab7831a6e773e4a | solonmoraes/CodigosPythonTurmaDSI | /Exercicio1/segunda atv.py | 186 | 3.9375 | 4 | print("===========Atividade=============")
salaTotal = float(input("Informe o quanto recebeu:\n"))
horasDia = int(input("Informe suas horas trabalhadas:\n"))
print(salaTotal / horasDia)
|
38445453493bcae3afdfafc93fd6568027dca64d | solonmoraes/CodigosPythonTurmaDSI | /Listas.py | 656 | 4.09375 | 4 | pessoas = ["Fabio","Carlos","Regina","Vanuza"]
print(type(pessoas))
print(pessoas)
pessoas[1] = "Sergio"
# adicionar elementoas
pessoas.append("Sarah")# adiciona no final
pessoas.insert(2,"Flavio")#adiciona em qualquer lugar
for chave, valor in enumerate(pessoas):
print(f"{chave:.<5}{valor}")
#removendo elementos
pessoas.pop()#remove o ultimo elemento
pessoas.pop(1)#remove qualquer posiçao
pessoas.remove("Flavio")
print(pessoas)
#copiando listas
pessoasBkp = pessoas
pessoasBkp.append("jeronimo")
print("\n\n",pessoas)
print(pessoasBkp,"\n\n")
pessoas.clear()#limpa alista
del(pessoas)#excluir a variavel ou lista
print(pessoas,"\n\n")
|
079e2d347895e1d1cf900b4772a3ad5902f793d7 | solonmoraes/CodigosPythonTurmaDSI | /banco de dados mongo/POO/aula3/conta.py | 1,220 | 3.8125 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite=1000):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
def depositar(self, valor):
if valor < 0:
print("Voce nao pode depositar valor negativo")
else:
self.__saldo += valor
def sacar(self, valor):
if valor > self.__saldo:
print(f"Voce nao pode sacar este valor, seu saldo e {self.__saldo}")
else:
self.__saldo -= valor
def getSaldo(self):
print(f"Seu saldo é {self.__saldo}")
# Outra forma de criar getters e setters
class Conta2:
def __init__(self, numero, titular, saldo, limite=1000):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
# decorator
# Exibir o saldo
@property
def saldo(self):
return f"O seu saldo é R$ {self.saldo}"
#Inserir valores no atributo
@saldo.saldo(self, valor):
if valor < 0:
print ("Voce nao pode depositar valores negativos")
else:
self.__saldo += Valor:
print("Valor depositado com sucesso")
|
f2794e3c31b085db9b10afa837d6026848ef1318 | lucasferreira94/Python-projects | /jogo_da_velha.py | 1,175 | 4.25 | 4 | '''
JOGO DA VELHA
'''
# ABAIXO ESTAO AS POSIÇÕES DA CERQUILHA
theBoard = {'top-L':'', 'top-M':'', 'top-R':'',
'mid-L':'','mid-M':'', 'mid-R':'',
'low-L':'', 'low-M':'', 'low-R':''}
print ('Choose one Space per turn')
print()
print(' top-L'+' top-M'+ ' top-R')
print()
print(' mid-L'+' mid-M'+ ' mid-R')
print()
print(' low-L'+' low-M'+ ' low-R ')
print()
# FUNÇÃO PARA PRINTAR A CERQUILHA NA TELA
def printBoard(board):
print(board['top-L'] + '|' + board['top-M'] +'|' + board['top-R'])
print('+-+-')
print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
print('+-+-')
print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])
# O JOGO INICIA PELA VEZ DO 'X'
turn = 'X'
for i in range(9):
printBoard(theBoard)
print('Turn for ' + turn + '. Move on wich space? ') # INDICA A VEZ DO JOGADOR
move = input() # O JOGADOR DEVERÁ COLOCAR A POSIÇÃO QUE QUER JOGAR
theBoard[move] = turn # ASSOCIA A JOGADA AO JOGADOR
print()
# CONDICIONAL PARA REALIZAR A MUDANÇA DE JOGADOR
if turn == 'X':
turn = 'O'
else:
turn = 'X'
printBoard(theBoard)
|
a9746ae70ae68aefacd3bb071fae46e949a7e29f | YangYishe/pythonStudy | /src/day8_15/day8_2.py | 683 | 4.40625 | 4 | """
定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法。
"""
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def move(self, x, y):
self._x += x
self._y += y
def distance_between(self, other_point):
return ((self._x - other_point._x) ** 2 + (self._y - other_point._y) ** 2) ** 0.5
def desc(self):
return '{x:%f,y:%f}' % (self._x, self._y)
def main():
p1 = Point(2, 4)
p2 = Point(3, 8)
p1.move(5, -10)
print(p1.desc())
print(p2.desc())
print(f'distance:{p1.distance_between(p2)}')
pass
if __name__ == '__main__':
main()
|
f12289953bccf14110d3d75acca9b35797bf9b30 | YangYishe/pythonStudy | /src/day1_7/day4_3.py | 481 | 3.984375 | 4 | """
打印如下所示的三角形图案。
"""
for i1 in range(1, 6):
for i2 in range(1, i1 + 1):
print('*', end='')
print('')
for i1 in range(1, 6):
for i2 in range(1, 6):
if i2 + i1 <= 5:
print(' ', end='')
else:
print('*', end='')
print('')
for i1 in range(1, 6):
for i2 in range(1, i1 + 5):
if i2 <= 5 - i1:
print(' ', end='')
else:
print('*', end='')
print('')
|
5c754378bc33111b88a28b80317c95ba075664a5 | YangYishe/pythonStudy | /src/day1_7/day7_6.py | 339 | 3.734375 | 4 | """
打印杨辉三角。
"""
def yhsj(n):
arr1=[1,1]
for i in range(n-1):
arr2=[1]
for j in range(i):
arr2.append(arr1[j]+arr1[j+1])
arr2.append(1)
arr1=arr2
yield arr1
pass
def main():
for i in yhsj(10):
print(i)
pass
if __name__ == '__main__':
main() |
bd49df8de11f36cfc6b881024001c01f6c88348e | benb2611/AmericanAirlines-scraper | /american_airlines.py | 16,446 | 3.828125 | 4 | """
Contains AmericanAirlines class, where help methods and logic for scraping data
from American Airlines web site are implemented. (all for educational purposes only!)
Check '__init__()' docstring for required parameters. To start scraping - just create instance of AmericanAirlines
and use 'run()' method. Example:
scraper = AmericanAirlines('mia', 'sfo', '02/12/2018', '02/15/2018')
scraper.run()
**Note**: this class does little about input data validation, so use 'aa_manager.py' (or your own script) to
perform data validation.
"""
import time
import os
import json
from selenium import webdriver
# from selenium.webdriver.chrome.options import Options
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.common.exceptions import NoSuchElementException, ElementNotInteractableException
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
class AmericanAirlines:
def __init__(self, departure_airport, destination_airport, departure_date, return_date=None,
sleeptime=3, trip_type="round trip",
airline="AA", price="lowest", passengers=1,
passengers_type=None, daytime="all day", file_path="", file_format="json"):
"""
:param departure_airport: code of airport from which you ant to depart (3 characters string)
:param destination_airport: destination airport code (3 characters string)
:param departure_date: date of departure - string with this format 'mm/dd/yyyy' (example: 02/10/2018)
:param return_date: date of return - string 'mm/dd/yyyy' (example: 02/17/2018). Only needed,
when trip_type="round trip"
:param sleeptime: wait time to download starting page
:param trip_type: type of the trip
- "round trip" - trip to chosen destination and back
- "one way" - trip to chosen destination
:param airline: service provider
- AA - Americans Airlines
- ALL - all providers
:param price: search by price, default value - "lowest"(doesnt have other options for now)
:param passengers: number of passengers(for now supporting only one passenger)
:param passengers_type: dictionary of passengers grouped by age corresponding to passengers total number;
{1: "adult", 2: "child"} etc. (Not supported for now).
:param daytime: return available flights only from chosen time interval(evening, morning). For now,
class support only one interval - 'all day'
:param file_path: full path to directory, where you want to save flights information(default location -
- current directory)
:param file_format: format in which data would be saved to a file. Chose from next option:
-"json"
"""
# making Firefox work in headless mode
firefox_options = Options()
firefox_options.add_argument('-headless')
# setting Firefox to use tor proxies
# profile = webdriver.FirefoxProfile()
# profile.set_preference('network.proxy.type', 1)
# profile.set_preference('network.proxy.socks', '127.0.0.1')
# profile.set_preference('network.proxy.socks_port', 9150)
self.sleeptime = sleeptime
self.trip_type = trip_type
self.airline = airline
self.price = price
self.passengers = passengers
self.passengers_type = passengers_type
self.daytime = daytime
self.departure = departure_airport
self.destination = destination_airport
self.departure_date = departure_date
self.return_date = return_date
self.file_path = file_path
self.file_format = file_format
self.driver = webdriver.Firefox(firefox_options=firefox_options)
# site has bot protection and easy detect 'default cromedriver'so we using firefox for now
# self.driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)
self.driver.get("https://www.aa.com/booking/find-flights") # opening site's search window
time.sleep(self.sleeptime)
def __del__(self):
self.driver.close()
def press_accept_cookies(self):
""" Method for pressing 'accept button'.
When we open site for the first time - they'll ask to accept cookies polices in separate pop-up window.
"""
try:
self.driver.find_element_by_xpath('//div[@aria-describedby="cookieConsentDialog"]//button[@id="cookieConsentAccept"]').click()
time.sleep(self.sleeptime)
except NoSuchElementException as e:
print(e.msg)
def _validate_file_format(self):
if self.file_format.lower() != "json":
return False
else:
return True
def _one_way_trip(self):
if self.trip_type.lower() == ("one way" or "oneway"):
return True
else:
return False
def _round_trip(self):
if self.trip_type.lower() == ("round trip" or "roundtrip"):
return True
else:
return False
def select_trip_type(self):
""" Method for selecting trip type in search box.
Can be "round trip" or "one way" trip
"""
if self._round_trip():
self.driver.find_element_by_xpath('//li[@aria-controls="roundtrip"]/a').click()
time.sleep(0.5)
if self._one_way_trip():
self.driver.find_element_by_xpath('//li[@aria-controls="oneway"]/a').click()
time.sleep(0.5)
def select_airline(self):
""" Method for selecting airline provider from search form.
Can be "aa" - which represent American Airlines or "all" - which represent all airlines
"""
if self.airline.lower() == "aa":
self.driver.find_element_by_xpath('//select[@id="airline"]/option[@value="AA"]').click()
time.sleep(0.5)
if self.airline.lower() == "all":
self.driver.find_element_by_xpath('//select[@id="airline"]/option[@value="ALL"]').click()
time.sleep(0.5)
def select_time_of_day(self, form):
""" Method for selecting time interval("all day" for now) in which available flights will be returned"""
form.find_element_by_xpath('.//option[@value="120001"]').click()
@staticmethod
def _clear_for_input(input_field, n):
""" Method for clearing input field from default data
"input_field" - selenium object located with webdriver.find method
'n' - number of characters to be deleted
"""
for i in range(0, n):
input_field.send_keys(Keys.BACKSPACE)
def fill_from_form(self):
""" Here we filling form 'from' with appropriate airport code"""
airport = self.driver.find_element_by_xpath('//input[@id="segments0.origin"]')
# clearing form from default text
self._clear_for_input(airport, 4)
airport.send_keys(self.departure)
def fill_destination_form(self):
""" Here we filling destination form ith appropriate airport code"""
airport = self.driver.find_element_by_xpath('//input[@id="segments0.destination"]')
airport.send_keys(self.destination)
def fill_date_form(self, selector, date):
""" Here we filling departure date form with appropriate date"""
self._clear_for_input(selector, 15)
selector.send_keys(date)
def click_search(self):
"""Pressing search form "search" button"""
self.driver.find_element_by_xpath('//button[@id="flightSearchSubmitBtn"]').click()
self._wait_to_load()
def check_for_input_error(self):
""" Here we checking if error box appeared and if so - terminated execution"""
self.driver.refresh()
try:
self.driver.find_element_by_xpath('//div[@class="message-error margin-bottom"]')
raise Exception("Search field was filled wrong")
except NoSuchElementException:
pass
try:
self.driver.find_element_by_xpath('//head/meta[@name="ROBOTS"]')
# text = self.driver.find_element_by_xpath('//body//div[@class="outerContainer"]/p[1]').text
# if text.strip() == "We're working on our site":
raise Exception("Bot was detected!")
except NoSuchElementException:
pass
def _wait_to_load(self):
""" private method for waiting until 'loading' indicator gone"""
time.sleep(0.5)
# initializing timer for 10 sec (means: don't ait for page to load if its tale more than 10 sec)
timer = time.time() + 10
while True:
try:
# this is loading indicator
self.driver.find_element_by_xpath('//div[@class="aa-busy-module"]')
if time.time() > timer:
break
time.sleep(0.5)
except NoSuchElementException:
break
time.sleep(0.5)
def fully_load_results(self):
""" Here we trying to load results, hidden by 'show more' button/link """
# initial wait to load a result page
time.sleep(self.sleeptime)
while True:
try:
self.driver.find_element_by_xpath('//a[@class="showmorelink"]').click()
time.sleep(0.2)
except (NoSuchElementException, ElementNotInteractableException):
break
def click_on_round_trip(self):
self.driver.find_element_by_xpath('//button[@data-triptype="roundTrip"]').click()
self._wait_to_load()
def parse_page(self):
"""Here we scraping flights information from 'search results' page"""
flights_list = []
bs = BeautifulSoup(self.driver.page_source, "html.parser")
# getting all flight available
flights_block = bs.select("li.flight-search-results.js-moreflights")
for flight in flights_block:
# getting departure and arrival time
departure_time = flight['data-departuretime']
arrival_time = flight['data-arrivaltime']
# getting information about amount of stops
try:
stops = flight.select_one("div.span3 div.flight-duration-stops a.text-underline").get_text()
stops = stops.strip()
temp = stops.split("\n")
stops = temp[0]
except AttributeError:
stops = "Nonstop"
# getting flight number and airplane model
flight_numbers_models = []
flight_numbers = flight.select("span.flight-numbers")
plane_model = flight.select("span.wrapText")
for number, name in zip(flight_numbers, plane_model):
temp = {"number": (number.get_text()).strip(),
"airplane": (name.get_text()).strip(),
}
flight_numbers_models.append(temp)
# getting lowest price
lowest_price = flight['data-tripprice']
# for the case, when we need to book ticket directly at airport
if lowest_price == "9999999999":
lowest_price = "N/A"
# dictionary with information about single flight
flight_info = {"depart": departure_time,
"arrive": arrival_time,
"stops": stops,
"price": lowest_price,
"details": flight_numbers_models
}
flights_list.append(flight_info)
# # print debugging info
# print("Depart at: {} Arrive at: {}".format(departure_time, arrival_time))
# print("Stops: {}".format(stops))
# print("Lowest price: ${}".format(lowest_price))
# print("Flight details:")
# for plane in flight_numbers_models:
# print(plane)
# print("-"*80)
return flights_list
@staticmethod
def _generate_file_name(departure, destination, date, file_format):
""" Private method for generating unique file names
:param departure: - airport code from where we departure
:param destination: - code of destination airport
:param date: - date of departure
:param file_format: - format of the file we will save or data to
"""
month, day, year = date.split("/")
time_string = time.strftime("%H%M%S")
return departure + "_" + destination + year + "-" + month + "-" + day + "-" + time_string + "." + file_format
def save_to_json(self, filename, list_of_dict):
""" Method to save scraped data to .json file
:param filename: unique file name generated by ::method::**_generate_file_name**
:param list_of_dict: scraped data, returned by ::method::**parse_page**
"""
name = os.path.join(self.file_path, filename)
with open(name, 'w') as file:
json.dump(list_of_dict, file, indent=2)
# def _get_my_ip(self):
# self.driver.get('https://checkmyip.com/')
# my_ip = self.driver.find_element_by_xpath('//tr[1]/td[2]').text
# print("My current ip was: {}".format(my_ip))
def run(self):
"""Here we executing scraping logic"""
if not self._validate_file_format():
raise ValueError("Unsupported file format for saving data!")
self.press_accept_cookies()
self.select_trip_type()
self.select_airline()
# setting time interval and departure/arrival dates
if self._round_trip():
# checking if we have return date filled:
if self.return_date is None:
raise ValueError("Return date must be filled!")
# here we selecting 'time interval' form
form1 = self.driver.find_element_by_xpath('//select[@id="segments0.travelTime"]')
self.select_time_of_day(form1)
depart_form = self.driver.find_element_by_xpath('//input[@id="segments0.travelDate"]')
self.fill_date_form(depart_form, self.departure_date)
time.sleep(0.5)
form2 = self.driver.find_element_by_xpath('//select[@id="segments1.travelTime"]')
return_form = self.driver.find_element_by_xpath('//input[@id="segments1.travelDate"]')
self.fill_date_form(return_form, self.return_date)
self.select_time_of_day(form2)
time.sleep(0.5)
elif self._one_way_trip():
# selecting 'time interval' form
form = self.driver.find_element_by_xpath('//select[@id="segments0.travelTime"]')
self.select_time_of_day(form)
depart_form = self.driver.find_element_by_xpath('//input[@id="segments0.travelDate"]')
self.fill_date_form(depart_form, self.departure_date)
time.sleep(0.5)
self.fill_from_form()
self.fill_destination_form()
# all search fields filled, and we beginning the search:
self.click_search()
self.check_for_input_error()
self.fully_load_results()
# scraping data from search results:
if self._one_way_trip():
list_results = self.parse_page()
file_name = self._generate_file_name(self.departure, self.destination, self.departure_date, self.file_format)
self.save_to_json(file_name, list_results)
# for round trip we need to scrap 2nd search page with returning flights
if self._round_trip():
self.click_on_round_trip()
self.fully_load_results()
list_results2 = self.parse_page()
file_name = self._generate_file_name(self.departure, self.destination, self.departure_date, self.file_format)
self.save_to_json(file_name, list_results2)
time.sleep(0.5)
# self._get_my_ip()
if __name__ == "__main__":
browser = AmericanAirlines('mia', 'sfo', '02/12/2018', '02/15/2018')
browser.run()
|
aab450116da1a0597767e1062274c9088cf8a9ef | damilarey98/user_validation | /user_validation.py | 1,813 | 3.90625 | 4 | import random
value = "abcdefghijklmnopqrstuvwxyz1234567890"
client_info = {}
n = int(input("How many number of users?: "))
#since range begins from 1, when n=2, it request only one value
for i in range(1, n):
new_client = {}
print("Enter first name of user", i, ":")
fname = input()
print("Enter last name of user", i, ":")
lname = input()
print("Enter email of user", i, ":")
email = input()
new_client["FirstName"] = fname
new_client["LastName"] = lname
new_client["Email"] = email
#comb is the combination of strings to form password
comb1 = fname[0:2]
comb2 = lname[-2:]
comb3 = random.sample(value, 5)
comb3_str = ''.join([str(elem) for elem in comb3])
password = str(fname[0:2] + lname[-2:] + comb3_str)
print("Your password is", password)
new_client["Password"] = password
#adds new clients to the main container which is printed out at the end of program.
new_client_id = len(client_info) + 1
client_info[new_client_id] = new_client
like = input("Do you like the password? [y/n]: ")
if like == "y".lower():
print("Password is secure.")
print("Details of user", i, ":" , new_client)
elif like == "n".lower():
while True:
new_password = input("Enter preffered password: ")
new_client["Password"] = new_password
if len(new_password) < 7:
print("Your password is not strong. Try again")
elif len(new_password) == 7:
print("Still not strong enough, length should be more than 7.")
else:
print("Your new password", new_password)
print("Details of user", i, ":", new_client)
break;
print("Clients added, client infos are now", client_info) |
43d06f5cb81bd0e3c924b99164a4526758979052 | SanamKhatri/school | /student_update.py | 4,554 | 3.828125 | 4 | import student_database
from Student import Student
def update_student():
roll_no = int(input("Enter the roll no:"))
is_inserted = student_database.getStudentDetails(roll_no)
if is_inserted:
student_deatail = student_database.getStudentDetails(roll_no)
print(student_deatail)
print("The detail are")
print("Name= " + student_deatail[1])
print("Address= " + student_deatail[2])
#print("Contact No= " + student_deatail[3])
update_menu = """
1.Only Name
2.Only Address
3.Only Contact No
4.Name and Address
5.Name and Contact
6.Address and Contact
7.Name, Address and Contact"""
print(update_menu)
update_choice = int(input("Enter the update you want to do"))
if update_choice == 1:
update_name = input("Enter the name to update:")
student_object = Student(name=update_name, address=None, contact_no=None)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
elif update_choice == 2:
update_address = input("Enter the address to update:")
student_object = Student(name=None, address=update_address, contact_no=None)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
elif update_choice == 3:
update_contact_no = input("Enter the Contact No to update:")
student_object = Student(name=None, address=None, contact_no=update_contact_no)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
elif update_choice == 4:
update_name = input("Enter the name to update:")
update_address = input("Enter the address to update:")
student_object = Student(name=update_name, address=update_address, contact_no=None)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
elif update_choice == 5:
update_name = input("Enter the name to update:")
update_contact_no = input("Enter the contact no to update:")
student_object = Student(name=update_name, address=None, contact_no=update_contact_no)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
elif update_choice == 6:
update_address = input("Enter the address to update:")
update_contact_no = input("Enter the contact no to update:")
student_object = Student(name=None, address=update_address, contact_no=update_contact_no)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
elif update_choice == 7:
update_name = input("Enter the name to update:")
update_address = input("Enter the address to update:")
update_contact_no = input("Entert the contact no to update")
student_object = Student(name=update_name, address=update_address, contact_no=update_contact_no)
student_object.setRollNo(student_deatail[0])
is_updated = student_database.update_by_name(student_object)
if is_updated:
print("The data is updated")
else:
print("The data is not updated")
else:
print("The data is not in database")
|
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7 | SanamKhatri/school | /teacher_delete.py | 1,234 | 4.1875 | 4 | import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the teacher to delete")
t=Teacher(name=delete_name)
is_deleted=teacher_database.delete_by_name(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
elif delete_choice==2:
delete_address = input("Enter the address of the teacher to delete")
t = Teacher(address=delete_address)
is_deleted = teacher_database.delete_by_address(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process")
elif delete_choice==3:
delete_subject = input("Enter the subject of the teacher to delete")
t = Teacher(subject=delete_subject)
is_deleted = teacher_database.delete_by_subject(t)
if is_deleted:
print("The data is deleted")
else:
print("There was error in the process") |
8103864502cd9649a73788870dabc9ac9cca1c6f | simhaonline/Database-Service-REST-API | /apps/app.py | 4,488 | 3.53125 | 4 | '''
SAMPLE DATABASE AS A SERVICE API
Register a user with username and password
Login a user with username and password
A user gets 10 coins by default when registration completed.
Every time a user logs in 1 coin is used up.
Once all coins are used up the registered user won't be able to log in.
'''
from flask import Flask, jsonify, request, make_response
from flask_restful import Api, Resource, reqparse
from pymongo import MongoClient
import bcrypt
app = Flask(__name__)
api = Api(app)
db_client = MongoClient("mongodb://database:27017")
database = db_client["Webapp"]
users = database["Users"]
class ParseData:
parser = reqparse.RequestParser()
parser.add_argument('username',
type=str,
required=True,
help='The username field is required'
)
parser.add_argument('password',
type=str,
required=True,
help='The password field is required'
)
def user_verification(username, password):
if users.find_one({"Username":username}):
hashed_password = users.find_one({
"Username":username
})["Password"]
if bcrypt.hashpw(password.encode('utf-8'), hashed_password) == hashed_password:
return True
else:
return False
else:
return False
def coins_counter(username):
coins = users.find_one({
"Username":username
})["Coins"]
return coins
class RegisterUser(Resource):
def post(self):
posted_data = ParseData.parser.parse_args()
username = posted_data['username']
password = posted_data['password']
# Check whether a user with the username already exists
if users.find_one({"Username":username}):
message = username + " already exists"
response = jsonify({"message": message})
resp = make_response(response)
resp.headers["Content-Type"] = "application/json"
resp.status_code = 422
return resp
# Encode and encrypt the password
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
# Register the user with default coins
users.insert_one({
"Username":username,
"Password":hashed_password,
"Coins":10
})
message = "User " + username + " successfully registered"
response = jsonify({"message":message})
resp = make_response(response)
resp.headers["Content-Type"] = "application/json"
resp.status_code = 200
return resp
class LoginUser(Resource):
def post(self):
posted_data = ParseData.parser.parse_args()
username = posted_data["username"]
password = posted_data["password"]
# Verify the username and password
verified = user_verification(username, password)
if not verified:
message = "Invalid username or password"
response = jsonify({"message": message})
resp = make_response(response)
resp.headers['Content-Type'] = 'application/json'
resp.status_code = 422
return resp
else:
# Check the coins remaining
coins_remaining = coins_counter(username)
if coins_remaining <= 0:
message = "User out of coins. Trial access expired"
response = jsonify({"message":message})
resp = make_response(response)
resp.headers["Content-Type"] = "application/json"
resp.status_code = 402
return resp
else:
# Remove 1 coin for Logging In
users.update({
"Username":username
},{
"$set":{
"Coins":coins_remaining - 1
}
})
message = "User Logged In"
response = jsonify({
"message":message,
"account_access_chance_remaining":coins_remaining - 1
})
resp = make_response(response)
resp.headers['Content-Type'] = 'application/json'
resp.status_code = 200
return resp
api.add_resource(RegisterUser, '/register')
api.add_resource(LoginUser, '/login')
if __name__ == '__main__':
app.run(host="0.0.0.0")
|
551d2c2c5d240929b8289bd9e86c95bd1c599114 | DRogalsky/dataVisualizationPythonCC | /dice.py | 317 | 3.625 | 4 | from random import randint
class Die:
"a class to represent a single die"
def __init__(self, num_sides=6):
"""assume 6 sides"""
self.num_sides = num_sides
def roll(self):
"""spit out a random number between 1 and the number of sides"""
return randint(1, self.num_sides)
|
b86433902a7cf3e9dcba2d7f254c4318656ca7f7 | heba-ali2030/number_guessing_game | /guess_game.py | 2,509 | 4.1875 | 4 | import random
# check validity of user input
# 1- check numbers
def check_validity(user_guess):
while user_guess.isdigit() == False:
user_guess = input('please enter a valid number to continue: ')
return (int(user_guess))
# 2- check string
def check_name(name):
while name.isalpha() == False:
print('Ooh, Sorry is it your name?!')
name = input('Please enter your name: ')
return name
# begin the game and ask the user to press yes to continue
print(f'Are you ready to play this game : Type Yes button to begin: ')
play = input(f' Type Yes or Y to continue and Type No or N to exit \n ').lower()
if play == 'yes' or play == 'y':
# get user name
name = check_name(input('Enter your name: \n'))
# get the number range from the user
first = check_validity(input('enter the first number you want to play: \n first number: '))
last = check_validity(input('enter the last number of range you want to play: \n last number: '))
# tell the user that range
print (f'Hello {name}, let\'s begin! the number lies between {first} and {last} \n You have 5 trials')
number_to_be_guessed = random.randint(first, last)
# print(number_to_be_guessed)
# Number of times for the guess game to run
run = 1
while run <= 5:
run += 1
user_guess = check_validity(input('what is your guess: '))
# if user guess is in the range
if user_guess in range(first, last):
print('Great beginning, you are inside the right range')
# 1- if the user guess is true
if user_guess == number_to_be_guessed:
print(f'Congratulation, you got it, the number is: {number_to_be_guessed}')
break
# 2- if the guess is high
elif user_guess > number_to_be_guessed:
print(f' Try Again! You guessed too high')
# 3 - if the guess is small
else:
print(f'Try Again! You guessed too small')
# # if the user guess is out of range
else:
print (f'You are out of the valid range, you should enter a number from {first} to {last} only!')
# # when the number of play is over
else:
print(f'{name}, Sorry \n <<< Game is over, Good luck next time , the guessed number is {number_to_be_guessed} >>>')
# # when user type no:
else:
print('Waiting to see you again, have a nice day')
|
f782209a4fb946cb6834f6c60cd33dd93d40b86e | josephevans24/SI106-Files | /ps6.py | 13,035 | 4.09375 | 4 | import test106 as test
# this imports the module 106test.py, but lets you refer
# to it by the nickname test
#### 1. Write three function calls to the function ``give_greeting``:
# * one that will return the string ``Hello, SI106!!!``
# * one that will return the string ``Hello, world!!!``
# * and one that will return the string ``Hey, everybody!``
# You may print the return values of those function calls, but you do not have to.
def give_greeting(greet_word="Hello",name="SI106",num_exclam=3):
final_string = greet_word + ", " + name + "!"*num_exclam
return final_string
#### DO NOT change the function definition above this line (OK to add comments)
# Write your three function calls below
print give_greeting()
print give_greeting(name = 'world')
print give_greeting(greet_word = 'Hey', name = 'everybody', num_exclam = 1)
#### 2. Define a function called mult_both whose input is two integers, whose default parameter values are the integers 3 and 4, and whose return value is the two input integers multiplied together.
def mult_both(x = 3, y = 4):
return x*y
print mult_both()
print "\n---\n\n"
print "Testing whether your function works as expected (calling the function mult_both)"
test.testEqual(mult_both(), 12)
test.testEqual(mult_both(5,10), 50)
#### 3. Use a for loop to print the second element of each tuple in the list ``new_tuple_list``.
new_tuple_list = [(1,2),(4, "umbrella"),("chair","hello"),("soda",56.2)]
for (x, y) in new_tuple_list:
print y
#### 4. You can get data from Facebook that has nested structures which represent posts, or users, or various other types of things on Facebook. We won't put any of our actual Facebook group data on this textbook, because it's publicly available on the internet, but here's a structure that is almost exactly the same as the real thing, with fake data.
# Notice that the stuff in the variable ``fb_data`` is basically a big nested dictionary, with dictionaries and lists, strings and integers, inside it as keys and values. (Later in the course we'll learn how to get this kind of thing directly FROM facebook, and then it will be a bit more complicated and have real information from our Facebook group.)
# Follow the directions in the comments!
# first, look through the data structure saved in the variable fb_data to get a sense for it.
fb_data = {
"data": [
{
"id": "2253324325325123432madeup",
"from": {
"id": "23243152523425madeup",
"name": "Jane Smith"
},
"to": {
"data": [
{
"name": "Your Facebook Group",
"id": "432542543635453245madeup"
}
]
},
"message": "This problem might use the accumulation pattern, like many problems do",
"type": "status",
"created_time": "2014-10-03T02:07:19+0000",
"updated_time": "2014-10-03T02:07:19+0000"
},
{
"id": "2359739457974250975madeup",
"from": {
"id": "4363684063madeup",
"name": "John Smythe"
},
"to": {
"data": [
{
"name": "Your Facebook Group",
"id": "432542543635453245madeup"
}
]
},
"message": "Here is a fun link about programming",
"type": "status",
"created_time": "2014-10-02T20:12:28+0000",
"updated_time": "2014-10-02T20:12:28+0000"
}]
}
# Here are some questions to help you. You don't need to
# comment answers to these (we won't grade your answers)
# but we suggest doing so! They
# may help you think through this big nested data structure.
for a in fb_data['data']:
print a['from']['name']
for a in fb_data['data'][0]['to']['data']:
print a['name']
print fb_data.keys()
print [word['from']['name'] for word in fb_data['data']]
print 'STOP'
# What type is the structure saved in the variable fb_data?
#This is a dictionary type with list rooted in it
# What type does the expression fb_data["data"] evaluate to?
# This evaluates to the list "data" the entire data set is rooted in this list
# What about fb_data["data"][1]?
# This evaluates to the second list that is nested in the entire dictionary. There are two data list within this and this directs you to the second
# What about fb_data["data"][0]["from"]?
#this evaluates to a dictionary
# What about fb_data["data"][0]["id"]?
#This evaluates to a string
# Now write a line of code to assign the value of the first
# message ("This problem might...") in the big fb_data data
# structure to a variable called first_message. Do not hard code your answer!
# (That is, write it in terms of fb_data, so that it would work
# with any content stored in the variable fb_data that has
# the same structure as that of the fb_data we gave you.)
first_message = fb_data['data'][0]['message']
print first_message
print "testing whether variable first_message was set correctly"
test.testEqual(first_message,fb_data["data"][0]["message"])
#### 5. Here's a warm up exercise on defining and calling a function:
# Define a function is_prefix that takes two strings and returns
# True if the first one is a prefix of the second one,
# False otherwise.
def is_prefix(x, y):
a = list(x)
b = list(y)
if y.find(x) == 0:
return True
else:
return False
# Here's a couple example function calls, printing the return value
# to show you what it is.
print is_prefix("He","Hello") # should print True
print is_prefix("Hi","Hello") # should print False
print 'testing whether "Big" is a prefix of "Bigger"'
test.testEqual(is_prefix("Big", "Bigger"), True)
print 'testing whether "Bigger" is a prefix of "Big"'
test.testEqual(is_prefix("Bigger", "Big"), False)
#### 6. Now, in the next few questions, you will ll build components and then a complete program that lets people play Hangman. Below is an image from the middle of a game...
# Your first task is just to understand the logic of the program, by matching up elements of the flow chart above with elements of the code below. In later problems, you'll fill in a few details that aren't fully implemented here. For this question, write which lines of code go with which lines of the flow chart box, by answering the questions in comments at the bottom of this activecode box.
# (Note: you may find it helpful to run this program in order to understand it. It will tell you feedback about your last guess, but won't tell you where the correct letters were or how much health you have. Those are the improvements you'll make in later problems.)
def blanked(word, guesses):
return "blanked word"
def health_prompt(x, y):
return "health prompt"
def game_state_prompt(txt ="Nothing", h = 6, m_h = 6, word = "HELLO", guesses = ""):
res = "\n" + txt + "\n"
res = res + health_prompt(h, m_h) + "\n"
if guesses != "":
res = res + "Guesses so far: " + guesses.upper() + "\n"
else:
res = res + "No guesses so far" + "\n"
res = res + "Word: " + blanked(word, guesses) + "\n"
return(res)
def main():
max_health = 3
health = max_health
secret_word = raw_input("What's the word to guess? (Don't let the player see it!)")
secret_word = secret_word.upper() # everything in all capitals to avoid confusion
guesses_so_far = ""
game_over = False
feedback = "let's get started"
# Now interactively ask the user to guess
while not game_over:
prompt = game_state_prompt(feedback, health, max_health, secret_word, guesses_so_far)
next_guess = raw_input(prompt)
next_guess = next_guess.upper()
feedback = ""
if len(next_guess) != 1:
feedback = "I only understand single letter guesses. Please try again."
elif next_guess in guesses_so_far:
feedback = "You already guessed that"
else:
guesses_so_far = guesses_so_far + next_guess
if next_guess in secret_word:
if blanked(secret_word, guesses_so_far) == secret_word:
feedback = "Congratulations"
game_over = True
else:
feedback = "Yes, that letter is in the word"
else: # next_guess is not in the word secret_word
feedback = "Sorry, " + next_guess + " is not in the word."
health = health - 1
if health <= 0:
feedback = " Waah, waah, waah. Game over."
game_over= True
print(feedback)
print("The word was..." + secret_word)
# What line(s) of code do what's mentioned in box 1?
# Line 21
# What line(s) of code do what's mentioned in box 2?
# Line 29
# What line(s) of code do what's mentioned in box 3?
# Lines 53 and 54
# What line(s) of code do what's mentioned in box 4?
# Lines 31 and 32
# What line(s) of code do what's mentioned in box 5?
# Line 34
# What line(s) of code do what's mentioned in box 6?
# Line 36
# What line(s) of code do what's mentioned in box 7?
# Line 39
# What line(s) of code do what's mentioned in box 8?
# Line 40
# What line(s) of code do what's mentioned in box 9?
# Lines 41-43
# What line(s) of code do what's mentioned in box 10?
# Lines 46-48
# What line(s) of code do what's mentioned in box 11?
# Lines 49-51
#### 7. The next task you have is to create a correct version of the blanked function:
# define the function blanked().
# It takes a word and a string of letters that have been revealed.
# It should return a string with the same number of characters as
# the original word, but with the unrevealed characters replaced by _
def blanked(word, str):
b = ""
for a in word:
if a in str:
b = b + a
else:
b = b + '_'
return b
# a sample call to this function:
print(blanked("hello", "elj"))
#should output _ell_
print "testing blanking of hello when e,l, and j have been guessed"
test.testEqual(blanked("hello", "elj"), "_ell_")
print "testing blanking of hello when nothing has been guessed"
test.testEqual(blanked("hello", ""), "_____")
print "testing blanking of ground when r and n have been guessed"
test.testEqual(blanked("ground", "rn"), "_r__n_")
#### 8. Now you have to create a good version of the health_prompt() function.
# define the function health_prompt(). The first parameter is the current
# health and the second is the the maximum health you can have. It should return a string
# with + signs for the current health, and - signs for the health that has been lost.
def health_prompt(h, mh):
b = mh - h
c = h
d = ('+'*c)+('-'*b)
return d
print(health_prompt(3, 7))
#this should produce the output
#health: +++----
print(health_prompt(0, 4))
#this should produce the output
#health: ----
print "testing health_prompt(3, 7)"
test.testEqual(health_prompt(3,7), "+++----")
print "testing health_prompt(0, 4)"
test.testEqual(health_prompt(0, 4), "----")
#### 9. Now you have a fully functioning hangman program!
def blanked(word, str):
b = ""
for a in word:
if a in str:
b = b + a
else:
b = b + '_'
return b
def health_prompt(h, mh):
b = mh - h
c = h
d = ('+'*c)+('-'*b)
return d
def game_state_prompt(txt ="Nothing", h = 6, m_h = 6, word = "HELLO", guesses = ""):
res = "\n" + txt + "\n"
res = res + health_prompt(h, m_h) + "\n"
if guesses != "":
res = res + "Guesses so far: " + guesses.upper() + "\n"
else:
res = res + "No guesses so far" + "\n"
res = res + "Word: " + blanked(word, guesses) + "\n"
return(res)
def main():
max_health = 5
health = max_health
secret_word = raw_input("What's the word to guess? (Don't let the player see it!)")
secret_word = secret_word.upper() # everything in all capitals to avoid confusion
guesses_so_far = ""
game_over = False
feedback = "let's get started"
# Now interactively ask the user to guess
while not game_over:
prompt = game_state_prompt(feedback, health, max_health, secret_word, guesses_so_far)
next_guess = raw_input(prompt)
next_guess = next_guess.upper()
feedback = ""
if len(next_guess) != 1:
feedback = "I only understand single letter guesses. Please try again."
elif next_guess in guesses_so_far:
feedback = "You already guessed that"
else:
guesses_so_far = guesses_so_far + next_guess
if next_guess in secret_word:
if blanked(secret_word, guesses_so_far) == secret_word:
feedback = "Congratulations"
game_over = True
else:
feedback = "Yes, that letter is in the word"
else: # next_guess is not in the word secret_word
feedback = "Sorry, " + next_guess + " is not in the word."
health = health - 1
if health <= 0:
feedback = " Waah, waah, waah. Game over."
game_over= True
print(feedback)
print("The word was..." + secret_word)
main()
|
020cea430b8939fef9b71ed4836c8bf85bf2211a | josephevans24/SI106-Files | /Final Project/finalproject.py | 18,208 | 3.6875 | 4 | import test106 as test
import csv
def collapse_whitespace(txt):
# turn newlines and tabs into spaces and collapse multiple spaces to just one space
res = ""
prev = ""
for c in txt:
# if not second space in a row, use it
if c == " " or prev == " ":
res = res + c.replace(" ", "")
else:
res = res + c
# current character will be prev on the next iteration
return res
class TextInformation:
"""A class used for helping the user discover simple information about large text files"""
def __init__(self, txt_in):
self.txt = txt_in
def most_freqs_lets(self):
if type(self.txt) == type(""):
dictionary_wanted_output = {}
split = collapse_whitespace(self.txt)
for a in split:
if a not in dictionary_wanted_output:
dictionary_wanted_output[a] = 1
else:
dictionary_wanted_output[a] += 1
keys = dictionary_wanted_output.keys()
first = keys[0]
for b in keys:
if dictionary_wanted_output[b] > dictionary_wanted_output[first]:
first = b
print "%s occurs %d times" % (first, dictionary_wanted_output[first])
elif type(self.txt) == type([]):
dictionary_wanted_output = {}
for a in self.txt:
for b in a:
if b not in dictionary_wanted_output:
dictionary_wanted_output[b] = 1
else:
dictionary_wanted_output[b] += 1
keys = dictionary_wanted_output.keys()
first = keys[0]
for c in keys:
if dictionary_wanted_output[c] > dictionary_wanted_output[first]:
first = b
print "%s occurs %d times" % (first, dictionary_wanted_output[first])
elif type(self.txt) == type({}):
keys = self.txt.keys()
first = keys[0]
for b in keys:
if self.txt[b] > self.txt[first]:
first = b
print "%s occurs %d times" % (first, self.txt[first])
def most_freqs_word(self):
if type(self.txt) == type([]):
dictionary_wanted_output = {}
for a in self.txt:
if a not in dictionary_wanted_output:
dictionary_wanted_output[a] = 1
else:
dictionary_wanted_output[a] += 1
keys = dictionary_wanted_output.keys()
first = keys[0]
for b in keys:
if dictionary_wanted_output[b] > dictionary_wanted_output[first]:
first = b
print "%s occurs %d times" % (first, dictionary_wanted_output[first])
elif type(self.txt) == type(""):
dictionary_wanted_output = {}
split = self.txt.split()
for a in split:
if a not in dictionary_wanted_output:
dictionary_wanted_output[a] = 1
else:
dictionary_wanted_output[a] += 1
keys = dictionary_wanted_output.keys()
first = keys[0]
for b in keys:
if dictionary_wanted_output[b] > dictionary_wanted_output[first]:
first = b
print "%s occurs %d times" % (first, dictionary_wanted_output[first])
elif type(self.txt) == type({}):
keys = self.txt.keys()
first = keys[0]
for b in keys:
if self.txt[b] > txt[first]:
first = b
print "%s occurs %s times" % (first, self.txt[first])
else:
print "Can't get the most frequent word"
def word_count(self, name):
lower_case = self.txt.lower()
txt = lower_case.replace("?", "").replace('"', "").replace(".", "").replace("!", "").replace(",", "")
new_name = name.lower()
count_it = txt.split()
accum = len([word for word in count_it if word == new_name])
print "%s occurs %d times" % (name, accum)
def top_five(self):
dictionary_wanted_output = {}
banana = self.txt.split()
for a in banana:
if a not in dictionary_wanted_output:
dictionary_wanted_output[a] = 1
else:
dictionary_wanted_output[a] += 1
going = sorted(dictionary_wanted_output.keys(), key = lambda x: dictionary_wanted_output[x], reverse = True)
print "For this file the top five most used words are: %s" % (going[:5])
class ShannonGameGuesser:
"""A Shannon Game Guesser class that can tell you how predictive certain texts are based on another text file the user provides"""
def __init__(self, txt_in, guesser_txt_in):
self.txt = txt_in
self.guesser_txt = guesser_txt_in
self.big_dictionary = self.next_letter_frequencies()
self.two_letter_big_dictionary = self.more_letter_frequencies()
self.letters_sorted_by_frequency = "eothasinrdluymwfgcbpkvjqxz".upper()
self.alphabet = self.setUpAlphabet()
self.rls = [('.', ' '), (". ", self.letters_sorted_by_frequency), (' ', self.alphabet), (None, self.alphabet)]
self.length_of_rules = 0
self.set_up_rules()
self.set_up_rules_for_two_letters()
def setUpAlphabet(self):
"""Creates an alphabet of every character in the training data to guess if none of the other rules appeal"""
list_of_alphabet = []
for x in self.txt:
if x not in list_of_alphabet:
list_of_alphabet.append(x)
return "".join(sorted(list_of_alphabet))
def next_letter_frequencies(self):
"""Creates a dictionary of letters and then the frequency of the next letter after"""
r = {}
#creating a blank dictionary
for i in range(len(self.guesser_txt)-1):
#iterating through positions in txt up to the last charcter
if self.guesser_txt[i] not in r:
# if the value of txt[i] not in r (i is an integer)
r[self.guesser_txt[i]] = {}
#make a new dictionary within the dictionary for that chracter
next_letter_freqs = r[self.guesser_txt[i]]
#assings the blank dictionary within the dictionary to next_letter_freqs
next_letter = self.guesser_txt[i+1]
#assings value next letter to be the position after the current character
if next_letter not in next_letter_freqs:
#if the next letter is not in the dictionary for that letter value...
next_letter_freqs[next_letter] = 1
#assing it the value of 1
else:
next_letter_freqs[next_letter] = next_letter_freqs[next_letter] + 1
#if the next letter is already in the dictionary of next letters after the current letter add one to that value
return r
def more_letter_frequencies(self):
"""Creates a dictionary of the past two letters in a text and frequency of the next letter after"""
r = {}
#creating a blank dictionary
for i in range(len(self.guesser_txt)-1):
#iterating through positions in txt up to the last charcter
if self.guesser_txt[i-2: i] not in r:
# if the value of txt[i] not in r (i is an integer)
r[self.guesser_txt[i-2: i]] = {}
#make a new dictionary within the dictionary for that chracter
next_letter_freqs = r[self.guesser_txt[i-2: i]]
#assings the blank dictionary within the dictionary to next_letter_freqs
next_letter = self.guesser_txt[i+1]
#assings value next letter to be the position after the current character
if next_letter not in next_letter_freqs:
#if the next letter is not in the dictionary for that letter value...
next_letter_freqs[next_letter] = 1
#assing it the value of 1
else:
next_letter_freqs[next_letter] = next_letter_freqs[next_letter] + 1
#if the next letter is already in the dictionary of next letters after the current letter add one to that value
return r
def set_up_rules(self):
"""Creates tuples to add to the rules and guess for the text were trying to predict"""
for key in self.big_dictionary:
string_to_append = ""
values = self.big_dictionary[key]
letter_list = sorted(values.keys(), key = lambda x: values[x], reverse = True)
for letter in letter_list:
string_to_append += letter
tuple_to_insert = (key, string_to_append)
self.rls.insert(1,tuple_to_insert)
self.length_of_rules = len(self.rls)
def set_up_rules_for_two_letters(self):
"""Creates rules based on what the past two letters are and what to guess next"""
for next in self.two_letter_big_dictionary:
add_on = ""
more = self.two_letter_big_dictionary[next]
almost = sorted(more.keys(), key = lambda x: more[x], reverse = True)
closer = almost[:15]
for lets in almost:
add_on += lets
tuple_to_insert = (next, add_on)
self.rls.insert(self.length_of_rules, tuple_to_insert)
def guesser(self, prev_txt):
"""Guesser function to be used in the performance function to create a string of guesses for the performance function to try"""
all_guesses = ""
for (suffix, guesses) in self.rls:
try:
if suffix == None or prev_txt[-len(suffix):] == suffix:
all_guesses += guesses
except:
pass
return all_guesses
def performance(self):
"""Shannon Guesser function for how accurate our training data was"""
tot = 0
#begins the accumulation
for i in range(len(self.txt)-1):
#iterate through the lenght of txt up to last character
#print txt[:i+1]
#print txt[:]
to_try = self.guesser(self.txt[:i+1])
#using the guesser function to see if the previous letters used tell us what to guess based on the list rules
guess_count = to_try.index(self.txt[i+1])
#Creates an integer for the index of the next letter of txt to iterate if a guess is possible by passing through the guesser function
tot = tot + guess_count
#Accumulates the total amount of guesses
print "%d characters to guess\t%d guesses\t%.2f guesses per character, on average\n" % (len(self.txt) -1, tot, float(tot)/(len(self.txt) -1))
#prints how many characters to guess in the text, #the total amount of guesses needed to correctly predict the txt, and the average amount of guesses needed per charcter
def most_freq_return(self):
"""Returns a numerical instead of a string value in a dictionary"""
if type(self.txt) == type({}):
keys = self.txt.keys()
first = keys[0]
for b in keys:
if self.txt[b] > self.txt[first]:
first = b
return first
def promptUser():
typeOfFile = ""
firstTry = True
firstChoicefirstTry = True
first_choice = 0
while first_choice != 1 and first_choice != 2:
if firstChoicefirstTry:
firstChoicefirstTry = False
else:
print "You must enter a 1 or a 2"
first_choice = int(raw_input("Press 1 and Enter if you would like to enter your own text. Press 2 if you would like to use text from a file.\n\n"))
if first_choice == 2:
while typeOfFile != "CSV" and typeOfFile != "TXT" and typeOfFile != "csv" and typeOfFile != "txt":
if firstTry:
firstTry = False
else:
print "You must enter CSV or TXT"
typeOfFile = raw_input("Please type the file extension of the file you would like to use: CSV or TXT\n\n")
nameOfTextFile = raw_input("Please give me the name of a file.\n\n")
text_to_guess = ""
if nameOfTextFile.find("csv") == -1 and nameOfTextFile.find("txt") == -1:
if typeOfFile.lower() == "csv":
opened = open(nameOfTextFile+".csv", "rU")
text_to_guess = opened.read()
elif typeOfFile.lower() == "txt":
opened = open(nameOfTextFile+".txt", "r")
text_to_guess = opened.read()
else:
opened = open(nameOfTextFile, "r")
text_to_guess = opened.read()
else:
text_to_guess = raw_input("Please enter the text you want guessed.\n\n")
return text_to_guess
def RuleMaker():
filelib = ""
firstTry = True
firstChoicefirstTry = True
first_choice = 0
while first_choice != 1 and first_choice != 2:
if firstChoicefirstTry:
firstChoicefirstTry = False
else:
print "You must enter a 1 or a 2"
first_choice = int(raw_input(" Now well make the rules! Press 1 if you would like to use your own text or file. Press 2 if you would like to use a file from our library to make your predictive text\n\n"))
if first_choice == 2:
text_to_choose = raw_input("Enter (t) for a CSV of text messages\nEnter (totc) for a Tale of Two Cities\nEnter (w) for The Wizard of Oz\nEnter (b) to use a Biology Textbook\nEnter (4) for the novel I am Number Four\nEnter (g) for The Great Gatsby in Spanish\nEnter (p) for a Programming Textbook\n\n")
text_to_choose =text_to_choose.lower()
if text_to_choose == "t":
message = open("SItextmessages.csv", "rU")
rules = message.read()
if text_to_choose == "totc":
book = open("Tale of Two Cities.txt", "r")
rules = book.read()
if text_to_choose == "w":
play = open("Wizard of Oz.txt", "r")
rules = play.read()
if text_to_choose == "b":
textbook = open("Biology Textbook.txt", "r")
rules = textbook.read()
if text_to_choose == "4":
novel = open("I am Number Four.txt", "r")
rules = novel.read()
if text_to_choose == "g":
spanish = open("El Gran Gatsby.txt", "r")
rules = spanish.read()
if text_to_choose == "p":
programming = open("Programming Textbook.txt", "r")
rules = programming.read()
if first_choice == 1:
typeOfFile = ""
secondTry = True
secondChoicesecondTry = True
second_choice = 0
while second_choice != 1 and second_choice != 2:
if secondChoicesecondTry:
secondChoicesecondTry = False
else:
print "You must enter a 1 or a 2"
second_choice = int(raw_input("You've chosen to use your own text or file! Press 1 and Enter if you would like to make rules from your own text. Press 2 if you would like to use text from a file.\n\n"))
if second_choice == 2:
while typeOfFile != "CSV" and typeOfFile != "TXT" and typeOfFile != "csv" and typeOfFile != "txt":
if secondTry:
secondTry = False
else:
print "You must enter CSV or TXT"
typeOfFile = raw_input("Please type the file extension of the file you would like to use: CSV or TXT (Make sure the file you choose is in the same directory)\n\n")
nameOfTextFile = raw_input("Please give me the name of a file.\n\n")
if nameOfTextFile.find("csv") == -1 and nameOfTextFile.find("txt") == -1:
if typeOfFile.lower() == "csv":
csv_file = open(nameOfTextFile+".csv", "rU")
rules = csv_file.read()
elif typeOfFile.lower() == "txt":
txt_file = open(nameOfTextFile+".txt", "r")
rules = txt_file.read()
else:
opened = open(nameOfTextFile, "r")
rules = opened.read()
else:
rules = raw_input("Please enter the text you want to make your rules from.\n\n")
return rules
text = promptUser()
rules_text = RuleMaker()
print "\n\nInitializing the TextInformation class and the methods you can use it for" +'\n\n'
First_Instance = TextInformation(text)
First_Instance.top_five()
First_Instance.most_freqs_word()
First_Instance.most_freqs_lets()
First_Instance.word_count('Ah')
print "\n\nTime to see the accuracy of our Shannon Game Guesser" +'\n\n'
gameInstance = ShannonGameGuesser(text, rules_text)
gameInstance.performance()
print "That's the end of my project, hope you enjoyed it! If you would like to see a variance in accuracy of the guesser, simply change the position of the two letter rules and the initial rules created. Oddly enough, the two letter guesser is not very accurate."
Practice_Instance = TextInformation("This is a test string for my SI 106 final project. Let's see what TextInformation we can find out")
Testing_Instance = ShannonGameGuesser("This is a test string for my SI 106 final project. Let's see what TextInformation we can find out", rules_text)
test.testEqual(type(Practice_Instance.top_five()), type(Practice_Instance.word_count('Hey')))
test.testEqual(type(Testing_Instance.performance()), type(Practice_Instance.most_freqs_lets()))
test.testEqual(type(Practice_Instance.most_freqs_word), type(Testing_Instance.performance))
|
a9a96b6bc344c5a44a45e61e4a947b1e37543e58 | ricew4ng/Slim-Typer-v1.0 | /code/class_thread_show_time_speed.py | 1,721 | 3.609375 | 4 | #coding:utf8
#显示用时以及计算打字速度的线程的类脚本
import threading
import time
# 创建此实例时,需要传入一个run_window(QtWidgets.QWidget对象)
# running是启动和关闭thread的标志。设置为false,则关闭线程。
class thread_show_time_speed(threading.Thread):
def __init__(self,run_window):
super(thread_show_time_speed,self).__init__()
self.run_window = run_window
self.running = True
self.waiting = False
self.words = 0 #字数初始化 //用于计算打字速度
def run(self):
time_start = time.time()
self.repeat = True
while self.running:
if self.waiting == False:
seconds = self.time_used(time_start,time.time())
if self.repeat:
self.repeat = False
else:
if self.words > 0:
self.words-=1
if seconds:
self.run_window.type_speed_set.setText('%.2f0字/秒'%(self.words/seconds))
time.sleep(0.5)
#在run_window界面的用时Label处 显示用时
#返回已花的时间(秒) int型
def time_used(self,time1,time2):
time_used = time2 - time1
all_seconds = time_used
hours_used = int(time_used // 3600 )
time_used = time_used % 3600
minutes_used = int(time_used // 60)
seconds_used = int(time_used % 60)
time_used = str(hours_used)+'时'+str(minutes_used)+'分'+str(seconds_used)+'秒'
self.run_window.time_used_set.setText(time_used)
return int(all_seconds)
#用于计算英文打字速度
def add_number(self):
self.words+=1
#用于计算汉字打字速度
def add_type_number(self,num):
self.words+=num
#用于终止线程运行及self.words初始化
def terminate(self):
self.words = 0
self.running = False
def wait(self):
self.waiting = True
|
67df8cb2c8409510d9b0d1f0c859402db1993e93 | aswarth123/DevoWorm | /parse-beautiful-stone-soup.py | 298 | 3.515625 | 4 | import lxml.etree as ET // uses lxml for parsing
content = "data.xml"
doc = ET.fromstring(content)
data = doc.find('data of interest') //tag that defines source of data
print(data.text)
info = doc.find('information') //tag that defines metadata
print(info.tail)
outfile = "test.txt"
FILE.close |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.