blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
9b5e4adb5cdb97f1185d3baa4d6e315aeb20c466 | Mr-Loony/Lottery-Python | /GamblingLottery.py | 660 | 3.890625 | 4 | from random import randint, random
num2 = []
numm3 = []
maxnr = 0
minnr = 100
print("Welcome to Solomon's Lottery!")
n = int(input("Enter sum: "))
for k in range(5):
m = int(input("Please enter number: "))
num2.append(m)
y = 0
num=[]
for i in range(10):
random=randint(1,20)
while random in num:
random=randint(1,20)
num.append(random)
for nr in num2:
if nr in num:
y = y+1
# new stuff. It just adds a * on numbers you guessed.
for nm in num:
if nm in num2:
print("*",end="")
nt = nt+1
print(nm,"",end="")
print("\n"+"You won: ",n*y,"$")
print("You guessed",nt,"out of 10 numbers.")
|
38a960b6810f1602463d2d870539e97259886fb8 | Hi-Tree/Phys661 | /Assignment2.py | 2,714 | 3.625 | 4 | #### Meri Khurshudyan
#### Assignment 2
from itertools import product
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import random
#@@@@@@@@@@@@@@@@@@@@@@@ Needed Functions @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
######################## Ideal Case 2 Dice #############################
def ideal(_N_, k):
t = [list(range(1,k)) for x in range(2)] #creates two dice
g = list(map(sum,list(product(*t)))) #gives all possible combinations
z = Counter(g) #counts the occurances of each combination
h = np.array(list(z.items())).astype(np.float) # convert the dict to an array
total = sum(h[:,1]) # gives the total probabilities
h[:,1] = (h[:,1]/total)*_N_ # where N is the number of times rolled the dice
return h
####################### Single Dice #######################################
def experimental1(_N_):
rand1 = [random.randint(1,6) for x in range(_N_)]
m = Counter(rand1)
h = np.array(list(m.items())).astype(np.float)
total = sum(h[:,1])
h[:,1] = h[:,1]*(100/total)
return h
####################### Experimental Case 2 Dice #########################
def experimental(_N_):
rand1 = [random.randint(1,6) for x in range(_N_)]
rand2 = [random.randint(1,6) for x in range(_N_)]
h = [rand1[i]+rand2[i] for i in range(_N_)]
g = Counter(h)
return g
###################### Biased Experimental Case 2 Dice ###################
def biased(_N_):
sides = [1,2,3,4,5,6]
rand1 = random.choices(sides,(10,10,20,40,70,5), k = _N_)
rand2 = random.choices(sides,(10,10,10,80,40,30), k = _N_)
h = [rand1[i]+rand2[i] for i in range(_N_)]
g = Counter(h)
return g
########################### Graphs ######################################
######################## Remove Quotes for Single Dice ###################
'''
N_ = 1000
probab = [float((100/6))]*6
range_ = range(1,7)
d = experimental1(N_)
plt.plot(range_, probab,"o", color = "red")
plt.bar(d[:,0],d[:,1])
plt.xlabel("Side")
plt.ylabel("Outcome (%)")
plt.title("Single Dice")
plt.show()
'''
####################### Remove Quotes for Part I #########################
'''
h = ideal(1000,7)
x = h[:,0]
y = h[:,1]
b = experimental(1000)
m = b.keys()
n = b.values()
plt.bar(m,n, color = 'pink')
plt.plot(x,y,'o', color = 'purple')
plt.ylabel("Frequency")
plt.xlabel("Sum For Roll")
plt.title("Fair Dice")
plt.show()
'''
###################### Remove Quotes for Part II #########################
'''
h = ideal(1000,7)
x = h[:,0]
y = h[:,1]
_h_ = biased(1000)
_x_ = _h_.keys()
_y_ = _h_.values()
plt.bar(_x_,_y_, color = 'red')
plt.plot(x,y,'o', color = 'purple')
plt.ylabel("Frequency")
plt.xlabel("Sum For Rolls")
plt.title("Unfair Dice")
plt.show()
'''
|
489b43668b8cabd8c72506a32119f58462a22a70 | kvizconde/Pokemon-Tamagotchi | /user_interface.py | 4,110 | 4.21875 | 4 | from constants import Constants
from egg import Egg
class UserInterface:
"""
This is the user interface class where the game gets executed by the user
The class consists of the menRus that the user uses to interact with their pokemon
"""
@staticmethod
def menu(pokeball):
"""
This method implements the main menu for the user interaction
:param pokeball: the origins of your pokemon, the Egg
:return: the user's input
"""
print(f"\nWhat would you like to do with {pokeball.get_name()}? \n")
print(f"1. Play with {pokeball.get_name()}")
print(f"2. Feed {pokeball.get_name()}")
print(f"3. Check {pokeball.get_name()}'s status")
print("4. Exit the game\n")
return input()
@staticmethod
def game_menu():
"""
This method implements the game menu. It iterates through the available games
and displays them to the user
:return: the choice of the user, an Int
"""
game_list = Constants.get_game_list()
while True:
counter = 1
print("\nGames: ")
for game in game_list:
print(f"{counter}. {game[0]}")
counter += 1
print("Please choose a game: ")
choice = input()
if not choice.isnumeric() or int(choice) > len(game_list) or int(choice) < 1:
print("Sorry, your choice is invalid!")
print("Choose Again: ")
else:
return int(choice)
@staticmethod
def food_menu():
"""
This method implements the food menu. It iterates through the available food
and displays them to the user
:return: the choice of the user, an Int
"""
food_list = Constants.get_food_list()
while True:
counter = 1
print("\n🍽 Food:")
for food in food_list:
print(f"{counter}. {food}")
counter += 1
print("\nPlease choose a food item: ")
choice = input()
if not choice.isnumeric() or int(choice) > len(food_list) or int(choice) < 1:
print("Sorry, your choice is invalid!")
print("Choose Again: ")
else:
return int(choice)
def main():
pokeball = Egg()
answer_input = ["Y", "N", "M", "F"]
answer_input = [answer.casefold() for answer in answer_input]
while True:
if isinstance(pokeball, Egg):
print("You received a new Pokeball, would you like to see your new Pokemon? (Y/N):")
choice = input().casefold()
if choice == answer_input[0]: # YES
pokeball = pokeball.hatch()
print("========================")
print("You got...", Egg.intro_header_name())
print("========================")
elif choice == answer_input[1]: # NO
print("Sad to see you go. Goodbye! 👋")
return
else:
print("Sorry, your choice is invalid!\n")
else:
choice = UserInterface.menu(pokeball)
if choice == "1": # game
game_choice = UserInterface.game_menu()
pokeball.play_game(game_choice)
elif choice == "2": # feed
feed_choice = input("(F)ood or (M)edicine: ").casefold()
if feed_choice == answer_input[2]: # MEDICINE
pokeball.eat_medicine()
elif feed_choice == answer_input[3]: # FOOD
food_choice = UserInterface.food_menu()
pokeball.eat_food(food_choice)
elif choice == "3": # status check
status = pokeball.check_status()
if status == -1: # checks the returned status of dead pokemon
pokeball = Egg()
elif choice == "4":
print("Thanks for playing, Goodbye! 👋")
return
if __name__ == '__main__':
main()
|
7646890051144b6315cd22fd1b5e04a44d9b266a | jabedude/python-class | /projects/week3/jabraham_guessing.py | 1,625 | 4.1875 | 4 | #!/usr/bin/env python3
'''
This program is an implementation of the "High-Low Guessing Game".
The user is prompted to guess a number from 1 to 100 and the
program will tell the user if the number is greater, lesser, or
equal to the correct number.
'''
from random import randint
def main():
'''
This function is the entry point of the program and handles user
interaction with the game.
'''
# CONSTANTS #
ANSWER = randint(1, 100)
BANNER = '''Hello. I'm thinking of a number from 1 to 100...
Try to guess my number!'''
PROMPT = "Guess> "
# MESSAGES #
err_msg = "{} is an invalid choice. Please enter a number from 1 to 100."
suc_msg = "{} was correct! You guessed the number in {} guess{}."
wrong_msg = "{} is too {}!"
print(BANNER)
valid_guesses = 0
while True:
user_input = input(PROMPT)
valid_guesses += 1
try:
user_input = int(user_input)
if user_input not in range(1, 101):
raise ValueError
elif user_input == ANSWER:
guess_ending = "es"
if valid_guesses == 1:
guess_ending = ""
print(suc_msg.format(user_input, valid_guesses, guess_ending))
exit(0)
else:
guess_clue = "high"
if user_input < ANSWER:
guess_clue = "low"
print(wrong_msg.format(user_input, guess_clue))
except ValueError:
valid_guesses -= 1
print(err_msg.format(user_input))
if __name__ == "__main__":
main()
|
fcdebbb78ba2d4c5b41967801b0d537c35e85c3a | jabedude/python-class | /chapter5/ex6.py | 384 | 4.125 | 4 | #!/usr/bin/env python3
def common_elements(list_one, list_two):
''' returns a list of common elements between list_one and list_two '''
set_one = set(list_one)
set_two = set(list_two)
return list(set_one.intersection(set_two))
test_list = ['a', 'b', 'c', 'd', 'e']
test_list2 = ['c', 'd', 'e', 'f', 'g']
test = common_elements(test_list, test_list2)
print(test)
|
973a9b54dcc92e28d4695050050ae0efc85f7982 | jabedude/python-class | /chapter4/ex4.py | 628 | 4.03125 | 4 | #!/usr/bin/env python3
text_set = set()
freq_dict = dict()
duplicate_count = 0
while 1:
data = input("Please enter a line (q to quit): ")
if data == "q":
break
for word in data.split():
if word in text_set:
duplicate_count += 1
freq_dict[word] += 1
text_set.add(word)
continue
freq_dict[word] = 1
text_set.add(word)
print(sorted(text_set))
print("User gave {} unique entries".format(len(text_set)))
for word, freq in sorted(freq_dict.items(), key=lambda x: x[1], reverse=True):
print("{} occured {} times".format(word, freq))
|
53c1ca380af737aabe9ce0e265b18011a3e290a2 | jabedude/python-class | /chapter9/ex4.py | 655 | 4.3125 | 4 | #!/usr/bin/env python3
''' Code for exercise 4 chapter 9 '''
import sys
def main():
'''
Function asks user for two file names and copies the first to the second
'''
if len(sys.argv) == 3:
in_name = sys.argv[1]
out_name = sys.argv[2]
else:
in_name = input("Enter the name of the input file: ")
out_name = input("Enter the name of the output file: ")
with open(in_name, "r") as in_file, open(out_name, "w") as out_file:
while True:
line = in_file.readline()
if not line:
break
out_file.write(line)
if __name__ == "__main__":
main()
|
3cb7470e40d147e81250cc35de89851c0dc453e6 | jabedude/python-class | /chapter9/ex7.py | 597 | 3.875 | 4 | #!/usr/bin/env python3
''' Code for exercise 7 chapter 9 '''
import sys
def main():
''' Docstring '''
in_one = sys.argv[1]
in_two = sys.argv[2]
set_one = set()
set_two = set()
with open(in_one, "r") as file_one, open(in_two, "r") as file_two:
while True:
line_one = file_one.readline()
line_two = file_two.readline()
if not line_one or not line_two:
break
set_one.add(line_one.strip())
set_two.add(line_two.strip())
print(set_one & set_two)
if __name__ == "__main__":
main()
|
c722a49a7f8b4b80ed4238b53759e922299957e2 | jabedude/python-class | /chapter7/restaurant.py | 1,686 | 4.21875 | 4 | #!/usr/bin/env python3
class Category():
''' Class represents Category objects. Only has a name '''
def __init__(self, name):
self.name = name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
def __str__(self):
return self.name
class MenuItem(Category):
''' Class represents a MenuItem object. Has a name, description, and price. '''
def __init__(self, name, desc, price):
super().__init__(name)
self.desc = desc
self.price = price
@property
def desc(self):
return self._desc
@desc.setter
def desc(self, desc):
self._desc = desc
@property
def price(self):
return self._price
@price.setter
def price(self, price):
self._price = price
def __str__(self):
return "Name: {}\nDescription: {}\nPrice: ${}".format(self.name, self.desc, self.price)
class Restaurant():
'''
Class represents a Restaurant object, a list of MenuItems. Has add() method
to add MenuItems to list.
'''
def __init__(self, *menu_items):
self.menu_items = list(menu_items)
@property
def menu_items(self):
return self._menu_items
@menu_items.setter
def menu_items(self, menu_items):
self._menu_items = menu_items
def add(self, item):
''' Method adds MenuItem to Restaurant obj '''
self.menu_items.append(item)
def __str__(self):
results = []
for num, item in enumerate(self.menu_items):
results.append("Item {}\n{}\n".format(num + 1, item))
return "\n".join(results)
|
3de09ed4a2e79290073962087fccd9a10ebcc245 | UlisesND/CYPUlisesND | /libro/problemas_resueltos/capitulo2/problema2_10.py | 706 | 3.953125 | 4 | A = int(input("introduce un numero entero"))
B = int(input("introduce un otro numero entero positivo"))
C = int(input("introduce un otro numero entero positivo"))
if A > B:
if A > C:
print (f"{A} es el mayor")
elif A == C:
print(f"{A} y {C} son iguales, y son los mayores")
else:
print(f"{C} es el mayor")
elif A == B:
if A > C:
print(f"{A} y {B} son iguales, y los mayores")
elif A == C:
print("los tres son iguales a {B}")
else:
print(f"{C} es el mayor")
elif B > C :
print(f"{B} es el mayor")
elif B == C:
print(f"{B} y {C} son iguales, y los mayores")
else:
print(f"{C} es el mayor")
print("fin del programa")
|
9e3dac800bd632b85beb9c905687e1141547732c | UlisesND/CYPUlisesND | /listas2.py | 1,361 | 4.40625 | 4 | # arreglos
#lectura
#escritura/ asignacion
#actualizacion: insercion, eliminacion, modificacion
#busqueda
#escritura
frutas = ["Zapote", "Manzana" , "Pera", "Aguaquate", "Durazno", "uva", "sandia"]
#lectura, el selector [indice]
print (frutas[2])
# Lectura con for
#for opcion 1
for indice in range (0,7,1):
print (frutas[indice])
print ("-------")
# for opcion 2 -- por un iterador each
for fr in frutas:
print (fr)
#asignacion
frutas[2]="melon"
print (frutas)
#insercion al final
frutas.append("Naranja")
print(frutas)
print(len(frutas))
frutas.insert(2,"limon")
print(frutas)
print(len(frutas))
frutas.insert(0, "mamey")
print(frutas)
#eliminacion con pop
print(frutas.pop())
print(frutas)
print(frutas.pop(1))
print(frutas)
frutas[2]="limon"
frutas.append("limon")
print(frutas)
frutas.remove("limon")
print(frutas)
#ordenamiento
frutas.sort()
print(frutas)
frutas.reverse()
print(frutas)
#busqueda
print(f"El limon esta en la posicion, {frutas.index('limon') }")
print(f"El limon esta {frutas.count('limon')} veces en la lista")
#concatenar
print(frutas)
otras_frutas = ["rambutan","mispero", "liche","pitahaya"]
frutas.extend(otras_frutas)
print(frutas)
# copiar
copia=frutas
copia.append("naranja")
print(frutas)
print(copia)
otracopia = frutas.copy()
otracopia.append("fresa")
otracopia.append("fresa")
print(frutas)
print(otracopia)
|
a7408410098390dad499a6b0663f680d9a6950a7 | UlisesND/CYPUlisesND | /libro/problemas_resueltos/capitulo2/problema2_8.py | 476 | 3.859375 | 4 | COMPRA = float (input("Ingresa tu monto de compra: "))
if COMPRA < 500 :
PAGAR = COMPRA
else:
if COMPRA <= 1000 :
PAGAR = COMPRA - (COMPRA +0.05)
else:
if COMPRA <= 7000 :
PAGAR = COMPRA - (COMPRA * 0.11)
else:
if COMPRA <= 15000 :
PAGAR = COMPRA - (COMPRA * 0.18)
else:
PAGAR = COMPRA - (COMPRA * 0.25)
print(f"El total a pagar es: { PAGAR }")
print(f"Fin del programa")
|
13af2fef7cc8e5fb279625a5ad6fd38a8044f25a | UlisesND/CYPUlisesND | /libro/problemas_resueltos/capitulo1/problema1_2.py | 196 | 3.734375 | 4 | BASE = float(input("Base del Triangulo:"))
ALTU = float(input("Altura del Triangulo:"))
SUP = (BASE * ALTU)/2
print(f" El area del triangulo con base {BASE} U.y altura {ALTU} U. es: {SUP} U^2.")
|
edf5c6a444671cfd511730b7e49695cb954f7dca | obhutara/Python | /untitled1.py | 2,086 | 3.640625 | 4 | import sys
import os.path
import nltk
import io
import itertools
import operator
import string
import re
import collections
from nltk.corpus import stopwords
stop_words=stopwords.words('english')
def readfile():
try:
filename=sys.argv[1]
if not os.path.isfile(filename):
print("This file does not exist")
with open(filename,"r",encoding="utf8") as file:
data = file.read()
return(data)
except IndexError:
print("This file does not exist")
def frequencyletters(data):
lettercount = collections.Counter(data.lower())
for letter,count in lettercount.most_common():
if letter in string.ascii_letters:
print(letter,count)
print('\n')
def transform(data): #function to clean and split the content of the text
data = re.sub(r'[^\w\s]','',data)
words = data.lower().split()
print('Number of words in text file')
print(len(words))
print('\n')
return(words)
def removestopwords(words): #function to remove commonly used conjunctions etc
words = [w for w in words if w not in stop_words]
return(words)
def distinctwords(words): #computes and prints count of unique words and also returns stopword removed string
print('Count of distinct words')
print(len(set(w.lower() for w in words)))
print('Most frequenct words')
wordsjoined = ' '.join(words)
return(wordsjoined)
def frequentwords(words):
frequentwords=collections.Counter(words).most_common(5)
for word,count in frequentwords:
print(word,count)
countflag=1
for word,count in frequentwords:
nextcountflag = collections.Counter()
for i,ind in enumerate(words):
if ind == word:
ind=words[i+1]
nextcountflag[ind]+=1
print('\n')
print('\n')
print("{}({} times)".format(word,count))
frequentwords2=nextcountflag.most_common()
for word2,count2 in frequentwords[0:5]:
print("->{}({} times)".format(word2,count2))
countflag= countflag+1
def main():
data=readfile()
frequencyletters(data)
words=transform(data)
words=removestopwords(words)
distinctwords(words)
frequentwords(words)
if __name__ == '__main__':
main()
|
bbdbdc8af0280e882f2a87b9ce0d4238db261c72 | rkporwal/MachineLearning | /Feature_selection.py | 1,406 | 3.515625 | 4 | import pandas as pd
import numpy as np
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
data=pd.read_csv("CellPhone.csv")
X = data.iloc[:,0:20] #independent columns
y = data.iloc[:,-1] #target column i.e price range
#univariate selection
#apply SelectKBest class to extract top 10 best features
bestfeatures = SelectKBest(score_func=chi2, k=10)
fit = bestfeatures.fit(X,y)
dfscores = pd.DataFrame(fit.scores_)
dfcolumns = pd.DataFrame(X.columns)
#concat two dataframes for better visualization
featureScores = pd.concat([dfcolumns,dfscores],axis=1)
featureScores.columns = ['Specs','Score'] #naming the dataframe columns
print(featureScores.nlargest(10,'Score')) #print 10 best features
## Features importance
from sklearn.ensemble import ExtraTreesClassifier
import matplotlib.pyplot as plt
model = ExtraTreesClassifier()
model.fit(X,y)
print(model.feature_importances_)
#plot graph of feature importances for better visualization
feat_importances = pd.Series(model.feature_importances_, index=X.columns)
feat_importances.nlargest(10).plot(kind='barh')
plt.show()
##Correlation Matrix with HeatMap
import seaborn as sns
#get correlations of each features in dataset
corrmat = data.corr()
top_corr_features = corrmat.index
plt.figure(figsize=(20,20))
#plot heat map
g=sns.heatmap(data[top_corr_features].corr(),annot=True,cmap="RdYlGn")
|
ed544f53a3a328aff0bdd1246a7a1db33867589c | Dulal-12/Python-basic-300 | /50+/Test6.py | 202 | 4.15625 | 4 | #Find BMI
height = float(input("Enter height ft(foot) : "))
weight = float(input("Enter weight Kg : "))
height = (height*12*2.54)/100
BMI = round(weight/height**2)
print(f'Your BMI is {BMI} KGM^2')
|
e43935bb36fceca09cca540c9a9049a56b469b36 | abigdream84/PythonStudy | /.metadata/.plugins/org.eclipse.core.resources/.history/a0/d0854a1af9db001612a6e4ac6047d554 | 178 | 3.78125 | 4 | #!/usr/bin/env python
class Car:
def __init__(self, brand, colour):
self.Brand = brand
self.Colour = colour
car1 = Car('BMW', 'Red')
print car1.Brand |
46571f9cb4192020003720aa3515a5e08b76ef57 | YeahHuang/Leetcode | /572_subTreeofAnotherTree.py | 1,728 | 3.671875 | 4 |
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def convert(p):
return "^" + str(p.val) + "#" + convert(p.left) + convert(p.right) if p else "$"
return convert(t) in convert(s)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def equal(self, s: TreeNode, t:TreeNode) -> bool:
if s is None and t is None:
return True
if s is None or t is None:
return False
return s.val == t.val and self.equal(s.left, t.left) and self.equal(s.right, t.right)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if t is None:
return True
if s is None:
return False
return self.equal(s,t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
#Sol3 96ms
def isSubtree(self, s, t):
from hashlib import sha256
def hash_(x):
S = sha256()
S.update(x)
return S.hexdigest()
def merkle(node):
if not node:
return '#'
m_left = merkle(node.left)
m_right = merkle(node.right)
node.merkle = hash_(m_left + str(node.val) + m_right)
return node.merkle
merkle(s)
merkle(t)
def dfs(node):
if not node:
return False
return (node.merkle == t.merkle or
dfs(node.left) or dfs(node.right))
return dfs(s) |
c17191f6336a29b888d7a6c2aec14adf69965107 | YeahHuang/Leetcode | /37_sudokuSolver.py | 1,865 | 3.625 | 4 | class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
def dfs(x, y, board, row, col, squa) -> bool:
if y==9:
if x == 8:
return True
else:
x, y = x+1, 0
while (board[x][y]!='.'):
y+=1
if y==9:
if x == 8:
return True
else:
x, y = x+1, 0
avail = row[x] & col[y] & squa[x//3*3 + y//3]
for num in avail:
board[x][y] = num
#print(num, row[x], col[y],squa[x//3*3 + y//3])
row[x].remove(num)
col[y].remove(num)
squa[x//3*3 + y//3].remove(num)
if dfs(x, y+1, board, row, col, squa):
return True
row[x].add(num)
col[y].add(num)
squa[x//3*3 + y//3].add(num)
board[x][y] = '.' #WA 一次 一开始忘记复原了
return False
"""
Do not return anything, modify board in-place instead.
"""
row, col, squa = [set() for _ in range(9)], [set() for _ in range(9)], [set() for _ in range(9)]
for i in range(9):
row.append(set())
col.append(set())
squa.append(set())
for j in range(1,10):
row[i].add(str(j))
col[i].add(str(j))
squa[i].add(str(j))
for i in range(9):
for j in range(9):
if board[i][j]!='.':
row[i].remove(board[i][j])
col[j].remove(board[i][j])
squa[i//3*3 + j//3].remove(board[i][j])
dfs(0, 0, board, row, col, squa)
|
3293518a918fbcaea2bcaffd73aa4513ef6b2651 | YeahHuang/Leetcode | /1110_deleteNodesandReturnForest.py | 2,281 | 3.625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.to_delete = set()
self.forests = {}
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
def dfs(tree):
if tree is None:
return
if tree.val in self.to_delete:
self.to_delete.remove(tree.val)
if tree.left:
if tree.left.val not in self.to_delete: #WA一次 忘记写这个判断条件了
self.forests[tree.left.val] = None
dfs(tree.left)
if tree.right:
if tree.right.val not in self.to_delete:
self.forests[tree.right.val] = None
dfs(tree.right)
return
else:
ret = TreeNode(tree.val)
ret.left = dfs(tree.left)
ret.right = dfs(tree.right)
if ret.val in self.forests:
self.forests[ret.val] = ret
return ret
self.to_delete = set(to_delete)
if root.val not in self.to_delete:
self.forests[root.val] = None
dfs(root)
return [v for k, v in self.forests.items()]
#Improved: 92ms -> 76ms 稍微省了一咩咩空间14.4M->14.3M
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
to_delete = set(to_delete)
forests = []
def dfs(tree:TreeNode, parent_deleted:bool):
if tree is None:
return
if tree.val in to_delete:
to_delete.remove(tree.val)
if tree.left:
dfs(tree.left, True)
if tree.right:
dfs(tree.right, True)
return
else:
ret = TreeNode(tree.val)
ret.left = dfs(tree.left, False)
ret.right = dfs(tree.right, False)
if parent_deleted:
forests.append(ret)
return ret
dfs(root, True)
return forests
|
b5d423922c0c5881695d626f154222caad1778fc | YeahHuang/Leetcode | /289_game_of_life.py | 2,345 | 3.546875 | 4 | class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
def checkNeighbor(board, x, y):
#一开始单独写了8个if 还是不够有统一性吖
return 0<=x<len(board) and 0<=y<len(board[0]) and abs(board[x][y])==2
debug = False
for i in range(len(board)):
for j in range(len(board[0])):
board[i][j] += 1
#board = [[board[i][j]+1 for j in range(len(board[0]))] for i in range(len(board))] 这样不会被改变
dx = [-1, -1, -1, 0, 0, 1, 1, 1]
dy = [-1, 0, 1, -1, 1, -1, 0, 1]
for i in range(len(board)):
for j in range(len(board[0])):
live_num = 0
for k in range(8): #for I in range(-1:1): for J in range(-1:1)
live_num += checkNeighbor(board, i+dx[k],j+dy[k])
if board[i][j] == 1 and live_num == 3:
board[i][j] *= -1
if board[i][j] == 2 and (live_num < 2 or live_num > 3):
board[i][j] *= -1
m = {2:1, 1:0, -2:0, -1:1}
for i in range(len(board)):
for j in range(len(board[0])):
board[i][j] = m[board[i][j]]
#board = [ [m[board[i][j]] for j in range(len(board[0]))] for i in range(len(board))]
#对于infinite 如果无法把所有的存于内存 live的也属于稀疏矩阵 那么之前的方法就不太好 摘自@Stefan
#不如把live的存好 emmm 但是emmm 其实这里还没有很看懂 需要继续消化吖
def gameOfLifeInfinite(self, live):
ctr = collections.Counter((I, J)
for i, j in live
for I in range(i-1, i+2)
for J in range(j-1, j+2)
if I!= i or J!=j)
return {ij for ij in ctr
if ctr[ij] == 3 or ctr[ij]==2 and ij in live}
def gameOfLife(self, board):
live = {(i,j) for i, row in enumerate(board) for j, live in enumerate(row) if live}
live = self.gameOfLifeInfinite(live)
for i, row in enumerate(board):
for j in range(len(row)):
row[j] = int((i,j) in live)
|
fe27afe34b5f85623fd8896b55e1deccf6f89bee | YeahHuang/Leetcode | /70_climingStairs.py | 262 | 3.5625 | 4 | class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
f = [0] * (n+3)
f[1] = 1
f[2] = 2
for i in range(3,n+1):
f[i] = f[i-1] + f[i-2]
return f[n] |
92ad4e42c960dde8f6a0849af5ba6a02f6be47a0 | YeahHuang/Leetcode | /211_wordDictionary.py | 2,292 | 3.859375 | 4 | class WordNode:
def __init__(self):
self.children = collections.defaultdict(WordNode)
self.end = False
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = WordNode()
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
cur = self.root
for c in word:
cur = cur.children[c]
cur.end = True
def search(self, word: str, cur=None) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
if cur is None:
cur = self.root
is_exist, flag = True, False
for i, c in enumerate(word):
if c=='.':
flag = False
for child in cur.children:
if self.search(word[i+1:], child):
flag = True
break
is_exist = flag
break
else:
cur = cur.children.get(c) #这里为了判定是否为空 由直接新建 -> .get 函数 注意一下
if cur is None:
is_exist = False
break
if is_exist and flag==False and cur.end==False:
is_exist = False
return is_exist
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
cur = self.root
for c in word:
cur = cur.children[c]
cur.end = True
def search(self, word):
cur = self.root
is_exist = True
for c in word:
cur = cur.children.get(c) #这里为了判定是否为空 由直接新建 -> .get 函数 注意一下
if cur is None:
is_exist = False
break
return is_exist and cur.end
def startsWith(self, prefix):
cur = self.root
is_prefix = True
for c in prefix:
cur = cur.children.get(c) #这里为了判定是否为空 由直接新建 -> .get 函数 注意一下
if cur is None:
is_prefix = False
break
return is_prefix |
d0c7e8a295b6f731d9f1f1872906b4109a12c006 | YeahHuang/Leetcode | /987_verticalOrderTraversalofBT.py | 2,560 | 3.734375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution: #52ms
def __init__(self):
self.opt = []
self.neg = []
def verticalTraversal(self, root: TreeNode):
self.myVerticalTraversal(root, 0, 0)
tmp = self.neg[::-1] + self.opt
ret = []
for i,x in enumerate(tmp): #一开始没有读懂题目细节 包括bottom-down + value重叠
x.sort()
ret.append([])
for xx in x:
ret[i].append(xx[1])
return ret
def myVerticalTraversal(self, tree: TreeNode, x:int, y:int):
if tree is None: #不如 if tree:
return
if x >= 0:
if x == len(self.opt):
self.opt.append([(y, tree.val)])
else:
self.opt[x].append((y, tree.val))
else:
if -x-1 == len(self.neg):
self.neg.append([(y, tree.val)])
else:
self.neg[-x-1].append((y, tree.val))
self.myVerticalTraversal(tree.left, x-1, y+1)
self.myVerticalTraversal(tree.right,x+1, y+1)
#Improved 1: collections.defaultdict(list) 来代替前面的neg&pos
class Solution:
def __init__(self):
self.list = collections.defaultdict(list)
def verticalTraversal(self, root: TreeNode):
self.myVerticalTraversal(root, 0, 0)
ret = [[] for _ in range(len(self.list))]
ordered = collections.OrderedDict(sorted(self.list.items())) #这一行的order可以不用 直接带入下面 44ms->32ms
i = 0
for i, (x, tmp) in enumerate(ordered.items()): #这一行的语法纠结了很久。 注意 所有dict下面的都需要dict.items() 才可以for k,v 的遍历
tmp.sort()
for (y, val) in tmp:
ret[i].append(val)
i += 1
return ret
def myVerticalTraversal(self, tree: TreeNode, x:int, y:int):
if tree:
self.list[x].append((y, tree.val))
self.myVerticalTraversal(tree.left, x-1, y+1)
self.myVerticalTraversal(tree.right,x+1, y+1)
#Improved2 进一步改进代码
def verticalTraversal(self, root: TreeNode): #32/36ms beats 90%
self.myVerticalTraversal(root, 0, 0)
return [[val for y,val in sorted(tmp)] for x,tmp in sorted(self.list.items())]
#真的没想到有一天我也可以写出这样的酷酷代码哈哈哈 快乐!!!
|
6d5cc6d478d38a395e12f2b779dd3c5a1180bac9 | YeahHuang/Leetcode | /151_reverseWordsInaStr.py | 365 | 3.640625 | 4 | class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(reversed(s.split()))
#一开始的时候写的是s.split(' ')反而不ok 学到了吖
#C++ Sol
'''
void reverseWords(string &s) {
istringstream is(s);
string tmp;
is >> s;
while(is >> tmp) s = tmp + " " + s;
if(s[0] == ' ') s = "";
}
''' |
b08d7f3e7ed2da87c0cd2f8a33436edfbab5379d | YeahHuang/Leetcode | /79_wordSearch.py | 4,479 | 3.671875 | 4 | import copy
class Record:
def __init__(self, x, y, step, visited):
self.x = x
self.y = y
self.step = step
self.visited = visited
class Solution:
#Sol1 BFS 因为deepcopy太耗时 会TLE
def exist(self, board, word: str) -> bool:
def equals(x,y,target):
'''
if x==0 and y==1:
print(x,y,m,n,target,board[x][y],visited[x][y])
print(False==False)
print((not False))
b = visited[x][y]
print(visited[x][y])
print((not b))
print((not (visited[x][y])))
'''
return 0<=x<m and 0<=y<n and board[x][y]==target and visited[x][y]==False
l = r = 0
dx = [-1,1,0,0]
dy = [0,0,1,-1]
pos = {}
is_exist = True
debug = False
#预处理生成pos 记录位置信息
for c in word:
if c not in pos:
pos[c] = []
for i, line in enumerate(board):
for j, char in enumerate(line):
if char==c:
pos[c].append((i,j))
if len(pos)==0:
is_exist = False
break
if debug:
print(pos)
if is_exist:
records = []
is_exist = False
m, n = len(board),len(board[0])
#no_visited = [['False']*n for _ in range(m)] 不行了 年度top10 最蠢bug
no_visited = [[False]*n for _ in range(m)]
for x,y in pos[word[0]]:
#tmp = no_visited.copy()
tmp = copy.deepcopy(no_visited)
if debug:
print(tmp)
print(no_visited)
tmp[x][y] = True
if debug:
print(tmp)
records.append(Record(x,y,0, tmp))
while records:
record = records.pop(0)
x, y, step, visited = record.x, record.y, record.step, record.visited
if debug:
print(x,y, step)
print(visited)
if step < len(word)-1:
target = word[step+1]
for i in range(4):
if equals(x+dx[i],y+dy[i],target):
if debug:
print(x+dx[i],y+dy[i],target)
tmp = copy.deepcopy(visited)
tmp[x+dx[i]][y+dy[i]] = True
records.append(Record(x+dx[i],y+dy[i],step+1, tmp))
else:
is_exist = True
break
return is_exist
#Sol2 DFS
def exist(self, board, word: str) -> bool:
global is_exist, dx,dy,m,n #新巩固了python的global使用
is_exist = False
dx = [-1,1,0,0]
dy = [0,0,1,-1]
def dfs(step, x, y, board): #其实如果+ret 就可以不用global is_exist 了 可以自己衡量一下
global is_exist, dx,dy, m, n
if step == len(word):
is_exist = True
return
if is_exist:
return
for i in range(4):
tx, ty = x+dx[i], y+dy[i]
if 0<=tx<m and 0<=ty<n and board[tx][ty]==word[step]:
board[tx][ty] = '#'
dfs(step+1, tx, ty, board)
board[tx][ty] = word[step]
'''
去除global的dx dy 但同样简洁美观的check方式
if i<0 or i>=len(board) or j<0 or j>=len(board[0]) or word[0]!=board[i][j]:
return False
res = self.dfs(board, i+1, j, word[1:]) or self.dfs(board, i-1, j, word[1:]) \
or self.dfs(board, i, j+1, word[1:]) or self.dfs(board, i, j-1, word[1:])
'''
m, n = len(board),len(board[0])
for i, line in enumerate(board):
for j, char in enumerate(line):
if char == word[0]:
board[i][j] = '#'
dfs(1, i, j, board)
if is_exist: #如果最好只有一个出口 可优化为break
return True
board[i][j] = word[0]
return is_exist
board = [["A","A"],["C","E"]]
words = ["AA"]
sol = Solution()
for word in words:
print(sol.exist(board,word)) |
a434f76eef766c481a8eaafcff76bcc4249a3d3a | crq-13/pythonIntermedio | /data_filter.py | 579 | 3.71875 | 4 | from data import DATA
def main():
all_python_devs = [worker["name"] for worker in DATA if worker["language"] == "python"]
all_platzi_workers = [worker["name"] for worker in DATA if worker["organization"] == "Platzi"]
adults = list(filter(lambda worker: worker["age"] > 18, DATA))
adults = list(map(lambda worker: worker["name"], adults))
old_people = list(map(lambda worker: worker | {"old": worker["age"] > 70}, DATA))
print(all_python_devs)
print(all_platzi_workers)
print(adults)
print(old_people)
if __name__ == '__main__':
main()
|
e76b8b90216b3c35efcc269ed7f90f6c75b6d4ce | CandyTt20/Notes | /algorithm/findmid.py | 483 | 3.703125 | 4 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def find_mid(head):
slow, fast = head, head
while fast.next is not None and fast.next.next is not None:
slow = slow.next
fast=fast.next.next
return slow
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
print(find_mid(head).value)
|
3e3db51329518b0432112f9f3546bca7b5599cae | CandyTt20/Notes | /archives/levelOrder.py | 790 | 3.921875 | 4 | class Tree(object):
def __init__(self, value, left=None, right=None):
self._value = value
self._left = left
self._right = right
def levelOrder(self):
#! 宽度遍历
queue = [self]
while queue:
cur = queue.pop(0)
print(cur._value,end=' ')
if cur._left:
queue.append(cur._left)
if cur._right:
queue.append(cur._right)
def preOrder(self, root):
#! 先序遍历
#? 递归
if root is None:
return
print(root._value)
self.preOrder(root._left)
self.preOrder(root._right)
tree = Tree(1, Tree(2, Tree(4, Tree(8), None), Tree(5)),
Tree(3, Tree(6), Tree(7)))
tree.preOrder(tree)
|
486990d19beead733bf3f655002e6afa663934f4 | CandyTt20/Notes | /algorithm/merge intervals.py | 698 | 3.5625 | 4 | class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
if intervals == []:
return []
merged = []
intervals.sort(key=lambda x: x[0])
start = intervals[0][0]
end = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] <= end:
end = max(end, intervals[i][1])
else:
merged.append([start, end])
start = intervals[i][0]
end = intervals[i][1]
merged.append([start, end])
return merged
x = Solution()
p = []
print(x.merge(p))
|
c3fb2a61eeeb3b89f54a91c1b31b5bdd66d298be | rhlvora/Random | /piglatin.py | 897 | 3.71875 | 4 | import numpy as np
def ScorePigLatin(beforeword, afterword):
if(afterword[-2:] != "ay"):
return False
transposed = beforeword[1:] + beforeword[0]
if(transposed != afterword[:-2]):
return False
return True
def ConvertWord(word):
x = 0
while(True):
x = x + 1
ss = np.random.permutation(list(word))
qq = ""
for i in ss:
qq = qq + i
qq = qq + "ay"
if(ScorePigLatin(word, qq)):
#print(qq + " discovered in " + str(x) + " iterations.")
return qq
def ConvertSentence(sentence):
if(sentence == ""):
return "Error: empty input sentence."
RetSentence = ""
for word in str.split(sentence):
RetSentence = RetSentence + ConvertWord(word) + " "
return RetSentence[0:-1]
print(ConvertSentence("the quick brown"))
|
c615ce093bfdbca79195b264796ff6eb6c2fe3e1 | nmschorr/twint | /nulspy-twitter/python-twitter/more/examples/get_all_user_tweets.py | 1,554 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Downloads all tweets from a given user.
Uses twitter.Api.GetUserTimeline to retreive the last 3,200 tweets from a user.
Twitter doesn't allow retreiving more tweets than this through the API, so we get
as many as possible.
t.py should contain the imported variables.
"""
from __future__ import print_function
import json
import sys
import twitter
from t import ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET
def get_tweets(api=None, screen_name=None):
timeline = api.GetUserTimeline(screen_name=screen_name, count=200)
earliest_tweet = min(timeline, key=lambda x: x.id).id
print("getting tweets before:", earliest_tweet)
while True:
tweets = api.GetUserTimeline(
screen_name=screen_name, max_id=earliest_tweet, count=200
)
new_earliest = min(tweets, key=lambda x: x.id).id
if not tweets or new_earliest == earliest_tweet:
break
else:
earliest_tweet = new_earliest
print("getting tweets before:", earliest_tweet)
timeline += tweets
return timeline
if __name__ == "__main__":
api = twitter.Api(
CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET
)
screen_name = sys.argv[1]
print(screen_name)
timeline = get_tweets(api=api, screen_name=screen_name)
with open('examples/timeline.json', 'w+') as f:
for tweet in timeline:
f.write(json.dumps(tweet._json))
f.write('\n')
|
0c1b5407359d307f58772c628130e7242840a60c | Sophyarach/programming | /hw9/hw9.py | 983 | 3.6875 | 4 | import re
def askfilename():
print("Введите название файла")
name=input()
try:
file=open(name)
except FileNotFoundError:
print("Такого файла нет или введена пустая строка вместо названия")
name=-1
return name
def find_find(text):
verb_forms=r'(?:найти|найд(?:у|(?:ё|е)(?:шь|т|м|те|нн(?:ы(?:й|м|е|х|ми)|о(?:го|му|м|й|е|ая|ую)))|я|ите|и)|наш(?:(?:ё|е)л|л(?:а|о|и)|едш(?:и|и(?:й|м|е|х|ми)|е(?:го|му|м|й|е)|ая|ую)))'
return re.findall(verb_forms,text)
def print_find(text):
res=find_find(text)
if res:
print(*set(res), sep=", ")
else:
print("В этом тексте нет форм глагола 'найти'")
name=askfilename()
if name!=-1:
with open(name, encoding='utf-8') as f:
text=f.read()
text=text.lower()
print_find(text)
|
56c1af79612f1dabcf35babeab54a2c6b42f45c3 | Sophyarach/programming | /caesar.py | 342 | 3.5625 | 4 | c=input()
alpha='абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
res=""
for x in c:
if x=='ю':
res+='a'
continue
if x=='я':
res+='б'
continue
if x==' ':
res+=' '
b=alpha.find(x)
if b==-1:
continue
res+=alpha[b+2]
print(res)
|
954a5bccd15db2537a100d04249d217a260e30d5 | Sophyarach/programming | /leap.py | 91 | 3.8125 | 4 | x=int(input())
if not x%4 and x%100 or not x%400:
print ("YES")
else:
print ("No")
|
d1fd301d72b085399ae5f9aba618d4f381b54bd3 | chenhuidong/MyGit | /MyScript/Python/generator.py | 255 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
g = (x * x for x in range(10))
g.next()
for n in g:
print n
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
g = fib(6)
for n in g:
print n |
e727fa70e3507d8ff3033ea9f0a890a53a1fb79d | chenhuidong/MyGit | /MyScript/Python/if.py | 124 | 4.25 | 4 | age = input('please enter your age: ')
if age >= 18:
print 'adult'
elif age >= 6:
print 'teenager'
else:
print 'kid' |
32b3098c57406045b2e30e8ae1ed1c8b8d2cc5cd | VincentPauley/python_reference | /03_indentation.py | 314 | 3.515625 | 4 | #!/usr/bin/python
# comments in python start with '#' character
# rather than using braces to denote code blocks as in C or javascript, python using indenting. This is rigidly enforeced, and all statements must be indented to the same amount
if True:
print( 'Today was a good day' )
else:
print( 'Bad day' )
|
c8dfc1abb5893d5bf47ce29b761973a40467683d | VincentPauley/python_reference | /17_substrings_and_slices.py | 239 | 3.578125 | 4 | #!/usr/bin/python
# python uses some very slick syntax to create substrings
team_name = "BlackHawks"
print( team_name[0] ) # 'B'
print( team_name[1:5] ) # 'lack' -> character 1 until 5
print( team_name[5:] ) # 'Hawks' -> character 5 on
|
02d93cbd77bd7932d09deb5c0f1a258882ab4efa | jofre44/EIP | /scripts/string_concatenated.py | 458 | 4.09375 | 4 | print("Actividad 1. Programacion Avanzada en Python")
print("Alumno: Jose Sepulveda \n")
# Lectura de string por pantalla
string_1 = input("Introducir primer string: \n")
string_2 = input("Introducir segundo string: \n")
# Tamaño de los string introducidos
len_str_1 = len(string_1)
len_str_2 = len(string_2)
# Resultado
print(f"\nResultado de la concatenación: {string_1} {string_2}")
print(f"Tamaño total de los string introducidos: {len_str_1 + len_str_2}") |
c9ba48d06cb3b6c4b51d327ced1547d86183205f | jofre44/EIP | /scripts/working_with_ddbb.py | 8,607 | 3.90625 | 4 | import sqlite3
from sqlite3 import Error
print("Actividad 7. Programacion Avanzada en Python")
print("Alumno: Jose Sepulveda \n")
def create_connection(db_file):
""" Funcion para crear conexion con la base de datos
param:
df_file: nombre de la base de datos
output:
conn: conexion a la base de datos
"""
conn = None
try:
conn = sqlite3.connect(db_file)
print(f'Conexión con la base de datos {db_file} correcta')
except Error as e:
print('No se pudo conectar a la base de datos.\n')
print(e)
return conn
def create_table(conn, query, table_name):
"""Funcion para crear tabla
params:
conn: conexion con base de datos
query: query para crear tabla
table_name: nombre de la tabla a crear
""""
if conn is None:
print('No hay conexión a base de datos')
return None
try:
c = conn.cursor()
c.execute(query)
print(f'Se creo table {table_name} de forma correcta')
except Error as e:
print(f'No se pudo crear tabla {table_name}.\n')
print(e)
def col_info(conn, mod_type, table_name):
""" Funcion para crear diccionario clave (nombre de as columnas de la tabla) valor (valor de las columnas)
params:
conn: conexion con base de datos
mod_type: tipo de modificacion a realizar
table_name: nombre de la tabla de datos
"""
query_col = f"""PRAGMA table_info({table_name});"""
c = conn.cursor()
c.execute(query_col)
col_list = c.fetchall()
values_dic = {}
for i in range(len(col_list)):
if col_list[i][1] == 'id' and mod_type == 'u':
value = input(f"Ingrese valor para campo {col_list[i][1]} ({col_list[i][2]}) que se va a actualizar: ")
else:
value = input(f"Ingrese valor para campo {col_list[i][1]} ({col_list[i][2]}): ")
values_dic[col_list[i][1]] = value
return values_dic
def modify_table(conn, mod_type, table_name):
""" Funcion para modificar tabla de datos
params:
conn: conexion con base de datos
mod_type: tipo de modificacion a realizar
table_name: nombre de la tabla de datos
"""
if mod_type == 'i':
# Consulta tipo INSERT
values_dic = col_info(conn, mod_type, table_name)
col_str = ''
val_str = ''
for col, val in values_dic.items():
if col_str == '':
col_str = col_str + col
val_str = val_str + '?'
else:
col_str = col_str + ',' + col
val_str = val_str + ',?'
query = f"""INSERT INTO {table_name} ({col_str})
VALUES({val_str})"""
data_list = tuple(values_dic.values())
try:
c = conn.cursor()
c.execute(query, data_list)
conn.commit()
print(f'Se ingresaron los valores de forma correcta')
except Error as e:
print(f'No se pudo ingresar valores.\n')
print(e)
elif mod_type == 'u':
# Consulta tipo UPDATE
values_dic = col_info(conn, mod_type, table_name)
col_str = ''
aux_list = []
for col, val in values_dic.items():
if col != 'id':
if col_str == '':
col_str = col_str + col + '= ?'
aux_list.append(val)
else:
col_str = col_str + ',\n' + col + '= ?'
else:
id_field = val
query = f"""UPDATE {table_name}
SET {col_str}
WHERE id = ?"""
print(query)
aux_list.append(id_field)
data_list = tuple(aux_list)
print(data_list)
try:
c = conn.cursor()
c.execute(query, data_list)
conn.commit()
print(f'Se actualizaron los valores de forma correcta')
except Error as e:
print(f'No se pudo actualizar valores.\n')
print(e)
elif mod_type == 's':
# Consulta tipo SELECT
query = f"""SELECT * FROM {table_name}"""
try:
c = conn.cursor()
c.execute(query)
rows = c.fetchall()
for row in rows:
print(row)
except Error as e:
print(f'Error al hacer el select.\n')
print(e)
elif mod_type == 'd':
#Consulta tipo DELETE
query = f"""DELETE FROM {table_name}"""
try:
c = conn.cursor()
c.execute(query)
conn.commit()
print(f'Se han eliminado todos los registros de la tabla.\n')
except Error as e:
print(f'Error el borrar datos en tabla.\n')
print(e)
else:
print('Dato incorrecto')
print('Actividad 1: Crear base de datos.\n')
db_name = input("Ingrese nombre de Base de datos (dejar en blanco para usar nombre predeterminado 'ejemplo'):\n")
if db_name == '':
db_name = 'ejemplo'
db_file = db_name + '.db'
conn = create_connection(db_file)
print('\nActividad 2: crear tablas')
crear_table_str = input('¿Desea crear tabla (t: si; f: no):\n')
if crear_table_str == 'f':
crear_tabla = False
elif crear_table_str == 't':
crear_tabla = True
else:
print('Dato in correcto, no se van a crear tabla')
crear_tabla = False
i = 1
while crear_tabla:
table_name = input(f"Ingrese nombre de tabla (dejar en blanco para usar nombre predeterminado 'tabla{i}'):\n")
if table_name == '':
table_name = 'tabla'+str(i)
numero_campos = int(input(f'Ingrese numero de campos en la tabla {table_name}:\n'))
print('Primer campo de la tabla es id siendo un integer y Primary key')
fields_query = 'id integer PRIMARY KEY'
for j in range(2,numero_campos+1):
col_name = input(f"Ingrese nombre de columna {j} (dejar en blanco para usar nombre predeterminado 'columna{j}'):\n")
if col_name == '':
col_name = 'columna'+str(j)
col_type = input(f"Ingrese tipo de dato de la columna (1 para integer; 2 para text'):\n")
if col_type == '1':
col_type = 'integer'
elif col_type == '2':
col_type = 'text'
else:
print('Dato erroneo. Se crea columna tipo integer')
col_type = 'integer'
col_null = input(f"Ingrese si se permite valor nulo para columna (1 es permitido; 2 no es permitido'):\n")
if col_null == '1':
col_null = ''
elif col_null == '2':
col_null = ' NOT NULL'
else:
print('Dato erroneo. Se permite valores nulos en la columna')
col_null = ''
fields_query = fields_query + ',\n' + col_name + ' ' + col_type + col_null
query = f"""CREATE TABLE IF NOT EXISTS {table_name} (
{fields_query}
);"""
create_table(conn, query, table_name)
crear_table_str = input('¿Desea crear otra tabla (t: si; f: no):\n')
if crear_table_str == 'f':
crear_tabla = False
elif crear_table_str == 't':
crear_tabla = True
i += 1
else:
print('Dato in correcto, no se van a crear tabla')
crear_tabla = False
print('\nActividad 3: modificar tablas')
modificar_str = input('¿Desea modificar alguna tabla (t: si; f: no):\n')
if modificar_str == 'f':
modificar = False
elif modificar_str == 't':
modificar = True
else:
print('Dato in correcto, no se van a modificar ninguna tabla')
modificar = False
while modificar:
c = conn.cursor()
c.execute(f"SELECT name FROM sqlite_master WHERE type='table';")
tables_list = c.fetchall()
tables_dic = {i: tables_list[i][0] for i in range(len(tables_list))}
table_ind = int(input(f'Seleccione tabla a modificar {tables_dic}:\n'))
table_select = None
try:
table_select = tables_dic[table_ind]
except:
print('Valor equivocado para seleccion de tabla')
if table_select is not None:
mod_type = input("Ingrese tipo de modificacion a realizar (i: insertar; u: actualizar; s: listar; d: borrar):\n")
modify_table(conn, mod_type, table_select)
modificar_str = input('¿Desea realizar otra modificacion (t: si; f: no):\n')
if modificar_str == 'f':
modificar = False
elif modificar_str == 't':
modificar = True
else:
print('Dato in correcto, no se van a realizar modificaciones')
modificar = False |
7864a41a75d755453c19572e19eed4e6503842a2 | hbhargava7/biophysical-data-aggregator | /bda/PDB.py | 4,930 | 3.71875 | 4 | """This script will enable the user to extract all structural information
avaiable for a given protein search."""
import urllib.request as urllib
import requests
import numpy as np
import pandas as pd
def getPDBIDs(input):
"""This function takes in a protein name, finds all related PDB IDs, and exports that as a list.
Parameters:
input(str): protein name or molecule name to be searched.
Returns:
list of unique protein PDB IDs associated to that particular name.
Example:
listPDBs = getPDBIDs(searchTerm)"""
url = 'http://www.rcsb.org/pdb/rest/search'
queryText = """<?xml version="1.0" encoding="UTF-8"?><orgPdbQuery><queryType>org.pdb.query.simple.MoleculeNameQuery</queryType><description>Molecule Name Search : Molecule Name=""" + input + """</description><macromoleculeName>""" + input + """</macromoleculeName></orgPdbQuery>"""
queryBytes = str.encode(queryText)
req = urllib.Request(url, data=queryBytes)
f = urllib.urlopen(req)
resultBytes = f.read()
resultsText = str(resultBytes, 'utf-8')
print(type(resultsText))
resultList = resultsText.split("\n")
if (resultList[-1] == ""):
del(resultList[-1])
updatedPDBIDs = []
for name in resultList:
updatedPDBIDs.append(name[0:4])
#Get rid of all redundant IDs
setPDBIDs = set(updatedPDBIDs)
updatedPDBIDs = list(setPDBIDs)
return updatedPDBIDs
def infoByID(inputIDs):
"""This function takes in a list of PDB IDs and finds all relevant PDB structures, tabulating all their information.
Parameters:
input(list): list of PDB IDs.
Returns:
Pandas dataframe, with the information for every PDB ID, organized in columns...
- PDB ID
- Structure Title
- Resolution
- Date of deposit
- Method Used for structural biology
- DOI
- Weblink to protein in RCSB
Example:
listPDBs = getPDBIDs(searchTerm)"""
listPDBID = []
listStructureTitle = []
listResolution = []
listDepositDate = []
listMethod = []
listLigand = []
listDOI = []
listWebLink = []
listAuthors = []
for name in inputIDs:
#Go in, and find another way to list, not by commas
url = "http://www.rcsb.org/pdb/rest/customReport.csv?pdbids=" + name + "&CustomReportColumns=structureTitle,resolution,depositionDate,experimentalTechnique,pdbDoi,structureAuthor&format=csv"
rString = requests.get(url) #, allow_redirects=True)
rList = str(rString.content).split(" />")
parameterList = rList[0]
del(rList[0])
del(rList[-1])
for entry in rList:
#print(entry)
#quit()
entry = entry.replace("<br","")
valuesList = entry.split('","')
listPDBID.append(valuesList[0].replace('"',''))
listStructureTitle.append(valuesList[1])
listResolution.append(valuesList[2])
listDepositDate.append(valuesList[3])
listMethod.append(valuesList[4])
listDOI.append(valuesList[5].replace('"',''))
url = "https://www.rcsb.org/structure/" + valuesList[0]
listWebLink.append(url)
listAuthors.append(valuesList[6].split("#")[0])
#print(listPDBID[0] + ", " + listChains[0])
outputDF = pd.DataFrame()
outputDF["PDB ID"] = listPDBID
outputDF["Structure ID"] = listStructureTitle
outputDF["Resolution"] = listResolution
outputDF["Date of Deposit"] = listDepositDate
outputDF["Method Used"] = listMethod
outputDF["DOI"] = listDOI
outputDF["Web Link"] = listWebLink
outputDF["Author"] = listAuthors
return outputDF
def search(searchTerm):
"""This function takes in a protein name, and organizes a search for its information in the RCBI.
It calls two functions, one that will convert the protein name to a list of PDB IDs (getPDBIDs)
another will convert the list of PDB IDs to a dataframe containing the relevant structural information
for each of those PDB IDs (infoByID). This function ultimately returns a dataframe.
Parameters:
input(str): protein name or molecule name to be searched.
Returns:
This is the same output as the function infoByID.
It returns a Pandas dataframe, with the information for every PDB ID, organized in columns...
- PDB ID
- Structure Title
- Resolution
- Date of deposit
- Method Used for structural biology
- DOI
- Weblink to protein in RCSB
Example:
listPDBs = getPDBIDs(searchTerm)"""
listPDBs = getPDBIDs(searchTerm)
print(listPDBs)
if (len(listPDBs) != 0):
DF = infoByID(listPDBs)
else:
DF = pd.DataFrame()
return(DF)
if __name__ == "__main__":
print(search("PKC"))
|
df3e76f8e666c1169ff376f6ff82d6d54e04912b | swiftlysingh/Learning_Python | /date.py | 173 | 3.5625 | 4 | from datetime import datetime,timedelta
current_date = datetime.now()
print(current_date)
one_day = timedelta(days=2)
print(current_date-one_day)
print(current_date.day) |
46ebc2660769d28c223db26a9ca88b79466fb027 | Cheesepuffed/2-Rooms-and-a-Boom-Randomizer | /main.py | 3,240 | 4.09375 | 4 | # This is a sample Python script.
from Role import Role
import random
# makes the member list with commas separating each member
def make_memberlist():
longlist = str(input("Please paste everyone's names ensuring each name is separated by a comma (,)\n"))
return longlist.split(",")
# creates finallist in main where the list returned contains members with groups of True and False values
def make_memberlist_with_role_class(memberlist,team):
memberlist_final = []
for x in memberlist:
memberlist_final.append(Role(x, team))
return memberlist_final
# randomizes the list and then splits the list of names into 2 teams
def split_into_teams(list):
random.shuffle(list)
half = len(list) // 2
return list[:half], list[half:]
# takes a team's list and a special role then turns a regular member of that team into the special role
def pick_special_role(team_list,role):
member = random.choice(team_list)
while member.role != "Regular Member":
member = random.choice(team_list)
Role.change_role(member,role)
return None
# writes a txt file that displays a team's members and the member's roles
def display_team(team_list,file_name):
file = open(file_name,"w")
for x in team_list:
file.write(x.team_info() + "\n")
file.close()
return None
# standard game that adds Bomber and President
def round_1(red_team,blue_team):
pick_special_role(red_team,"Bomber")
pick_special_role(blue_team,"President")
return red_team, blue_team
# Game introduces spies and coy roles
def round_2(red_team,blue_team):
pick_special_role(red_team,"Bomber")
pick_special_role(blue_team,"President")
pick_special_role(red_team, "Red Spy")
pick_special_role(blue_team, "Blue Spy")
pick_special_role(red_team, "Red Coy")
pick_special_role(blue_team, "Blue Coy")
return red_team, blue_team
# Game introduces Engineer and Doctor roles
def round_3(red_team,blue_team):
pick_special_role(red_team,"Bomber")
pick_special_role(blue_team,"President")
pick_special_role(red_team, "Red Spy")
pick_special_role(blue_team, "Blue Spy")
pick_special_role(red_team, "Red Coy")
pick_special_role(blue_team, "Blue Coy")
pick_special_role(red_team, "Engineer")
pick_special_role(blue_team, "Doctor")
return red_team, blue_team
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
# Creates the Blue and Red Teams
member_list = make_memberlist()
team1, team2 = split_into_teams(member_list)
blue_team = make_memberlist_with_role_class(team1,"Blue")
red_team = make_memberlist_with_role_class(team2,"Red")
# Asks what version user wants to play
round = input("Which round is it?\n")
if round == "1":
red_team, blue_team = round_1(red_team,blue_team)
if round == "2":
red_team, blue_team = round_2(red_team,blue_team)
if round == "3":
red_team, blue_team = round_3(red_team,blue_team)
# Writes roles out on files so they are easily accessible outside of IDE
display_team(blue_team,"Blue Team List.txt")
display_team(red_team,"Red Team List.txt")
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
d3aca3e126466efe777f55bbcee9aa3007417a3b | luxiaolei930/python3_book | /第三章/3.8 利用nltk工具包进行分句和分词.py | 1,247 | 4.0625 | 4 | # 利用nltk工具包进行分句和分词
# 导入nltk
import nltk
# 待分句、分词文本,使用\符号隔开目的是方便阅读。
text = "He was an old man who fished alone in a skiff in the Gulf Stream and he had gone eighty-four days now without taking a fish. In the first forty days a boy had been with him." \
" But after forty days without a fish the boy’s parents had told him that the old man was now definitely and finally salao, which is the worst form of unlucky, and the boy had gone at their orders in another boat which caught three good fish the first week. " \
"It made the boy sad to see the old man come in each day with his skiff empty and he always went down to help him carry either the coiled lines or the gaff and harpoon and the sail that was furled around the mast."
print("原始文本:")
print(text)
# 利用sent_tokenize()进行分句
sents = nltk.sent_tokenize(text)
print("输出分句结果:")
for i, sent in enumerate(sents):
print("第"+str(i+1)+"句:", sent)
# 利用word_tokenize()进行对每个句子进行分词
words = [nltk.word_tokenize(sent) for sent in sents]
print("输出分词结果:")
for i, word in enumerate(words):
print("第"+str(i+1)+"句:", word)
|
cd32b23e5fd521b3db28dcfbeafc427774d9d071 | luxiaolei930/python3_book | /第一章/1.12 翻页获取语料代码.py | 1,319 | 3.59375 | 4 | #引入 requests 库
import requests
#引入BeautifulSoup4 解析库
import bs4
#查看网址链接,发现top250的电影名称总共有10页,每页所列的电影数目为25。使用for循环实现翻页,设置代表页码的i变量,取值为0-9之间。(range的取值范围为左闭右开区间。即大于等于第一个参数,小于第二个参数。)
for i in range(0,10):
#查看网址链接,发现翻页的时候变化的是start参数,网页每页所列的电影数目为25,start参数每页增加25。 用i*25表示参数的变化,将其命名为start_,i的取值范围为(0,10)
start_=i*25
#使用requests.get获取页面内容,其中start参数在每次循环时变化,使用str()函数将start_转换成字符串。
response= requests.get("https://movie.douban.com/top250?start="+str(start_)+"&filter=")
#使用BeautifulSoup 解析库中的标准库("html.parser")来解析已获取页面的文本内容(response.text)
soup=bs4.BeautifulSoup(response.text,"html.parser")
#找到所有"div"标签中class为"hd"的内容
content=soup.find_all("div",class_="hd")
#使用for...in循环,依次把内容中需要的元素迭代出来
for each in content:
#打印<a><a/>标签中的文本
print(each.a.text)
|
8dc98b7f9d8b64771ec4eb95a2e3817daef79ec9 | Nitro2000/Speak_Bot | /BOT.py | 4,826 | 3.578125 | 4 | import pyttsx3 # Text to speak
import speech_recognition as sr # Speak to string(text)
from datetime import datetime # For correct time and date
import wikipedia # For search
import webbrowser # For opening sites
import os # For opnening inbuild platforms
import smtplib # For mail (stands for simple mail transfer protocol library)
import time
ST = pyttsx3.init('sapi5')
voices = ST.getProperty('voices')
ST.setProperty('voice', voices[0].id)
def speak(audio): # Func for text to speak
ST.say(audio)
ST.runAndWait()
def Wish(): # Func for wishing the owner
hr = int(datetime.now().hour) # datetime return a string in 24 hr format
if 6 <= hr < 12:
speak("good morning! sir") # no need for capital letters. it will speak same
elif 12 <= hr < 16:
speak("good afternoon! sir")
elif 16 <= hr < 20:
speak("good evening! sir")
else:
speak("good night! sir")
speak("i am speak bot. please tell me how can i help you")
def takecommand(): # Func for speech to text
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening......")
r.pause_threshold = 2 # for a pause
audio = r.listen(source)
try:
print("I am recognizing....")
query = r.recognize_google(audio, language = "en - IN") # To recognise your language usig google
print(f"user said: {query}\n")
except Exception as e:
print("say that again please......")
return takecommand()
else:
return query
def sendmail(to, content): # Func for sending mails
server = smtplib.SMTP("smtp.gmail.com", 587) # this is default smpt site and port
server.starttls()
server.login("rishabhyo456@gmail.com", "Rishi@654")
server.sendmail("rishabhyo456@gmail.com", to, content)
if __name__ == "__main__":
Wish()
while True:
a = takecommand().lower()
if "wikipedia" in a:
speak("Searching wikipedia")
a = a.replace("wikipedia", "")
result = wikipedia.summary(a, sentences = 4)
speak("according to wikipedia")
print("result")
speak("result")
elif "open youtube" in a:
webbrowser.open("youtube.com")
time.sleep(5)
elif "open google" in a:
webbrowser.open("google.com")
time.sleep(5)
elif "open stack overflow" in a:
webbrowser.open("stackoveflow.com")
elif "open data science guide" in a:
webbrowser.open("datasciguide.com")
elif "open insta" in a:
webbrowser.open("instagram.com")
time.sleep(5)
elif "the time" in a:
time = datetime.now().hour
if 0 <= time < 12:
time = datetime.now().strftime("%I:%M:%S")
speak(f"sir, the time is {time} A M")
print(time,"AM")
else:
time = datetime.now().strftime("%I:%M:%S")
speak(f"sir, the time is {time} P M")
print(time,"PM")
elif "the day" in a:
day = datetime.now().strftime("%A")
speak(f"sir, today is {day}")
elif "the month" in a:
month = datetime.now().strftime("%B")
speak(f"sir, it's {month}")
elif "the date" in a:
date = datetime.now().date()
speak(f"sir, the date is {date}")
elif "google search" in a:
speak("what do you want to search on google")
c = takecommand()
try:
from googlesearch import search
except ImportError:
print("no module named 'google' found")
else:
for i in search(c, tld= "co.in", num=10, stop=10, pause=2):
print(i)
speak("following websites are the results based on your search")
elif "open notepad" in a:
print("opening notepad..")
os.system("notepad.exe")
elif "send mail" in a or "send a mail" in a:
speak("please speak the email content")
content = takecommand()
speak("now tell me the receiver email account")
to = takecommand()
to = to.replace(" ", "")
sendmail(to, content)
speak("email has been sent!")
elif "quit" in a:
speak("it was nice talking to you sir. see you soon again")
break
elif "your specification" in a:
speak("i have 8 g b ram 256 s s d with intel core i 5 8th generation")
exit()
|
4bfff67203f0ab60a696bdb49cbc00de7db79767 | govindak-umd/Data_Structures_Practice | /LinkedLists/singly_linked_list.py | 2,864 | 4.46875 | 4 | """
The code demonstrates how to write a code for defining a singly linked list
"""
# Creating a Node Class
class Node:
# Initialize every node in the LinkedList with a data
def __init__(self, data):
# Each of the data will be stored as
self.data = data
# This is very important because is links one
# of the node to the next one and by default
# it is linked to none
self.next = None
# Creating a LinkedList class
class LinkedList:
def __init__(self, ):
# The below is the head of the LinkedList
# which is the first element of a LinkedList
self.head = None
# Writing a function to print the LinkedList
def PrintLinkedList(self):
temporary_head = self.head
while temporary_head is not None:
print(temporary_head.data)
temporary_head = temporary_head.next
# Implement addition at the beginning functionality
def addBeginning(self, new_node):
new_node_beg = Node(new_node)
new_node_beg.next = self.head
self.head = new_node_beg
# Implement addition at the end functionality
def addEnd(self, new_node):
new_node_end = Node(new_node)
# creating a temporary head
temp_head = self.head
# keep looping until the head doesn't have anything next
while temp_head.next:
temp_head = temp_head.next
temp_head.next = new_node_end
# Implement addition at the middle functionality
def removeNode(self, new_node):
new_node_removed = Node(new_node)
temp_head = self.head
# removing the first element
if self.head.data == new_node_removed.data:
temp_head = temp_head.next
self.head = temp_head
# for removing the any other element other than the first element
while temp_head.next:
if temp_head.next.data == new_node:
temp_head.next = temp_head.next.next
break
else:
temp_head = temp_head.next
if __name__ == '__main__':
# Creating a LinkedList object
linked_list_object = LinkedList()
# Defining the head for the linkedList
linked_list_object.head = Node(1)
# defining the second, third and fourth elements in the linked list
second = Node(2)
third = Node(3)
fourth = Node(4)
# Linking each element to the next element starting with
# linking the head to the second element
linked_list_object.head.next = second
second.next = third
third.next = fourth
# Testing adding in the beginning
linked_list_object.addBeginning(99)
# Testing adding at the end
linked_list_object.addEnd(55)
# Testing removing any key in the LinkedList
linked_list_object.removeNode(3)
linked_list_object.PrintLinkedList()
|
1b79159fe3e599737ba1c9e6c34c7783726578ee | jiangjiane/Python | /pythonpy/test16_6.py | 917 | 4.0625 | 4 | def func():
x=4
action=(lambda n:x**n)
return action
x=func()
print(x(2))
print(x(3))
print('\n')
def func():
x=4
action=(lambda n,x=x:x**n)
return action
x=func()
print(x(2))
print(x(3))
print('\n')
#变量在嵌套的函数被调用时才进行查找,所以结果是同样的值
def makeActions():
acts=[]
for i in range(5):
acts.append(lambda x:i**x)
return acts
acts=makeActions()
print(acts[0](2))
print(acts[2](2))
print(acts[4](2))
print(acts[1](3))
print('\n')
#使用默认参数把当前的值传递给嵌套作用域的变量
def makeActions():
acts=[]
for i in range(5):
acts.append(lambda x,i=i:i**x)
return acts
acts=makeActions()
print(acts[0](2))
print(acts[2](2))
print(acts[4](2))
print(acts[4](3))
print('\n')
#任意嵌套
def f1():
x=99
def f2():
def f3():
print(x)
f3()
f2()
f1()
|
c762ee9649cca79d79ff7970f00fb51d2d7bdf14 | jiangjiane/Python | /pythonpy/class1.py | 756 | 3.65625 | 4 | #! /usr/bin/python3
# -*- coding: utf8 -*-
#例1
class MixedNames:
data='spam'
def __init__(self,value):
self.data=value
def display(self):
print(self.data,MixedNames.data)
print('-----例1-----')
x=MixedNames(1)
y=MixedNames(2)
x.display()
y.display()
#例2
class NextClass:
def printer(self,text):
self.message=text
print(self.message)
print('-----例2-----')
x=NextClass()
x.printer('instance call')
print(x.message)
#例3
class Super:
def method(slef):
print('in Super.method')
class Sub(Super):
def method(self):
print('starting Sub.method')
Super.method(self)
print('ending Sub.method')
print('-----例3-----')
x=Super()
x.method()
x=Sub()
x.method()
|
13cb81770a801836a42d4f35d81c40c7cc78ded2 | jiangjiane/Python | /pythonpy/primes.py | 463 | 3.890625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
for n in primes():
if n<1000:
print(n)
else:
break
def _odd_iter():
n=1
while True:
n=n+2
yield n
def _notdivisible(n):
return lambda x:x%n>0
def primes():
yield 2
it=_odd_iter()
while True:
n=next(it)
yield n
it=filter(_not_divisible(n),it)
if _name_=='_main_':
main()
|
8520011404a3e7fd9ca5205dd68348acf9dd0cc5 | jiangjiane/Python | /pythonpy/attr.py | 681 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Myobject(object):
def __init__(self):
self.x=9
def power(self):
return self.x*self.x
obj=Myobject()
print('hasattr(obj,\'x\')=',hasattr(obj,'x'))#是否有属性'x'
print('hasattr(obj,\'y\')=',hasattr(obj,'y'))#是否有属性'y'
setattr(obj,'y',19)# 设置属性'y'
print('hasattr(obj,\'y\')=',hasattr(obj,'y'))#是否有属性'y'
print('getattr(obj,\'y\')=',getattr(obj,'y'))#获取属性'y'
print('obj.y=',obj.y)#获取属性'y'
print('getattr(obj,\'z\')=',getattr(obj,'z',404))#获取属性'z',若不存在,则返回值404
f=getattr(obj,'power')#获取属性‘power’
print(f)
print(f())
|
ff97ced37ea41e57879dfb013924eb7b89750856 | jiangjiane/Python | /pythonpy/part4_5.py | 201 | 3.8125 | 4 | #第四部分习题
#xiti5 字典复制
def copyDict(old):
new={}
for key in old.keys():
new[key]=old[key]
return new
d={1:1,2:2}
e=copyDict(d)
d[2]='?'
print('d=',d)
print('e=',e)
|
f72adcb023e20f58c1c28a6789e718aced2fe7a3 | jiangjiane/Python | /pythonpy/xiti3_4.py | 938 | 3.765625 | 4 | #第三部分 语句和语法
#第四题
#a
print('第三部分第四题 ')
print('a小题\n')
L=[1,2,4,8,16,32,64]
X=5
i=0
while i<len(L):
if 2**X==L[i]:
print('at index',i)
break
i+=1
else:
print(X,'not found')
print('\n')
#b
print('b小题\n')
L=[1,2,4,8,16,32,64]
X=5
for p in L:
if(2**X)==p:
print((2**X),'was found at',L.index(p))
break
else:
print(X,'not found')
print('\n')
#c
print('c小题\n')
L=[1,2,4,8,16,32,64]
X=5
if (2**X) in L:
print((2**X),'was found at',L.index(2**X))
else:
print(X,'not found')
print('\n')
#d
print('d小题\n')
X=5
L=[]
for i in range(7):L.append(2**i)
print(L)
if (2**X) in L:
print((2**X),'was found at',L.index(2**X))
else:
print(X,'not found')
print('\n')
#e
print('e小题\n')
X=5
L=list(map(lambda x:2**x,range(7)))
print(L)
if (2**X) in L:
print((2**X),'was found at',L.index(2**X))
else:
print(X,'not found')
|
edc0087b0906acb96fa8f6ec77d3923b472fc47e | jiangjiane/Python | /pythonpy/part4_3.py | 608 | 3.984375 | 4 | #第四部分习题
#xiti3
def adder1(*args):
print('adder1',end=' ')
if type(args[0])==type(0): #手动测试类型,看是否为整数
sum=0 #若为整数,sum初始值为0
else:
sum=args[0][:0] #若不是整数,第一个参数的空分片为初始值
for arg in args:
sum+=arg
return sum
def adder2(*args):
print('adder2',end=' ')
sum=args[0]
for next in args[1:]:
sum+=next
return sum
for func in (adder1,adder2):
print(func(2,3,4))
print(func('spam','eggs','toast'))
print(func(['a','b'],['c','d'],['e','f']))
|
6a7c42b6a4d4e0297a1a9df574fbe23c219ae864 | wjlei1990/finance101 | /src/stock.py | 2,070 | 3.734375 | 4 | #!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
"""
Stock price implementation
:copyright:
Wenjie Lei (wjlei1990@gmail.com), 2017
:license:
UNDERTERMINED YET
"""
from __future__ import print_function, division, absolute_import
import numpy as np
import matplotlib.pyplot as plt
TRADING_DAYS = 250
class DailyStock(object):
def __init__(self, data=None, name="UNKNOWN"):
"""
:param data: data is the array of stock price. Because in python,
copy is shallow copy, so it is very efficient. However, if you
want the data to keep intact, please make a copy of the original
data.
:type data: numpy.ndarray
:param name: stock name
:type name: str
"""
self.data = data
self.name = name
def price_return(self, start=0, end=-1):
""" Cumulative return """
return self.data[end] / self.data[start] - 1.0
def volatility(self, start=0, end=-1):
"""
:return: the anualized volatility of a stock.
the dimension of returned volatility will be
(len(self.data) - 2)
"""
if end == -1:
# end = -1 is a corner case here since (end+1) will be 0
end = len(self.data) - 1
daily_change = \
np.diff(self.data[start:(end+1)]) / self.data[start:end]
std = np.std(daily_change)
vol = np.sqrt(TRADING_DAYS) * std
return vol
def draw_down(self, start=0, end=-1):
min_price = np.min(self.data[start:end])
return (min_price - self.data[start]) / self.data[start]
def sharpe(self, start=0, end=-1):
if end < 0:
end = end + len(self.data)
ndays = end - start + 1
annual_return = \
(1 + self.price_return()) ** (float(TRADING_DAYS) / ndays) - 1
vol = self.volatility()
return annual_return / vol
def plot(self):
plt.figure()
plt.plot(self.data)
plt.title(self.name)
plt.xlabel("days")
plt.ylabel("stock price")
plt.show()
|
9a81df8d915013d0daf4213736d65ae211c81e58 | igauravsehrawat/Utility-scripts | /python-utility/graphics_in_python.py | 202 | 3.703125 | 4 | import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor("green")
brad = turtle.Pen()
for i in (1,5):
brad.forward(100)
brad.left(90)
window.exitonclick()
draw_square()
|
70da10ed10a452e43ad55f9313b3f71e8ebd8f35 | jspencersharp/Portfolio | /Python/Stars/stars.py | 452 | 3.515625 | 4 | #part 1
# def draw_stars():
# x = [4,6,1,3,5,7,25]
# for i in range(0,len(x)):
# temp = x[i]
# print("*" * temp)
# draw_stars()
#part 2
import string
def star2(arr):
for i in arr:
if isinstance(i, int):
print "*" * i
elif isinstance(i, str):
length =len(i)
letter =i[0].lower()
print letter * length
star2([4,"Tom", 1, "Michael", 5, 7, "Jimmy Smith"])
|
03d392f60a994c3ac4e6a6d78f1269625aae1695 | jspencersharp/Portfolio | /Python/names/names.py | 1,631 | 3.5 | 4 | #part 1
# students = [
# {'first_name': 'Michael', 'last_name' : 'Jordan'},
# {'first_name' : 'John', 'last_name' : 'Rosales'},
# {'first_name' : 'Mark', 'last_name' : 'Guillen'},
# {'first_name' : 'KB', 'last_name' : 'Tonel'}
# ]
# for data in students:
# print data['first_name'], data['last_name']
#part 2
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
def studentNames(arr):
for students in students:
print students['first_name'], students['last_name']
def showUsers(users):
for role in users:
counter=0
print role
for person in users[role]:
counter = counter +1
first_name = person['first_name']
last_name = person['last_name']
length = len(first_name) + len(last_name)
print "{} - {} {} - {}".format(counter, first_name, last_name, length)
studentNames(students)
showUsers(users)
# can't get part two to work... have spent too much time on this but getting error that students in line 37 is referenced before assignment. |
627a7b8809a91183e6779fab590942f9ec4ca039 | jspencersharp/Portfolio | /Python/deckOfCards/deck.py | 1,092 | 3.625 | 4 | from random import shuffle
import copy
class Deck(object):
def __init__(self):
self.cardList = ["SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10" ,"SJ", "SQ", "SK", "HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10" ,"HJ", "HQ", "HK", "DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10" ,"DJ", "DQ", "DK", "CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10" ,"CJ", "CQ", "CK"]
self.availCards = []
def shuffle(self):
self.availCards = copy.deepcopy(self.cardList)
shuffle(self.availCards)
return self
def draw(self):
return self.availCards.pop()
def count(self):
return len(self.availCards)
myHand1 = []
myHand2 = []
myDeck = Deck()
myDeck.shuffle()
for count in range(0,5):
myHand1.append(myDeck.draw())
myHand2.append(myDeck.draw())
# print myDeck.count()
player1 = raw_input("Enter the name of the first player: ")
print player1, "has these cards -", myHand1
player2 = raw_input("Enter the name of the second player: ")
print player2, "has these cards -", myHand2 |
ea14b178d782fe155888caf2987a29f851d9a096 | vintagefuture/passwordGenerator | /generate-pwd.py | 1,416 | 3.8125 | 4 | from tkinter import *
def createPassword():
import secrets
import string
import datetime
x = datetime.datetime.now()
piece1 = ''
piece2 = ''
piece3 = ''
t = 'ioqxnmzvdbIOQXNMZVDB' # letters to exclude becuase difficult to pronounce and understand
for x in range(0, 3):
piece1 += secrets.choice(string.ascii_lowercase.translate({ord(i): None for i in t+piece1}))
for x in range(0, 3):
piece2 += secrets.choice(string.digits.translate({ord(i): None for i in piece2}))
for x in range(0, 3):
piece3 += secrets.choice(string.ascii_uppercase.translate({ord(i): None for i in t+piece3+piece1.upper()}))
password = (piece1 + piece2 + piece3)
#password = x.strftime("%a%Y%m%d")
s = " ".join(repr(e) for e in password)
e.delete(0, END)
e.insert(0, password)
def cleanScreen():
e.delete(0, END)
root = Tk()
#root.geometry("200x200")
root.title('Password Generator')
#label = Label(root, text="Password Generator")
e = Entry(root, width=12, justify = CENTER, font = "Helvetica 44 bold")
button1 = Button(root, text="Generate password", command=createPassword, font = "Helvetica 20 bold")
button2 = Button(root, text="Reset", command=cleanScreen, font = "Helvetica 20 bold")
#label.grid(row=0, sticky= N)
e.grid(row=1, sticky=N, columnspan = 2)
button1.grid(row = 2, column=0, sticky=N)
button2.grid(row = 2, column=1, sticky=N)
root.mainloop()
|
d0a89ddf61233ac6b283a46abf49479dd5a34afc | liran2208/AT1 | /SM_brute.py | 620 | 3.703125 | 4 | from collections import deque
# small world problem
def d_two_nodes_graph(g, num1, num2):
count = 0
q = deque()
q.append(g[num1-1])
current = 0
while count < len(g):
count += 1
current = q.popleft()
if (num2 in current):
return count
else:
for i in current:
q.append(g[i-1])
return 404
graph = [[2, 4], [1, 3], [4, 2], [3, 1]]
graph = [ [2, 5],
[6, 5, 4],
[6, 9, 4],
[2, 3, 5, 8, 9],
[2, 3, 8, 7],
[6, 9],
[6, 5, 4],
[5, 3, 4, 7]]
print (d_two_nodes_graph(graph, 1, 9))
|
a02a807bfc1189201fd0b64aa24a1be136b00a67 | XandraMcC/LabSheet3.2 | /DBOperations.py | 6,257 | 3.515625 | 4 | import sqlite3
import pandas as pd
import constants as constants
from Employee import Employee
class DBOperations:
def __init__(self):
self.get_connection()
def get_connection(self):
self.conn = sqlite3.connect("mydb")
self.cur = self.conn.cursor()
# Drop table EmployeeUoB
def drop_table(self):
try:
self.get_connection()
self.conn.execute(constants.sql_drop_table)
self.conn.commit()
print(constants.table_dropped)
except Exception as e:
print(e)
finally:
self.conn.close()
# Create Table
def create_table(self):
try:
self.get_connection()
self.cur.execute(constants.sql_create_table)
self.conn.commit()
print(constants.table_created)
except Exception as e:
if self._table_exists():
print(constants.table_exists)
else:
print(e)
finally:
self.conn.close()
# Insert Data
def insert_data(self):
try:
if self._table_exists():
self.get_connection()
emp = Employee()
_id = self._numeric_input(constants.enter_id)
if self._search_data(_id) == False:
emp.set_employee_id(_id)
emp.set_employee_title(input(constants.enter_title))
emp.set_forename(input(constants.enter_forename))
emp.set_surname(input(constants.enter_surname))
emp.set_email(input(constants.enter_email))
emp.set_salary(self._numeric_input(constants.enter_salary))
args = (emp.get_employee_id(), emp.get_employee_title(), emp.get_forename(), emp.get_surname(), emp.get_email(), emp.get_salary())
self.cur.execute(constants.sql_insert, args)
self.conn.commit()
print(constants.data_added)
else:
print(constants.emp_id_exists)
else:
print(constants.table_not_exist)
except Exception as e:
print(e)
finally:
self.conn.close()
# Show all data
def show_all(self):
try:
if self._table_exists():
self.get_connection()
# Using Pandas to format table
print(pd.read_sql_query(constants.sql_select_all, self.conn))
else:
print(constants.table_not_exist)
except Exception as e:
print(e)
finally:
self.conn.close()
# Print data
def print_data(self):
try:
if self._table_exists():
self.get_connection()
_id = self._numeric_input(constants.enter_id)
_result = self._search_data(_id)
if _result != False:
for index, detail in enumerate(_result):
if index == 0:
print(constants.emp_id + str(detail))
elif index == 1:
print(constants.emp_title + detail)
elif index == 2:
print(constants.emp_forename + detail)
elif index == 3:
print(constants.emp_surname + detail)
elif index == 4:
print(constants.emp_email + detail)
else:
print(constants.emp_salary + str(detail))
else:
print (constants.record_not_found)
else:
print(constants.table_not_exist)
except Exception as e:
print(e)
finally:
self.conn.close()
# Update data
def update_data(self):
try:
if self._table_exists():
self.get_connection()
__choose_user = int(input(constants.enter_id_to_update))
__choose_column = int(input(constants.column_update_command))
__update_info = input(constants.update)
__args = (__update_info, __choose_user)
if __choose_column == 1:
self.cur.execute(constants.sql_update_title_data, __args)
elif __choose_column == 2:
self.cur.execute(constants.sql_update_title_data, __args)
elif __choose_column == 3:
self.cur.execute(constants.sql_update_title_data, __args)
elif __choose_column == 4:
self.cur.execute(constants.sql_update_title_data, __args)
elif __choose_column == 5:
self.cur.execute(constants.sql_update_title_data, __args)
self.conn.commit()
print(constants.data_added)
else:
print(constants.table_not_exist)
except Exception as e:
print(e)
finally:
self.conn.close()
# Delete data
def delete_data(self):
try:
if self._table_exists():
self.get_connection()
__choose_user = int(input(constants.enter_id_to_delete))
if self._find_record(__choose_user):
self.cur.execute(constants.sql_delete_data, (__choose_user,))
self.conn.commit()
if self._find_record(__choose_user):
print(constants.record_not_deleted)
else:
print(constants.record_deleted)
else:
print(constants.record_not_found)
else:
print(constants.table_not_exist)
except Exception as e:
print(e)
finally:
self.conn.close()
# Delete all data
def delete_all(self):
try:
if self._table_exists():
self.get_connection()
self.cur.execute(constants.sql_delete_all_data)
self.conn.commit()
else:
print(constants.table_not_exist)
except Exception as e:
print(e)
finally:
self.conn.close()
# Private methods
# Check if EmployeeUoB table exists
def _table_exists(self):
try:
self.get_connection()
self.cur.execute(constants.sql_table_exists)
_table = self.cur.fetchone()
if _table[0] == 1:
return True
else:
return False
self.conn.commit()
except Exception as e:
print(e)
finally:
self.conn.close()
# Find record with EmployeeID
def _find_record(self, emp_id):
self.cur.execute(constants.sql_count_by_id, (emp_id,))
return self.cur.fetchone()
# Search if data exists with EmployeeID
def _search_data(self, id):
_result = self._find_record(id)
if type(_result) == type(tuple()):
return _result
else:
return False
# Check input is numeric
def _numeric_input(self, constant):
_arg = (input(constant))
while _arg.isnumeric() == False:
print(constants.entry_not_numeric)
_arg = (input(constant))
return int(_arg)
|
90806ae210ebcd37d5e930f3f353122b7518177f | chrisguest75/py-wordament-helper | /py_wordament_helper/dictionary_abc.py | 369 | 3.9375 | 4 | from abc import ABC, abstractmethod
from typing import Text
class dictionary_abc(ABC):
@abstractmethod
def is_word(self, word: Text) -> bool:
"""Is the word in the dictionary
Arguments:
word {Text} -- Word to check for in dictionary
Returns:
bool -- True if dictionary contains word
"""
pass
|
8d919c8ff5fff1d5d87a98ca5d5143ed25320812 | Abdul-Rehman1/Python-Assignment1 | /pattern.py | 552 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 13:19:18 2019
@author: Abdul Rehman
"""
'''
for i in range(0,20):
print(" "*(20-i),end="")
print("* "*i,end="")
print()
# print(" *"*i)
for i in range(20,-1,-1):
print(" "*(20-i),end="")
print("* "*i,end="")
# print(" *"*i)
print("Done")
'''
for i in range(0,5):
print("*"*(5-i),end="")
print(" "*i,end="")
print("*"*(5-i))
for i in range(5,-1,-1):
print("*"*(5-i),end="")
print(" "*i,end="")
print("*"*(5-i))
print("Done") |
6efd365cc80b1c343b38f8881e174c41aa2f7efb | Rauf-Totakhil/BoringBookTools | /ReadXlsxFile.py | 221 | 3.546875 | 4 | from openpyxl import Workbook
from openpyxl import load_workbook
import pandas as pd
import os
def readXlsxFile():
df = pd.read_excel (input("Enter Name of the file with Xlsx : "))
print (df)
readXlsxFile()
|
bab18545791bf6e8b510c64caf9713e8a0e5e104 | MageCraft/pyfreecell | /funds/t.py | 2,724 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
(align_left, align_right, align_middle) = range(3)
#header must have following format:
#(text, length, align, data_align)
class PrintTable:
def __init__(self, headers=None, rows=None):
self.headers = headers
if rows is None:
self.rows = []
else:
self.rows = rows
def set_headers(self, headers):
self.headers = headers
def append_row(self, row):
self.rows.append(row)
def line_str(self):
return '-' * ( sum([h[1] for h in headers]) + len(headers) + 1 ) + '\n'
def output(self):
s = ''
s += self.line_str()
s += self.header_str()
s += self.line_str()
s += self.rows_str()
s += self.line_str()
print s
def header_str(self):
s = ''
s += '|'
for header in headers:
text, length, align = header[:-1]
s += self.cell_str(text, length, align)
s += '|'
return s + '\n'
def rows_str(self):
s = ''
for row in self.rows:
s += '|'
for col in range(len(row)):
header = headers[col]
text, length, align = row[col], header[1], header[-1]
s += self.cell_str(text, length, align)
s += '|'
s += '\n'
return s
def cell_str(self, text, length, align):
L = len(text)
assert( L <= length )
s = None
ch = ' '
if align == align_right:
s = ch* (length-L) + text
elif align == align_left:
s = text + ch* (length-L)
else:
l1 = (length-L) / 2
l2 = length-l1-L
s = ch*l1 + text + ch*l2
return s
if __name__ == '__main__':
headers = []
headers.append( ('', 10, align_middle, align_middle) )
headers.append( ('', 10, align_middle, align_middle) )
headers.append( ('ݶ', 10, align_middle, align_middle) )
headers.append( ('', 10, align_middle, align_middle) )
headers.append( ('ֵ', 8, align_middle, align_middle) )
headers.append( ('ǵ', 8, align_middle, align_middle) )
headers.append( ('ǰ', 10, align_middle, align_middle) )
t = PrintTable(headers)
#t.output_cell('', 8, align_left)
#t.output_cell('', 8, align_middle)
#t.output_cell('', 9, align_middle)
row = ('400003', 'ѡ', '20000.00', '20000.00', '1.009', '1.27%', '21500.00')
t.append_row( row )
t.append_row( row )
t.output()
|
dc8e36cdd048bcff0c3bfaa69c71923fd53ec7bc | pgrandhi/pythoncode | /Assignment2/2.VolumeOfCylinder.py | 367 | 4.15625 | 4 | #Prompt the use to enter radius and length
radius,length = map(float, input("Enter the radius and length of a cylinder:").split(","))
#constant
PI = 3.1417
def volumeOfCylinder(radius,length):
area = PI * (radius ** 2)
volume = area * length
print("The area is ", round(area,4), " The volume is ", round(volume,1))
volumeOfCylinder(radius,length)
|
b3e4b7f3b30bc917e1feb007aa3eb289fb9aa479 | pgrandhi/pythoncode | /Triangle.py | 689 | 4.09375 | 4 | import turtle
turtle.pensize(2)
def drawShapeUsingForwardLeft(color):
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
def drawShape(color, start, points):
turtle.pencolor(color)
turtle.penup()
turtle.goto(start)
turtle.pendown()
turtle.begin_fill()
x,y = start
for point in points:
dx, dy = point
turtle.goto(x + dx, y + dy)
turtle.goto(start)
turtle.end_fill()
turtle.penup()
print("Using Forward Left")
drawShapeUsingForwardLeft("blue")
print("Using DrawShape method")
triangleShape=[(200,0), (100,100),(0,0)]
drawShape("red",(100,-100), triangleShape)
|
1bf9ae4f947b407009b3a1423dae4a0bd6df2cb8 | pgrandhi/pythoncode | /Class/OlympicSymbol_Functions.py | 324 | 4.0625 | 4 | import turtle
turtle.pensize(5)
def drawCircle(color, x, y, radius=45):
turtle.color(color)
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.circle(radius)
drawCircle("blue",-110,-25)
drawCircle("black",0,-25)
drawCircle("red",110,-25)
drawCircle("yellow",-55,-75)
drawCircle("green",55,-75)
|
224678df235e2466ec4df9f5ab19c251d44b040b | pgrandhi/pythoncode | /Assignment4/TestStock.py | 295 | 3.796875 | 4 | from Stock import Stock
stock1 = Stock("INTC","Intel Corporation",20.50,20.35)
print("Stock name:",stock1.getName(),"Symbol:",stock1.getSymbol(), "previous closing price",stock1.getPreviousClosingPrice(),"current price:",stock1.getCurrentPrice(),"change Percent:",stock1.getChangePercent())
|
670e2caa200e7b81c4c67abe0e8db28c9d3bce5d | pgrandhi/pythoncode | /Class/BMICalculator.py | 584 | 4.3125 | 4 | #Prompt the user for weight in lbs
weight = eval(input("Enter weight in pounds:"))
#Prompt the user for height in in
height = eval(input("Enter height in inches:"))
KILOGRAMS_PER_POUND = 0.45359237
METERS_PER_INCH = 0.0254
weightInKg = KILOGRAMS_PER_POUND * weight
heightInMeters = METERS_PER_INCH * height
#Compute BMI = WgightInKg/(heightInMeters squared)
bmi = weightInKg /(heightInMeters ** 2)
print("BMI is: ", bmi)
if(bmi <18.5):
print("Under-weight")
elif (bmi <25):
print("Normal weight")
elif (bmi <30):
print("Over-weight")
else:
print("Obese")
|
d9dc45bda82b080bd87db396165a659430f7aee2 | pgrandhi/pythoncode | /Assignment2/8.CalculateEnergy.py | 497 | 3.953125 | 4 | #Prompt the use to enter the input to calculate energy
weightInKgs = eval(input("Enter the amount of water in kilograms:"))
initialTemp = eval(input("Enter the initial temperature:"))
finalTemp = eval(input("Enter the final temperature:"))
#constants
ENERGY_CONST = 4184
def calculateEnergy(weightInKgs, initialTemp, finalTemp):
energy = weightInKgs * (finalTemp - initialTemp)* ENERGY_CONST
print("The energey needed is",energy)
calculateEnergy(weightInKgs,initialTemp,finalTemp)
|
8c544140e9567a5de4b2bf10e08989d793b8d2e2 | pgrandhi/pythoncode | /Assignment4/TestTime.py | 320 | 3.921875 | 4 | from Time import Time
t = Time()
print("Time class created")
print ("Current time :", t.getHour(),":",t.getMinute(),":",t.getSecond())
elapseTime = eval(input("Enter the elapsed time:"))
t.setTime(elapseTime)
print ("The hour:minute:second for the elapsed time is :", t.getHour(),":",t.getMinute(),":",t.getSecond())
|
040517aec84c454143f6fc41ee34cbcfb12928a6 | 16GordonA/Essay-Writer | /paragraphs.py | 3,211 | 3.96875 | 4 | '''
Takes paragraph as text string, parses for quotes, searches internet to find full quote and verifies with citation
Several different types of paragraphs which will be formed using the inputted quotes
'''
from fileparse import *
qmarks = ['"'] #quotation marks since... there are several for some reason
#sample paragraph follows from an old essay. The program will take paragraphs in from text files in the future
paragraph = 'In his sonnet 90, Shakespeare requests that the Fair Youth end his relationship with the Poet, and "hate [him]...'
paragraph +=' if ever, now" (XC i), in order that he might contribute to the beginning of a cycle of bad fortune, rather than "drop in fo'
paragraph +='r an after-loss" (iv). This theme continues as the Poet mentions further "sorrow" and likens his experiences to a "windy nig'
paragraph +='ht" (v,vii). Finally, Shakespeare concludes that, though a break-up with the Fair Youth would be "the very worst of fortune' + "'"
paragraph +='s might" (xii), it will alleviate the suffering caused by the Poet'+"'"+'s other misfortunes. However, this romantic outlook on th'
paragraph +='eir love is tempered by the use of military language throughout the sonnet.'
def match(quotes, citations):
matched = [] #[ [ ["quote" , "quote"] , (citation)] , [ ["quote" , "quote"] , (citation)] ]
temp = []
c = 0
q = 0
while q < len(quotes):
#print(q)
if quotes[q][1] < citations[c][0]: #if quote is before that citation
temp = temp + [ paragraph[quotes[q][0] : quotes[q][1]] ]
#print(temp)
q = q + 1
else:
matched = matched + [[temp , paragraph[citations[c][0] : citations[c][1]] ]]
#print(matched)
temp = []
c = c + 1
#print ('reached')
matched = matched + [[temp , paragraph[citations[c][0] : citations[c][1]] ]]
#print(matched)
#adds authors for all quotes
print(matched)
mrauthor = 'default' #most recent author
for p in range(len(matched)):
cit = matched[p][1]
if ',' in cit and cit.index(',') > 5: #crude method of making sure it's not a citation like (72,74)
mrauthor = cit[1:cit.index(',')]
print(mrauthor)
matched[p] = matched[p] + [mrauthor] #appends author to citation
return matched
paragraphs = parse()
paragraph = paragraphs[0] + ' ' + paragraphs[1]
print(paragraph)
quotes = [] #will hold tuples of <start quote , end quote> values
citations = [] #will hold tuples of <start citation, end citation> values
qbeg = -1 #will store locations of first quote
cbeg = -1 #will store locations of first paren
for i in range(len(paragraph)): #sweeps paragraph
if paragraph[i:i+1] == '"':
if qbeg >= 0:
quotes = quotes + [[qbeg, i]]
qbeg = -1
else:
qbeg = i + 1
elif paragraph[i:i+1] == '(' or paragraph[i:i+1] == ')':
if cbeg >= 0:
citations = citations + [[cbeg, i + 1]]
cbeg = -1
else:
cbeg = i
print(quotes)
print(citations)
m = match(quotes, citations)
print(m)
|
82d8385e9f60546bc89fb5faed44fe627279970f | doseboy/CSCI-4830 | /project1/vigenere.py | 6,063 | 3.671875 | 4 | #!/usr/bin/python3
#Author: William Anderson
#Identikey: wian8678
#Assignment: Project 1
#Class: ECEN 4113
import sys
from collections import Counter
#taken from Wikipedia
letter_freqs = {
'A': 0.08167,
'B': 0.01492,
'C': 0.02782,
'D': 0.04253,
'E': 0.12702,
'F': 0.02228,
'G': 0.02015,
'H': 0.06094,
'I': 0.06966,
'J': 0.00153,
'K': 0.00772,
'L': 0.04025,
'M': 0.02406,
'N': 0.06749,
'O': 0.07507,
'P': 0.01929,
'Q': 0.00095,
'R': 0.05987,
'S': 0.06327,
'T': 0.09056,
'U': 0.02758,
'V': 0.00978,
'W': 0.02361,
'X': 0.00150,
'Y': 0.01974,
'Z': 0.00074
}
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def pop_var(s):
"""Calculate the population variance of letter frequencies in given string."""
freqs = Counter(s)
mean = sum(float(v)/len(s) for v in freqs.values())/len(freqs)
return sum((float(freqs[c])/len(s)-mean)**2 for c in freqs)/len(freqs)
# ic(string: ciphertext)
# This function returns the Index of Coincidence for the sequence of ciphertext given
# Returns an integer
def ic(ciphertext):
# Length of ciphertext to be used in IC equation
N = float(len(ciphertext))
# Variable for the frequency of the char in alphabet
frequency = 0.0
# Go through alphabet list
for char in alphabet:
# Source: https://en.wikipedia.org/wiki/Index_of_coincidence
frequency += ciphertext.count(char) * (ciphertext.count(char) - 1)
return frequency / (N * (N - 1))
# findKeyLen(string: ciphertext)
# Finds the length of the key given a cipher text
# This uses the Kasiski method byt is more verbose and abstract
def findKeyLen(ciphertext):
#index of coincidence table
icTable = []
# For guess length of highest keylen guess. Go through each of the sequences
# all the way up to 13. After splitting up the cipher text into sequences up
# to size 13, sort the index of coincidences of those sequences.
for guess in range(13):
#IC for a particular sequence
icSum = 0.0
#Average of those sequences
icAverage = 0.0
# Build sqeuence from ciphertext based upon indicie
for i in range(guess):
sequence = ""
# This is the part that breaks up the ciphertext based upon
# the sequence number and guess length
for j in range(0, len(ciphertext[i:]), guess): #For
sequence += ciphertext[i+j]
# Build the IC sum to come up with average
icSum += ic(sequence)
# If on first indicie, avoid dividing by zero and just add it
# to the table.
if not guess == 0:
icAverage = icSum / guess
icTable.append(icAverage)
# Find the best IC from the stable after sorting it. If the first guess
# this is to deal with if the key is twice or three times itself. In
# order to prevent IC's of repeated keys we throw out the first best guess
# for the second one, or just take the first one if it is long enough.
best = icTable.index(sorted(icTable, reverse = True) [0])
secondBest = icTable.index(sorted(icTable, reverse = True) [1])
if best % secondBest == 0:
return secondBest
else:
return best
# frequencyAnalysis(string: seq):
# This uses the Chi squared statistic in order to compare a sequence to
# the dictionary of frequencies of letters in the english language.
# Returns a character.
def frequencyAnalysis(seq):
# Turn dict into list of frequencies to loop through
values = letter_freqs.values()
valuesList = list(values)
# List of Chi Squareds for each letter corresponding by index
chiSquareds = [0] * 26
#Offset based upon if we are dealing with capitals or not
offset = ord('A')
# Go through sequence letter by letter and develop chi squared
# for each letter of the alphabet
for i in range(26):
#This is the summation variable of chi squared equation
chiSquaredSum = 0.0
# This is meant to deal with the ascii offset when dealing with chi squared equation
seqOffset = [chr(((ord(seq[j]) - offset - i) % 26)+offset) for j in range(len(seq))]
# This is the observed value in chi squared equation
observed = [0] * 26
# Generate table of observed values from ascii
for l in seqOffset:
observed[ord(l) - ord('A')] += 1
# Divide these to make them into frequencies between 0 and 1
for j in range(26):
observed[j] *= (1.0/float(len(seq)))
# Now they are comparable to our list of letter frequencies
for j in range(26):
chiSquaredSum += ((observed[j] - float(valuesList[j]))**2)/float(valuesList[j])
chiSquareds[i] = chiSquaredSum
# Find the index of the smalles chi squared and this is how you get
# the number of your letter.
shift = chiSquareds.index(min(chiSquareds))
# Account for ascii shift
return chr(shift+offset)
# findKey(string: ciphertext, int: keylen):
# Once you know your key length all you have to do is loop through
# all of the sequences up to that length and do a frequency analysis to
# determine all possible characters of this key.
def findKey(ciphertext, keylen):
# Our eventual key.
key = ''
# Loop through each sequence of ciphertext up to key length
for i in range(keylen):
# Our eventual sequence.
seq = ""
for j in range(0,len(ciphertext[i:]), keylen):
seq += ciphertext[i+j]
# Do frequency analysis to get each character of the key
key += frequencyAnalysis(seq)
return key
if __name__ == "__main__":
# Read ciphertext from stdin
# Ignore line breaks and spaces, convert to all upper case
cipher = sys.stdin.read().replace("\n", "").replace(" ", "").upper()
#################################################################
# Your code to determine the key and decrypt the ciphertext here
# print("Cipher: " + cipher)
# keyLength = findKeyLen(cipher)
# print("Key Length: " + str(keyLength))
# print("-" * 20)
print("Key: " + findKey(cipher, keyLength))
|
10adfe46188ab41c061efdba5d694e966a479f6b | LucianErick/URI | /estruturas_e_bibliotecas/pares_e_impares.py | 793 | 4.0625 | 4 | numberList = []
pairList = []
oddList = []
## functions
def bubbleSort(vector):
for i in range(len(vector) - 1):
for j in range(len(vector) - 1):
if(vector[j+1] < vector[j]):
vector[j], vector[j + 1] = vector[j + 1], vector[j]
def reverseBubbleSort(vector):
for i in range(len(vector) - 1):
for j in range(len(vector) - 1):
if(vector[j+1] > vector[j]):
vector[j], vector[j + 1] = vector[j + 1], vector[j]
# code
qtd = int(input())
for number in range(qtd):
n = int(input())
if(n % 2 == 0):
pairList.append(n)
else:
oddList.append(n)
bubbleSort(pairList)
reverseBubbleSort(oddList)
# output
for number in pairList:
print (number)
for number in oddList:
print (number) |
dc4eb7f06aebe59bbbbdf90dc4bca68b97630d40 | BenPoole2005/Practice | /guessingGame.py | 376 | 4.0625 | 4 | print("guess a number between 1 and 20")
import random
number = random.randint(1,22)
guess = 0
while guess != number:
guess = raw_input()
if guess == "q":
break
else:
guess = int(guess)
if number == 21:
print("NO")
elif guess > 20:
print("Idiot")
elif guess == number:
print("You win!!")
elif guess > number:
print("Too high")
else:
print("too low")
|
491d43e6905758402b2aaa59e65efb65e4e2ea61 | nguyenhuudat123/lesson5 | /bt3.py | 403 | 3.609375 | 4 |
def is_perfect(n):
# kiểm tra xem số tự nhiên n có phải là số hoàn hảo hay ko,
sum = 0
if n <= 0:
return 0
elif n == 1:
return 1
else:
for i in range(1, int(n/2)+1):
if n % i == 0:
sum += i
if sum == n:
return 1
else:
return 0
if is_perfect(6):
print('hh')
else:
print("khong hh") |
ca2840732d5629eb14bbfc80d607b3674ba2b72e | MosesSymeonidis/aggregation_builder | /aggregation_builder/operators/arithmetic.py | 5,352 | 3.75 | 4 | def ABS(expression):
"""
Returns the absolute value of a number.
See https://docs.mongodb.com/manual/reference/operator/aggregation/abs/
for more details
:param expression: The number or field of number
:return: Aggregation operator
"""
return {'$abs': expression}
def ADD(*expressions):
"""
Adds numbers together or adds numbers and a date.
If one of the arguments is a date, $add treats the other arguments as milliseconds to add to the date.
See https://docs.mongodb.com/manual/reference/operator/aggregation/add/
for more details
:param expressions: The numbers or fields of number
:return: Aggregation operator
"""
return {'$add': list(expressions)}
def CEIL(expression):
"""
Returns the smallest integer greater than or equal to the specified number.
See https://docs.mongodb.com/manual/reference/operator/aggregation/ceil/
for more details
:param expression: The number or field of number
:return: Aggregation operator
"""
return {'$ceil': expression}
def DIVIDE(x, y):
"""
Divides one number by another and returns the result.
See https://docs.mongodb.com/manual/reference/operator/aggregation/divide/
for more details
:param x: The number or field of number (is the dividend)
:param y: The number or field of number (is the divisor)
:return: Aggregation operator
"""
return {'$divide': [x, y]}
def EXP(number):
"""
Returns the exponential value of a number.
See https://docs.mongodb.com/manual/reference/operator/aggregation/exp/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$exp': number}
def FLOOR(number):
"""
Returns the largest integer less than or equal to the specified number.
See https://docs.mongodb.com/manual/reference/operator/aggregation/floor/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$floor': number}
def LN(number):
"""
Calculates the natural logarithm ln of a number and returns the result as a double.
See https://docs.mongodb.com/manual/reference/operator/aggregation/ln/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$ln': number}
def LOG(number, base):
"""
Calculates the log of a number in the specified base and returns the result as a double.
See https://docs.mongodb.com/manual/reference/operator/aggregation/log/
for more details
:param number: The number or field of number
:param base: The base of log operation
:return: Aggregation operator
"""
return {'$log': [number, base]}
def LOG10(number):
"""
Calculates the log base 10 of a number and returns the result as a double.
See https://docs.mongodb.com/manual/reference/operator/aggregation/log10/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$log10': number}
def MOD(x, y):
"""
Divides one number by another and returns the remainder.
See https://docs.mongodb.com/manual/reference/operator/aggregation/mod/
for more details
:param x: The number or field is the dividend,
:param y: The number or field is the divisor,
:return: Aggregation operator
"""
return {'$mod': [x, y]}
def MULTIPLY(*expressions):
"""
Multiplies numbers together and returns the result.
See https://docs.mongodb.com/manual/reference/operator/aggregation/multiply/
for more details
:param expressions: An array of numbers or fields
:return: Aggregation operator
"""
return {'$multiply': list(expressions)}
def POW(number, exponent):
"""
Raises a number to the specified exponent and returns the result.
See https://docs.mongodb.com/manual/reference/operator/aggregation/pow/
for more details
:param number: The number or field that will be raised
:param exponent: The number or field that will be the exponent
:return: Aggregation operator
"""
return {'$pow': [number, exponent]}
def SQRT(number):
"""
Calculates the square root of a positive number and returns the result as a double.
See https://docs.mongodb.com/manual/reference/operator/aggregation/sqrt/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$sqrt': number}
def SUBTRACT(x, y):
"""
Subtracts two numbers to return the difference,
or two dates to return the difference in milliseconds,
or a date and a number in milliseconds to return the resulting date.
See https://docs.mongodb.com/manual/reference/operator/aggregation/subtract/
for more details
:param x: The number or field of number
:param y: The number or field of number (is subtracted from the first argument)
:return: Aggregation operator
"""
return {'$subtract': [x, y]}
def TRUNC(number):
"""
Truncates a number to its integer.
See https://docs.mongodb.com/manual/reference/operator/aggregation/trunc/
for more details
:param number: The number or field of number
:return: Aggregation operator
"""
return {'$trunc': number}
|
3596417999170bb42042659bdf7864ece1d8fa16 | Puthiaraj1/Comprehensions | /timtit_challenge.py | 482 | 3.78125 | 4 | import timeit
def fact(n):
result = 1
if n > 1:
for f in range(2, n + 1):
result *= f
return result
def factorial(n):
# n! can also be defined as n * (n-1)!
if n <= 1:
return 1
else:
return n * factorial(n-1)
if __name__ == '__main__':
print(timeit.timeit("x = fact(130)", setup="from __main__import fact", number=1000))
print(timeit.timeit("x = factorial(130)", setup="from __main__import fact", number=1000)) |
6325c9d7e3c9d68cb5e82f4c86d7db8c48c915aa | aviik/pirple_py_Is_easy | /homework1.py | 613 | 3.546875 | 4 | """ Program to enlist some of the important
attributes that could describe a song """
#Attribute variables
song = " I'll Play The Blues For You"
artist = "Daniel Castro"
albumn = "No Surrender"
year = 1999
genre = "Blues"
sub_genre = "Blues-Contemporary"
track_number = 8
song_duration = 7.42
#Attribute Labels Print Format
print("")
print("")
print("Song: ", song)
print("Artist: ", artist)
print("Albumn: ", albumn)
print("Year: ", year)
print("Genre: ", genre)
print("Sub-genre: ", sub_genre)
print("Track Number:",track_number)
print("Length: ", song_duration) |
338461346f5813f79e5fc25eaab7e5caaf6eba6e | tarados2/prueba1 | /paroimpar.py | 155 | 3.90625 | 4 | ### Introducir un numero por teclado y decir si es par o impar
num = int(input('Introduzca un numero: '))
ifnum % 2 == 0:
print('Par')
else:
print('Impar') |
4fc02d640d9387001833cb7376581298d53c5547 | zioan/list_comprehensions | /only_nymbers.py | 567 | 3.84375 | 4 | temps = [221, 234, 340, -9999, 230]
#-9999 means no data
new_temps = [temp / 10 for temp in temps if temp != -9999]
print(new_temps)
#[22.1, 23.4, 34.0, 23.0]
#-9999 is excluded from the loop/execution
#will display only numbers, no strings
def foo(lst):
new_lst = []
for i in lst:
if isinstance(i, int):
new_lst.append(i)
return new_lst
print(foo([99, "no data", 45]))
#will display only positive numbers
numbers = [-5, 3, -1, 101]
def num(numbers):
return [numb for numb in numbers if numb > 0]
print(num(numbers)) |
2efd04f806a3108cc5a6856a1a3a12807d9fe5ba | Antoine07/Data-01 | /Exercices_chap1_introduction/moyenne.py | 530 | 3.671875 | 4 | #! /usr/bin/env python
"""
Calculateur de moyenne
======================
Ce programme admet un nombre arbitraire d'arguments.
Il affiche la moyenne de toutes les valeurs.
"""
from argparse import ArgumentParser
from statistics import mean
parser = ArgumentParser()
parser.add_argument(dest="nombres", type=int, nargs='*', help="entier")
input_args = parser.parse_args()
nombres = input_args.nombres
print(nombres)
resultat = mean(nombres)
print("La moyenne de la série de nombres est : {}".format(resultat)) |
92ce6a908d91d420ea44e404f659fa4d428b71f2 | PaulG17/python-project-lvl1 | /brain_games/games/gcd.py | 553 | 3.671875 | 4 | from random import randint
DESCRIPTION = "Find the greatest common divisor of given numbers."
def prepare_round():
one = randint(1, 100)
two = randint(1, 100)
question = f"{one} {two}"
right_answer = gcd(one, two)
return question, str(right_answer)
def gcd(one, two):
if one == two:
return one
if one < two:
two, one = one, two
remainder = one % two
if remainder == 0:
return two
while remainder != 0:
remainder = one % two
one, two = two, remainder
return one
|
e17f5a02da071dcc1dae864460babf1d2690bb7b | VladimirKozlov466/QAP_module_16 | /testCat.py | 835 | 3.75 | 4 | from cat import Cat
Baron = Cat("Барон", "мальчик", 2)
Sam = Cat("Сэм", "мальчик", 2)
# --------- Вывод из этого файла
print(f'Имя питомца: {Baron.getName()}, Пол питомца: {Baron.getGender()}, Возраст: {Baron.getAge()} года')
print(f'Имя питомца: {Sam.getName()}, Пол питомца: {Sam.getGender()}, Возраст: {Sam.getAge()} года')
# ---------- Вывод через функцию из оригинального файла (надо ли?!)
# выводит в дополнение вымышленного питомца "Федора" из оригинального файла (на первом месте)?)))) не требуется но хочется знать почему))
print(Baron.pet_info())
print(Sam.pet_info())
|
8f672d109a35cd8647a5e16f217323301d202cca | gustavo-moura/SCC5900-algorithm-design | /04-backtracking-queens-chess/backtracking.py | 2,108 | 4.03125 | 4 | # -*- coding: utf-8 -*-
"""
# Backtracking
## SCC5900 - Algorithm Design
### Lecture 4
#### v1
"""
import sys
def printBoard(board):
for l in range(8):
for c in range(8):
print(f"{board[l][c]:2}", end=" ")
print('')
def zeroes(l):
return [False for _ in range(l)]
def condition(lin, col, params):
if (
not params['lines'][lin]
and not params['right_diagonal'][lin - col + 7]
and not params['left_diagonal'][lin + col]
):
return True
return False
def set_control(lin, col, params, boolean):
params['lines'][lin] = boolean
params['right_diagonal'][lin - col + 7] = boolean
params['left_diagonal'][lin + col ] = boolean
def backtracking(col, summ, params, max_scores):
if col == 8:
max_scores.append(summ)
return True
for lin in range(8):
if condition(lin, col, params):
set_control(lin, col, params, True)
backtracking(col + 1, summ + params['board'][lin][col], params, max_scores)
set_control(lin, col, params, False)
return False
def solveQueens(board):
max_scores = []
# Control lists, marks if a queen blocks certain line or diagonal
params = {
'lines': zeroes(8), # lines
'right_diagonal': zeroes(15), # diagonals left-up to right-down
'left_diagonal': zeroes(15), # diagonals right-up to left-down
'board': board,
}
backtracking(0, 0, params, max_scores)
print(f"{max(max_scores):5}")
if __name__ == "__main__":
# with open('1.in', 'r') as file:
# content = file.readlines()
data = sys.stdin.readlines()
content = [line.rstrip() for line in data]
n_test_cases = int(content[0])
# boards = []
for n in range(0, n_test_cases):
board = []
for l in range(1,9): # Board square with size 8
line = [int(c) for c in content[n * 8 + l].replace('\n', '').split()]
board.append(line)
solveQueens(board)
# boards.append(board)
|
fe80ce91e178bb8da556ab141e00de1133de9c41 | edwinnab/code_python | /strings.py | 158 | 3.59375 | 4 | name ="john is {} a boy"
print(name.format("very clean"))
print(name.count("[0:]"))
num = "John"
num1 = "Edwinn"
num2 = "Bikeri"
print(num[0],num1[0],num2[0]) |
3c77545df683b67b1c16cf7f478a325ba5af5bb4 | edwinnab/code_python | /datatypes.py | 3,605 | 4.53125 | 5 | """
#integers
print(34)
#assign to a variable
num = 34
print(num)
#perform mathematical operations
#addition
num = 34
num2 = 45
#sum is a keyword to perform addition uses the operator +
sum = (num + num2)
print(sum)
#subtraction
print(num - num2)
#multiplication
print(num * num2)
#division integer division
print(num/num2)
#floor division
print(num//num2)
#check what data type yoy have by using the function type()
print(type(sum))
"""
"""
#float has decicimal points
num = 45.32
print(num)
#check type
print(type(num))
#float is not equal to an integer
"""
"""
#Boolean named after George Boole a mathematician
#used for logical operations
#True,False are special values in python thus start with a capital letter.
num = True
print(num)
#check type
print(type(num))
"""
"""
#strings is a sequence of one or more characters (letters, numbers ,symbols)
#sting can be either constant or variable
#store a string on a variable
my_str = "Edwinna"
print(my_str)
print(type(my_str))
#operations on strings
#lists are mutable,use square brackets on list,
#access elements using indeces
my_list = ["money", "food", "clothes", "pencils"]
print(type(my_list))
#tuple use round brackets and are immutable
my_tuple = (1,2,3,4,5,6)
print(type(my_tuple))
#dictionaries use curly braces and have a key_value pair
my_dict = {"two": 2, "three": 3, "four": 4}
print(type(my_dict))
#sets non repetitive, curly braces
my_set = {"money", "love","family"}
print(type(my_set))
"""
#working with strings
#exist within double quotes ad single quotes
#whichever you choose to use just be consistent
#display using the print function
units = " this is a very long string "
print(type(units))
#manipulation of strings
#concatination +
#to have a space between the strings you use whitespaces inside the string
cs = "string"
print( cs + units)
print("Edwinna" + " Bikeri")
#string replication, repeats the string several times uses the* operator
print("CODE UNTIL YOU CODE " *4)
#string literal (what we see in the source code including the quotation marks),
#string value is what we see after running the program,
#string literal
name = "Edwinna Bikeri"
#string value
print(name)
#quotes embed double quotes within single quotes
print('edwinna says, "hello"')
#apostrophe use the possessive apostrophe with double quotes
print("Edwinna's car")
#to display multiple lines use triple single/double quotes
print("this is my car")
#or triple multiple lines
print("""call it family,
how amazing to have that,
amazing i tell you
am just tryin to show
the use of triple quotes
to display multiple lines""")
#use backslash \ for quotations
print("Edwinna says \"hello\"")
print("edwinna\'s car")
print("1. maize" "2. love" "3. beans")
print("sammy\'s says \"the baloon is red?\"")
#raw string tells python to ignore all the escape characters.
print(r"sammy's says this is the color red?")
print(r"sammy\'s says \"the baloon is red?\"")
print(name.upper())
print(name.lower())
print(len(name))
print(name.replace("Bikeri","Omwando"))
"""
"""
#boolean methods return True, False
#.isnumeric prints True if numeric
phone_number = "098279747"
print(phone_number.isnumeric())
#.isupper() accepts uppercase
name = "a ahsjakak3826282"
print(name.isupper())
#.isalpha accepts alphabets
school = "hakkVDSJYE"
print(school.isalpha())
#.isalnum accepts alphanumerc
pasd ="njkj2889913931"
print(pasd.isalnum())
#.islower accepts lowercase
phone = "hjo b aeihwqwu"
print(phone.islower())
sent = "this is a sentenses to check something I've learnt"
mak = "this too so just follow"
print(reversed(mak))
print(mak.count("o")) |
99c1967188396b40b668b043f3de75235b39b62f | samrooj/Prisoners-Dilemma-in-Trees | /player.py | 2,081 | 3.625 | 4 | """CSC111 Winter 2021 Final Project
Module Description
==================
This module handles Player, which represents any decision-maker in a game of
Prisoner's Dilemma.
Copyright and Usage Information
===============================
This file is provided solely for the personal and private use of TAs and instructors
involved with CSC111 at the University of Toronto St. George campus. All forms of
distribution of this code, whether as given or with any changes, are
expressly prohibited.
Copyright (c) 2021 Abdus Shaikh, Jason Wang, Samraj Aneja, Kevin Wang
"""
from __future__ import annotations
from typing import Optional
import pd_strategy
from pd_game import PDGame
class Player:
"""A player of Prisoner's Dilemma.
Instance Attributes:
- strategy: the strategy algorithm which this player uses
- curr_points: the number of points this player has so far
- player_num: 1 if this player is Player 1 or 2 if this player is Player 2
Representation Invariants:
- player_num in {1, 2}
"""
curr_points: int
strategy: Optional[pd_strategy.Strategy]
player_num: int
def __init__(self, strategy: Optional[pd_strategy.Strategy], player_num: int) -> None:
self.curr_points = 0
self.strategy = strategy
self.player_num = player_num
def __copy__(self) -> Player:
"""Create a new copy of this Player.
"""
return Player(self.strategy.__copy__(), self.player_num)
def make_move(self, game: PDGame) -> bool:
"""Return True if this player cooperates, and False otherwise.
"""
return self.strategy.make_move(game)
if __name__ == '__main__':
import python_ta.contracts
python_ta.contracts.check_all_contracts()
import doctest
doctest.testmod()
import python_ta
python_ta.check_all(config={
'extra-imports': ['pd_strategy', 'pd_game'], # the names (strs) of imported modules
'allowed-io': [], # the names (strs) of functions that call print/open/input
'max-line-length': 100,
'disable': ['E1136']
})
|
a726d85e43863c9bb2182a2c18c5b60c6863d120 | ZicanGong/exercise | /ex7.py | 1,822 | 3.515625 | 4 | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
m = len(board)
n = len(board[0])
if board[0][0] == word:
return True
def dfs(a,b,s,history):
if a > 0:
if board[a-1][b] == s[0] and (a-1,b) not in history:
if len(s) == 1:
return True
else:
if dfs(a-1,b,s[1:],history+[(a-1,b)]): return True
if a < m-1:
if board[a+1][b] == s[0] and (a+1,b) not in history:
if len(s) == 1:
return True
else:
if dfs(a+1,b,s[1:],history+[(a+1,b)]): return True
if b > 0:
if board[a][b-1] == s[0] and (a,b-1) not in history:
if len(s) == 1:
return True
else:
if dfs(a,b-1,s[1:],history+[(a,b-1)]): return True
if b < n-1:
if board[a][b+1] == s[0] and (a,b+1) not in history:
if len(s) == 1:
return True
else:
if dfs(a,b+1,s[1:],history+[(a,b+1)]): return True
return False
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == word[0]:
if not word[1:]:
return True
if dfs(i,j,word[1:],[(i,j)]):
return True
return False
# https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
|
35e884947ad00e548f06347fc3c5bf2316e11299 | parduman/lovebabbar450 | /tree/leftViewOfTree.py | 1,235 | 3.875 | 4 | class Node:
def __init__(self, data) -> None:
self.data = data
self.left = None
self.right = None
def leftViewOfTree(node, height, maxheight):
if not node: return
if(height>maxheight[0]):
print(node.data)
maxheight[0] += 1
if node.left: leftViewOfTree(node.left, height+1, maxheight)
if node.right: leftViewOfTree(node.right, height+1, maxheight)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.right.left.left = Node(7)
root.right.left.right = Node(8)
maxheight = [-1]
leftViewOfTree(root,0,maxheight)
print(maxheight)
# geekForGeeksSolution
# maxheight=-1
# arr = []
# def LeftView(node):
# global arr,maxheight
# LeftViewTree(node,0)
# arrToReturn = arr
# arr = []
# maxheight = -1
# return arrToReturn
# # code here
# def LeftViewTree(node, height = 0):
# global maxheight, arr
# if not node: return
# if(height>maxheight):
# arr.append(node.data)
# maxheight += 1
# height += 1
# if node.left: LeftViewTree(node.left, height)
# if node.right: LeftViewTree(node.right, height)
# return arr
|
3066f03eb90bb1175b303f818865db2aa69d731f | laxmankusuma/practice_notebook | /Approaching_Almost_Any_Machine_Learning_Problem_1.py | 3,297 | 4.09375 | 4 | #!/usr/bin/env python
# coding: utf-8
# # by Abhishek Thakur
# # Supervised vs unsupervised learning
# • **Supervised data:** always has one or multiple targets associated with it.
# <br>
# • **Unsupervised data:** does not have any target variable.
# If the target is categorical, the problem becomes a classification problem. And if the target is a real number, the problem is defined as a regression problem.
# <br>
# <br>
# • **Classification:** predicting a category, e.g. dog or cat.
# <br>
# • **Regression:** predicting a value, e.g. house prices.
# Clustering is one of the approaches of Unsupervised problems.
# <br>
# To make sense of unsupervised problems, we can also use
# numerous decomposition techniques such as **Principal Component Analysis
# (PCA)**, **t-distributed Stochastic Neighbour Embedding (t-SNE) etc.**
# https://www.kaggle.com/arthurtok/interactive-intro-to-dimensionality-reduction
# In[1]:
import matplotlib.pyplot as plt # for plotting
import numpy as np # to handle the numerical arrays
import pandas as pd # to create dataframes from the numerical arrays
import seaborn as sns # for plotting
from sklearn import datasets # to get the data
from sklearn import manifold # to perform t-SNE
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
data = datasets.fetch_openml(
'mnist_784',
version=1,
return_X_y=True
)
pixel_values, targets = data
# In[3]:
pixel_values
# 784 means 28*28 pixels(each records is one image)
# In[4]:
pixel_values.info()
# In[5]:
targets
# In[6]:
targets = targets.astype(int)
# In[7]:
targets
# We can visualize the samples in this dataset by reshaping them to their original
# shape and then plotting them using matplotlib.
# In[8]:
single_image = pixel_values.iloc[1, :].values.reshape(28, 28)
plt.imshow(single_image, cmap='gray')
# In[9]:
tsne = manifold.TSNE(n_components=2, random_state=42)
transformed_data = tsne.fit_transform(pixel_values.iloc[:3000, :])
# In[10]:
transformed_data
# In[11]:
len(transformed_data)
# the above step creates the t-SNE transformation of the data.
# <br>
# We use only two components as we can visualize them well in a two-dimensional setting.
# <br>
# The transformed_data, in this case, is an array of shape 3000x2 (3000 rows and 2 columns). A data like this can be converted to a pandas dataframe by calling pd.DataFrame on the array.
# In[12]:
tsne_df = pd.DataFrame(
np.column_stack((transformed_data, targets[:3000])),
columns=['x','y','targets']
)
# In[13]:
tsne_df #x and y are the two components from t-SNE decomposition and targets is the actual number
# In[14]:
grid = sns.FacetGrid(tsne_df, hue='targets', size=8)
grid.map(plt.scatter, 'x', 'y').add_legend()
# This above is one way of visualizing unsupervised datasets.
# <br>
# We can also do **k-means clustering** on the same dataset and see how it performs in an unsupervised setting. You have to find the number clusters by **cross-validation.**
# <br>
# MNIST is a supervised classification problem, and we converted it to an unsupervised problem only to check if it gives any kind of good results.
# <br>
# we do get good results with decomposition with t-SNE, the results would be even better if we use classification algorithms
|
5177016ebf88ce8b363829b422b6399d36e26caa | eimearfoley/MosaicMake | /api/backups/get_photo_ids.py | 1,688 | 3.53125 | 4 | """
A simple example script to get all photos on a user's timeline.
Originally created by Mitchell Stewart.
<https://gist.github.com/mylsb/10294040>
"""
import facebook
import requests
from PIL import Image
from io import BytesIO
def some_action(photo, p, i):
#saves the photo in the folder 'photos' eg photos/0_0.jpeg
response = requests.get(photo['source'])
img = Image.open(BytesIO(response.content))
img = img.resize ((tileWidth, tileWidth), Image.ANTIALIAS)
img.save("photos/%i_%i.jpeg" %(p, i))
return(photo['source'])
def get_facebook_images():
# You'll need an access token here to do anything. You can get a temporary one
# here: https://developers.facebook.com/tools/explorer/
access_token = 'EAACEdEose0cBAFw2yQcdkBRrt4CpXzetgC7tEZAyZBx1EvGe8eKHDet6sZC1I7ZBWR3y7V0KArLdDyo3K1MfsWL9GFN54q7gZAiOttT24q5yIsLO6P8OATPE6fvSng5GtTVQq40NQeuAoiZBf4alsHlJH3MTQRw8fZB9sQlhG77WQZDZD'
# Look at my profile!
user = 'me'
graph = facebook.GraphAPI(access_token)
profile = graph.get_object(user)
photos = graph.get_connections(profile['id'], 'photos')
# Wrap this block in a while loop so we can keep paginating requests until
# finished.
page = -1
while True:
page += 1
try:
# Perform some action on each photo in the collection we receive from
# Facebook.
img = 0
for photo in photos['data']:
some_action(photo, page, img)
img += 1
# Attempt to make a request to the next page of data, if it exists.
photos = requests.get(photos['paging']['next']).json()
except KeyError:
# When there are no more pages (['paging']['next']), break from the
# loop and end the script.
break
print("Done!")
|
e8ed6b7ea00018d8190062643bfafb3c8770bd38 | AntoData/Hate_Crimes_Spain_2014_2017 | /Instantiators/LinearRegression.py | 5,607 | 3.921875 | 4 | '''
Created on 27 oct. 2019
@author: ingov
'''
#We import pandas to manage our data through dataframes
import pandas as pd
#We import this modules to handle linear regression tasks
from sklearn import datasets, linear_model
#We import this modules to handle r square calculations
from sklearn.metrics import mean_squared_error,r2_score
#We import matplotlib to handle how to plot charts
import matplotlib.pyplot as plt
#We import numpy to handle math tasks
import numpy as np
#We import this custom made module to handle how to get the information in the format
#we need for our dataframes
from data import getDataFrame as gdf
#We create two different dataframes reading those excel files
print("Loading data")
dflgtbiphobia = gdf.getDataFrameReady("Lgtbifobia", "Name", "../data/ProvincesCoordinates.xlsx", "../data/HateCrimes")
print(dflgtbiphobia)
dfxenophobia = gdf.getDataFrameReady("Xenofobia", "Name", "../data/ProvincesCoordinates.xlsx", "../data/HateCrimes")
print(dfxenophobia)
#We create a dataframe using the dataframe that contains the data for lgtbiphobic crimes
#but we filter the dataframe getting only the columns that contain the number of crimes per year
#and use the function sum() to get the total of lgtbiphobic crimes every year. We also use the
#function rename to give this dataseries a name so when it necomes a row for our dataframe, it
#has an index with an appropiate name
print("Performing some transformations")
df = pd.DataFrame(dflgtbiphobia[range(2014,2018)].sum().rename("lgtbiphobia"))
#We transpose the dataframe so now it has one row and 4 columns. The row represents lgtbiphobic
#crimes and every column represent the number of those crimes per year
df = df.T
#Now we add the xenophonic crimes per year, using the same transformation we used earlier
#we get the number of those crimes per year using sum and we give the row a name so it has an
#index with an appropiate name
df = df.append(dfxenophobia[range(2014,2018)].sum().rename("Xenophobia"))
#Now we have a valid matrix for chi square. As we have our variables as row and the frequency
#for each different year as columns
print("Our data for our regression:")
print(df)
#We have to get our two variables in different array series. We use loc to get the row whose
#index is the variable we are looking for and we rename it. We have to build it as a numpy array
#so we can use the function reshape with parameters (-1,1) so our array is a 2D array
#This is needed for variable X in a next step
X = np.array(df.loc["lgtbiphobia"].rename("lgtbiphobia"))
X = X.reshape(-1,1)
print("Our variable X: lgtbiphobic crimes:\n{0}".format(X))
#We get our variable Y to check if there is linear correlation. In this case, there is no need
#to transform this series into a numpy array
Y = df.loc["Xenophobia"].rename("Xenophobia")
print("Our variable Y: xenophobic crimes:\n{0}".format(Y))
#We create an object for linear regression using linear_model
regr = linear_model.LinearRegression()
#We use the function fit and the objects that represents our variables X and Y to make our
#object for linear regression to update all variables for linear regression with our data
regr.fit(X,Y)
#We get the correlation coefficient using the first position of the variable coef_ of our object
#for linear regression
coefcorr = regr.coef_[0]
print("Coeficientes: ",coefcorr)
#We evalutate the correlation between our variables
if(coefcorr == 1):
print("There is a perfect positive correlation between our variables")
elif(1 > coefcorr >= 0.7):
print("There is a strong positive correlation between our variables")
elif(0.7 > coefcorr >= 0.5):
print("There is positive correlation between our variables")
elif(0.5 > coefcorr > 0):
print("There is very weak positive correlation between our variables")
elif(coefcorr == 0):
print("There is absolutely no correlation between our variables")
elif(coefcorr == -1):
print("There is a perfect negative correlation between our variables")
elif(-1 < coefcorr <= -0.7):
print("There is a strong negative correlation between our variables")
elif(-0.7 < coefcorr <= -0.5):
print("There is negative correlation between our variables")
elif(-0.5 < coefcorr < 0):
print("There is a very weak negative correlation between our variables")
#Now we use our variable X and the method predict to generate the value for our variable Y
#that this linear model returns as a prediction
Y_pred = regr.predict(X)
print("Y_pred")
print(Y_pred)
#Now we get the parameter R square, which measures the differences between our variable Y
# and the values we predict for this variable Y in our model
rsquare = r2_score(Y, Y_pred)
print("R cuadrado: ",rsquare)
if(rsquare == 1):
print("There is a perfect correlation between our variables")
elif(1 > rsquare >= 0.7):
print("There is a very strong correlation between our variables")
elif(0.7 > rsquare >= 0.5):
print("There is strong correlation between our variables")
elif(0.5 > rsquare > 0.3):
print("There is correlation between our variables")
elif(0.3 >= rsquare > 0):
print("There is very weak correlation between our variables")
elif(rsquare == 0):
print("There is absolutely no correlation between our variables")
#So our variables are likely not independent, but there is a very week negative correlation between
#them
plt.scatter(X, Y, color = "black" )
plt.plot(X,Y_pred,color="Blue")
plt.xlabel("Lgtbiphobic crimes")
plt.ylabel("Xenophobic crimes")
plt.title("Linear Regression Graph")
for i in range(0,len(df.columns)):
plt.annotate(df.columns[i], np.array(df[df.columns[i]]))
plt.show()
|
5ec70d0a90702a14fb71c2b2b523632df1096448 | AntoData/Hate_Crimes_Spain_2014_2017 | /API/GifGenerator.py | 3,959 | 3.75 | 4 | '''
Created on 8 sept. 2019
@author: ingov
'''
#selenium to display the html files in a browser and get screenshots
from selenium import webdriver
#time to set a delay between the opening of the browser and the screenshot
import time
#os to manage folders and path for the html, png and gif files
import os
#imageio to turn a collection of pngs to gif
import imageio
def fromFoliumMaptoGIF(listMaps,pathName,webdriverPath):
"""
Basically, this is a function that given a list of objects of type map from Folium,
will save it as an HTML. Then, we will open these HTML files in a headless browser using Selenium
and save them as images. Finally, we will use these images in a certain order to create
a gif that shows an animation of the evolution of these maps.
@param listMaps: a list of objects of type map from Folium to save as PNG files and turn into
the gif
@param pathName: the path for our files (which includes a basic name for our files but with no extension)
@param webdriverPath: in order to be able to open our browser using selenium we neeed to provide the path for
the webdriver in the parameter webdriverpath
"""
#We create a variable "i" to be used as a counter, this will be part of the name of our files
i = 0
#We create this empty list that will contain the paths where the images taken to the HTML file
#when it was opened using Selenium are
pngFiles = []
print("Applying headless configuration to Chrome webdriver")
#We first generate this object to handle the configuration of our Chrome webdriver
chromeOptions = webdriver.ChromeOptions()
#We set it up to be headless like this
chromeOptions.add_argument("--headless")
#We create a Chrome browser
print("Opening headless Chrome browser")
print(os.getcwd()+"\\"+webdriverPath)
#Now we create our Chrome browser object, we need to provide the full path for our
#webdriver using the parameter of this function called webdriverPath
browser = webdriver.Chrome(executable_path=os.getcwd()+"\\"+webdriverPath,chrome_options=chromeOptions)
#We maximize the window
browser.maximize_window()
#Now for each map in our list of maps in function parameter listMaps
for vMap in listMaps:
print("Processing file number {0} of {1}".format(i+1,len(listMaps)))
#We generate the full path for our HTML file needed to be opened in a browser and take a
#screenshot. We add the value of "i" to the path so we are always creating a new file
#and never overwriting
htmlResult = os.getcwd()+"\\..\\HTML\\"+pathName+"{0}.html".format(i)
#We generate the full path for our PNG file which will contain the screenshot taken to
#the HTML file we open in this iteration using our webdriver. We add the value of "i"
#to the path so we are always creating a new file and never overwriting
pngResult = os.getcwd()+"\\..\\png\\"+pathName+"{0}.png".format(i)
print("Saving HTML file number {0}".format(i))
#We save our map as the HTML file in the path given in htmlResult
vMap.save(htmlResult)
#We open the freshly created html
browser.get("file:///"+htmlResult)
#Give the map tiles some time to load
time.sleep(5)
#We take a screenshot of the browser and save it to a png file
browser.save_screenshot(pngResult)
#We save the file paths to the list pngFiles
pngFiles.append(pngResult)
#We use "i" as a way to order our files
i+=1
#We close the browser
browser.quit()
#images is a list where we will keep the png files opened
images = []
#We go through the screenshot and turn open them with imageio
for filename in pngFiles:
images.append(imageio.imread(filename))
#We turn the images to our gif
imageio.mimsave(os.getcwd()+"\\..\\Results\\"+pathName+".gif", images,fps=0.5) |
82e13fb04e0254eb0812abf6f971d70a4a8e1cef | 918spyderporsche/movie-recommender-system | /insertToMongo.py | 1,518 | 3.78125 | 4 | import sqlite3
def get_all_movies(db_file):
""" create a database connection to a SQLite database """
movies = []
conn = None
try:
conn = sqlite3.connect(db_file)
cur = conn.cursor()
for row in cur.execute("SELECT * FROM Movies"):
print(row)
movies.append(row)
else:
print('Movies is empty')
conn.commit()
conn.close()
return movies
except Error as e:
print(e)
finally:
if conn:
conn.close()
return movies
def outputJson():
movies = get_all_movies(r"/home/spinosaurus/UIUC/CS411/movie_recommender/database.db")
# print(movies)
entries = []
for movie in movies:
entry = {}
id, movie_title, stars, release_year, rating, genres, summary, director = movie
star1, star2 = stars.strip()[1:-1].replace('\'', '').split(',')
star2 = star2[1:]
entry['_id'] = id
entry['movie_title'] = movie_title
entry['stars'] = stars
entry['release_year'] = release_year
entry['rating'] = rating
genres = genres[1:-1].replace('\'', '').split(',')
genres = [elem.strip() for elem in genres]
entry['genres'] = genres
entry['summary'] = summary
entry['director'] = director
entries.append(entry)
print(entry)
print('--------')
# print(entries)
return entries
if __name__ == "__main__":
outputJson()
|
af39c2e32e439c19ed098067f37e467d3fa467ae | antonyshen/sbc-lte-ap | /rootfs/usr/local/bin/shutdown.py | 1,349 | 3.8125 | 4 | #!/usr/bin/python3
# Simple script for shutting down the raspberry Pi at the press of a button.
# by Inderpreet Singh
import RPi.GPIO as GPIO
import time
import os
# Use the Broadcom SOC Pin numbers
SHUTDOWN_PIN = 24
# Setup the Pin with Internal pullups enabled and PIN in reading mode.
GPIO.setmode(GPIO.BCM)
GPIO.setup(SHUTDOWN_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Our function on what to do when the button is pressed
def Shutdown(channel):
time.sleep(0.01) # need to filter out the false positive of some power fluctuation
if GPIO.input(SHUTDOWN_PIN) != GPIO.LOW:
print('quitting event handler because this was probably a false positive')
return
os.system("els81-off")
time.sleep(2) # need to filter out the false positive of some power fluctuation
if GPIO.input(SHUTDOWN_PIN) != GPIO.LOW:
print("Short-press on reset button, reboot system now...")
os.system("sudo sync; sudo sync; sudo sync")
os.system("sudo reboot -h now")
else:
print("Shutdown system now...")
os.system("sudo sync; sudo sync; sudo sync")
os.system("sudo shutdown -h now")
# Add our function to execute when the button pressed event happens
GPIO.add_event_detect(SHUTDOWN_PIN, GPIO.BOTH, callback=Shutdown, bouncetime=150)
# Now wait!
while 1:
time.sleep(86400)
|
abd18b8111328000caf08d5078065b85b79449c5 | WyattOchoa/Data_Sorter | /main.py | 4,308 | 3.75 | 4 | import tkinter as tk
import pandas as pd
def browse():
global user_file
#Global variable for use in functions 1-6
from tkinter.filedialog import askopenfilename
user_file = askopenfilename()
#asks tkinter to open a file that is defined as user_file
browselabel.config(text=user_file)
#updates the topframe browse label with the file path selected by the user
def browsesave():
global save_file
from tkinter import filedialog
save_file = filedialog.asksaveasfilename()
savelabel.config(text=save_file)
def op1():
global user_file
user_file = pd.read_csv(user_file)
user_file = (user_file.sort_values('Name'))
#function 1-6 all use the pandas function of sort_values for data sorting
user_file.to_csv(save_file, index=False)
#functions 1-6 also use pandas to_csv without indexing to save the file in the selected .csv file
def op2():
global user_file
user_file = pd.read_csv(user_file)
user_file = (user_file.sort_values('Name', ascending=False))
#ascending=False to sort in descending order
user_file.to_csv(save_file, index=False)
def op3():
global user_file
user_file = pd.read_csv(user_file)
user_file = (user_file.sort_values('IP'))
user_file.to_csv(save_file, index=False)
def op4():
global user_file
user_file = pd.read_csv(user_file)
user_file = (user_file.sort_values('IP', ascending=False))
user_file.to_csv(save_file, index=False)
def op5():
global user_file
user_file = pd.read_csv(user_file)
user_file = (user_file.sort_values('Date Captured'))
user_file.to_csv(save_file, index=False)
def op6():
global user_file
user_file = pd.read_csv(user_file)
user_file = (user_file.sort_values('Missing Patches'))
user_file.to_csv(save_file, index=False)
root = tk.Tk()
#root window for tkinter
canvas = tk.Canvas(root, height=300, width=500)
canvas.pack()
topframe = tk.Frame(root, bg='#21c2c4')
topframe.place(relx=.01, rely=.01, relwidth=.98, relheight=.15)
#Establishes a frame in root to house other widgets
label = tk.Label(topframe, text="Step 1: Select CSV File for Analysis:", bg="#ceded2" )
label.place(relx=.01, rely=.02, relwidth=.40, relheight=.4)
button = tk.Button(topframe, text="Browse", bg="yellow", command=browse)
#command=browse is used to activate the browse function when clicking the button
button.place(relx=.42, rely=.02, relwidth=.1, relheight=.4)
browselabel = tk.Label(topframe, text='', bg="white")
browselabel.place(relx=.01, rely=.5, relwidth=.98, relheight=.4)
midframe = tk.Frame(root, bg='#21c2c4')
midframe.place(relx=.01, rely=.17, relwidth=.98, relheight=.15)
label = tk.Label(midframe, text="Step 2: Select output location for sorted File:", bg="#ceded2" )
label.place(relx=.01, rely=.02, relwidth=.5, relheight=.4)
button = tk.Button(midframe, text="Browse", bg="yellow", command=browsesave)
button.place(relx=.52, rely=.02, relwidth=.1, relheight=.4)
savelabel = tk.Label(midframe, text="", bg="white" )
savelabel.place(relx=.01, rely=.5, relwidth=.98, relheight=.4)
botframe = tk.Frame(root, bg='#21c2c4')
botframe.place(relx=.01, rely=.33, relwidth=.98, relheight=.66)
label = tk.Label(botframe, text="Step 3: How would you like the data sorted?", bg="#ceded2" )
label.place(relx=.01, rely=.02, relwidth=.50, relheight=.1)
button = tk.Button(botframe, text="Alphabetized", bg="pink", command=op1)
button.place(relx=.01, rely=.2, relwidth=.3, relheight=.25)
button = tk.Button(botframe, text="IPs", bg="pink", command=op3)
button.place(relx=.35, rely=.2, relwidth=.3, relheight=.25)
button = tk.Button(botframe, text="Date Captured", bg="pink", command=op5)
button.place(relx=.69, rely=.2, relwidth=.3, relheight=.25)
button = tk.Button(botframe, text="Alphabetized Desc.", bg="pink", command=op2)
button.place(relx=.01, rely=.6, relwidth=.3, relheight=.25)
button = tk.Button(botframe, text="IPs Desc.", bg="pink", command=op4)
button.place(relx=.35, rely=.6, relwidth=.3, relheight=.25)
button = tk.Button(botframe, text="Missing Patches", bg="pink", command=op6)
button.place(relx=.69, rely=.6, relwidth=.3, relheight=.25)
root.mainloop()
#end of the root tkinter window |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.