blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
028026f8713a6648910c355f1901106b37a84cc3
lbd1607/goingGreen2
/goingGreen2.py
3,278
4.15625
4
#Laura Davis #1 May 2016 #This program will calculate the energy difference after of going green by #comparing energy bills from the year prior to making the switch and the year #following the switch. It will aggregate two years' worth of data and #compute the savings. The data will be saved in file savings.txt and #data can be imported from that file. #CGP145 Ch10 Lab-4 Going Green def main(): #declare variables endProgram = "no" months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] option = 0 while endProgram == "no": print "1 - Load data to file" print "2 - Load data from file" option = input("Select your option --> ") #function calls if option == 1: notGreenCost = getNotGreen(months) goneGreenCost = getGoneGreen(months) savings = energySaved(notGreenCost, goneGreenCost) writeToFile(savings, notGreenCost, goneGreenCost) else: savings, notGreenCost, goneGreenCost = readFromfile() displayInfo(notGreenCost, goneGreenCost, savings, months) endProgram = raw_input('Do you want to end program? (Enter no or yes) --> ') #the writeToFile function def writeToFile(savings, notGreenCost, goneGreenCost): outFile = open('savings.txt', 'w') print >> outFile, 'Savings' counter = 0 while counter < 12: outFile.write(str(savings[counter]) + '\n') outFile.write(str(notGreenCost[counter]) + '\n') outFile.write(str(goneGreenCost[counter]) + '\n') counter = counter + 1 outFile.close() #the readFromfile function def readFromfile(): notGreenCost = [0] * 12 goneGreenCost = [0] * 12 savings = [0] * 12 inFile = open('savings.txt', 'r') str1 = inFile.readline() lstr = len(str1) str1 = str1[0:lstr-1] print str1 counter = 0 while counter < 12: str3 = inFile.readline() lstr = len(str3) savings[counter] = str3[0:lstr-1] str4 = inFile.readline() lstr = len(str4) notGreenCost[counter] = str4[0:lstr-1] str5 = inFile.readline() lstr = len(str5) goneGreenCost[counter] = str5[0:lstr-1] counter = counter + 1 inFile.close() return savings, notGreenCost, goneGreenCost #the getNotGreen function def getNotGreen(months): notGreenCost = [0] * 12 counter = 0 while counter < 12: notGreenCost[counter] = input('Enter NOT GREEN energy costs for ' + months[counter] +' --> ') counter = counter + 1 return notGreenCost #the getGoneGreen function def getGoneGreen(months): goneGreenCost = [0] * 12 counter = 0 while counter < 12: goneGreenCost[counter] = input('Enter GONE GREEN energy costs for ' + months[counter] +' --> ') counter = counter + 1 return goneGreenCost #the energySaved function def energySaved(notGreenCost, goneGreenCost): savings = [0] * 12 counter = 0 while counter < 12: savings[counter] = notGreenCost[counter] - goneGreenCost[counter] counter = counter + 1 return savings #the displayInfo function def displayInfo(notGreenCost, goneGreenCost, savings, months): counter = 0 while counter < 12: print "Information for " + months[counter] print "\t Savings \t\t$" + str(savings[counter]) print "\t Not Green Costs \t$" + str(notGreenCost[counter]) print "\t Gone Green Costs \t$" + str(goneGreenCost[counter]) counter = counter + 1 #calls main main()
7502a34ab41ad79cb009927fb08c32986cc6deed
omuga/INF-349-Programacion-Competitiva
/Codeforces/579A - Raising Bacteria.py
269
3.53125
4
import math __author__ = 'Obriel Muga' def raising_bacteria(x): binario = '{0:b}'.format(x) num = 0 for i in binario: if i == '1': num = num + 1 return num if __name__ == "__main__": x = int(input()) print(raising_bacteria(x))
1b8d5ac4015043828db9de4149cf8436ea2dc710
anshul0412/python-openCv
/chapter4.py
410
3.671875
4
import cv2 import numpy as np #draw shaped and to put text on images #first we will create a matrix filled with 0{black} img= np.zeros((512,512,3),np.uint8) #print(img) #img[:]= 0,0,0 cv2.line(img,(0,0),(300,300),(0,0,255),5) cv2.circle(img,(300,300),50,(255,0,255),10) #text on images cv2.putText(img,"openCV",(300,300),cv2.FONT_HERSHEY_COMPLEX,0.5,(255,200,20),1) cv2.imshow("img",img) cv2.waitKey(0)
3d163a491a3b9a6e5a0d9b486e03eae055e72366
PengZhang2018/LeetCode
/algorithms/python/DiameterOfBinaryTree/DiameterOfBinaryTree.py
994
3.84375
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 diameterOfBinaryTree(self, root: TreeNode) -> int: self.result = 0 def dfs(node: TreeNode): if not node: return 0 L = dfs(node.left) R = dfs(node.right) self.result = max(self.result, L+R) return max(L, R) + 1 dfs(root) return self.result ######## # Test # ######## # 1 # / \ # 2 3 # / \ # 4 5 # / \ \ # 6 7 8 root = TreeNode(1) node1 = TreeNode(2) node2 = TreeNode(3) node3 = TreeNode(4) node4 = TreeNode(5) node5 = TreeNode(6) node6 = TreeNode(7) node7 = TreeNode(8) root.left = node1 root.right = node2 node1.left = node3 node1.right = node4 node3.left = node5 node3.right = node6 node4.right = node7 assert Solution().diameterOfBinaryTree(root) == 4 print("OH, YEAH!")
cedd1379bb5e1f1ce488aa020930d1b8aa1e15d9
Seinu/MIT-6.00-OCW
/Problem-Set-2/ps2_hangman.py
2,480
4.125
4
# 6.00 Problem Set 3 # # Hangman # # ----------------------------------- # Helper code # (you don't need to understand this helper code) import random import string WORDLIST_FILENAME = "words.txt" def load_words(): """ Returns a list of valid words. Words are strings of lowercase letters. Depending on the size of the word list, this function may take a while to finish. """ print "Loading word list from file..." # inFile: file inFile = open(WORDLIST_FILENAME, 'r', 0) # line: string line = inFile.readline() # wordlist: list of strings wordlist = string.split(line) print " ", len(wordlist), "words loaded." return wordlist def choose_word(wordlist): """ wordlist (list): list of words (strings) Returns a word from wordlist at random """ return random.choice(wordlist) def concatenateWord(word): c = '' for i in range(0, len(word)): c = c + word[i] return c # end of helper code # ----------------------------------- # actually load the dictionary of words and point to it with # the wordlist variable so that it can be accessed from anywhere # in the program wordlist = load_words() word = choose_word(wordlist) # your code begins here! abc = 'abcdefghijklmnopqrstuvwyxz' print 'Welcome to the game, Hangman!' print 'I am thinking of a word that is', len(word), 'letters long.' print '-------------' wordGuessed = [] strWordGuessed = '' for i in range(0, len(word)): wordGuessed.append('_ ') print concatenateWord(wordGuessed) print strWordGuessed count = 0 maxGuess = int(len(word) * 1.5) while count < maxGuess: print 'You have', maxGuess - count, 'guesses left.' print 'available letters: ', abc letterGuessed = raw_input('Please guess a letter: ') inWord = False if letterGuessed not in abc: print 'This letter has already been guessed!', strWordGuessed else: for x, l in enumerate(word): if l == letterGuessed: wordGuessed[x] = l strWordGuessed = concatenateWord(wordGuessed) inWord = True if inWord == True: print 'Good guess:', strWordGuessed else: count += 1 print 'Oops! That letter is not in my word:', strWordGuessed abc = abc.replace(letterGuessed, '') print '-------------' if strWordGuessed == word: print 'Congratulations, you won!' break
91e1b3a828db781c99832a91c3d1fc767aa627ab
gyanmittal/regression
/naive_word2vec_skipgram.py
6,335
3.53125
4
''' Author: Gyan Mittal Corresponding Document: https://gyan-mittal.com/nlp-ai-ml/nlp-word2vec-skipgram-neural-network-iteration-based-methods-word-embeddings Brief about word2vec: A team of Google researchers lead by Tomas Mikolov developed, patented, and published Word2vec in two publications in 2013. For learning word embeddings from raw text, Word2Vec is a computationally efficient predictive model. Word2Vec methodology is used to calculate Word Embedding based on Neural Network/ iterative. Word2Vec methodology have two model architectures: the Continuous Bag-of-Words (CBOW) model and the Skip-Gram model. About Code: This code demonstrates the basic concept of calculating the word embeddings using word2vec methodology using Skip-Gram model. ''' from collections import Counter import itertools import numpy as np import re import matplotlib.pyplot as plt from util import * # Clean the text after converting it to lower case def naive_clean_text(text): text = text.strip().lower() #Convert to lower case text = re.sub(r"[^A-Za-z0-9]", " ", text) #replace all the characters with space except mentioned here return text def prepare_training_data(corpus_sentences): window_size = 1 split_corpus_sentences_words = [naive_clean_text(sentence).split() for sentence in corpus_sentences] center_word_train_X = [] #context_words_train_y = [] context_words_train_one_hot_vector_y = [] word_counts = Counter(itertools.chain(*split_corpus_sentences_words)) vocab_word_index = {x: i for i, x in enumerate(word_counts)} reverse_vocab_word_index = {value: key for key, value in vocab_word_index.items()} vocab_size = len(vocab_word_index) for sentence in split_corpus_sentences_words: for i in range(len(sentence)): center_word = [0 for x in range(vocab_size)] center_word[vocab_word_index[sentence[i]]] = 1 #context = [0 for x in range(vocab_size)] for j in range(i - window_size, i + window_size+1): context = [0 for x in range(vocab_size)] if i != j and j >= 0 and j < len(sentence): context[vocab_word_index[sentence[j]]] = 1 center_word_train_X.append(center_word) #context_words_train_y.append(vocab_word_index[sentence[j]]) context_words_train_one_hot_vector_y.append(context) return np.array(center_word_train_X), np.array(context_words_train_one_hot_vector_y), vocab_word_index def initiate_weights(input_size, hidden_layer_size, output_size): np.random.seed(100) W1 = np.random.randn(input_size, hidden_layer_size) W2 = np.random.randn(hidden_layer_size, output_size) return W1, W2 def predict(X, W1, W2): Z1 = X.dot(W1) Z2 = Z1.dot(W2) y_pred = naive_softmax(Z2) y_pred = np.array(np.argmax(y_pred, axis=1)) return y_pred def back_propagation(train_X, train_y_one_hot_vector, yhat, Z1, W1, W2, learning_rate): #dl_dyhat = np.divide(train_y_one_hot_vector, pred_train_y) dl_dz2 = yhat - train_y_one_hot_vector dl_dw2 = Z1.T.dot(dl_dz2) dl_dz1 = dl_dz2.dot(W2.T) dl_dw1 = train_X.T.dot(dl_dz1) # update the weights W1 -= learning_rate * dl_dw1 W2 -= learning_rate * dl_dw2 return W1, W2 def forward_propagation(train_X, W1, W2): Z1 = train_X.dot(W1) Z2 = Z1.dot(W2) yhat = naive_softmax(Z2) return Z1, yhat def plot_embeddings_and_loss(W, vocab_word_index, loss_log, epoch, max_loss, img_files=[]): fig, (ax1, ax2) = plt.subplots(1, 2, sharex=False, figsize=(10, 5)) ax1.set_title('Word Embeddings in 2-d space for the given example') plt.setp(ax1, xlabel='Embedding dimension - 1', ylabel='Embedding dimension - 2') #ax1.set_xlim([min(W[:, 0]) - 1, max(W[:, 0]) + 1]) #ax1.set_ylim([min(W[:, 1]) - 1, max(W[:, 1]) + 1]) ax1.set_xlim([-3, 3.5]) ax1.set_ylim([-3.5, 3]) for word, i in vocab_word_index.items(): x_coord = W[i][0] y_coord = W[i][1] #print(word, ":\t[", x_coord, ",", y_coord, "]") ax1.plot(x_coord, y_coord, "cD", markersize=5) #ax1.text(word, (x_coord, y_coord)) ax1.text(x_coord, y_coord, word, fontsize=10) ax2.set_title("Loss graph") plt.setp(ax2, xlabel='#Epochs (Log scale)', ylabel='Loss') ax2.set_xlim([1 , epoch * 1.1]) ax2.set_xscale('log') ax2.set_ylim([0, max_loss * 1.1]) if(len(loss_log) > 0): ax2.plot(1, max(loss_log), "bD") ax2.plot(loss_log, "b") ax2.set_title("Loss is " + r"$\bf{" + str("{:.6f}".format(loss_log[-1])) + "}$" + " after " + r"$\bf{" + str(f'{len(loss_log) - 1:,}') + "}$" + " epochs") directory = "images" if not os.path.exists(directory): os.makedirs(directory) filename = f'images/{len(loss_log)}.png' for i in range(13): img_files.append(filename) # save frame plt.savefig(filename) plt.close() return img_files corpus_sentences = ["I love playing Football", "I love playing Cricket", "I love playing sports"] train_X, train_y_one_hot_vector, vocab_word_index = prepare_training_data(corpus_sentences) # Network with one hidden layer input_size = len(train_X[0]) # Number of input features hidden_layer_size = 2 # Design choice [Embedding Dimension] output_size = len(vocab_word_index) # Number of classes W1, W2 = initiate_weights(input_size, hidden_layer_size, output_size) epoch = 200000 learning_rate = 0.0001 loss_log =[] saved_epoch_no = 0 for epoch_no in range(epoch): loss = 0 Z1, yhat = forward_propagation(train_X, W1, W2) loss = cross_entropy_loss(train_y_one_hot_vector, yhat) if (epoch_no==0): image_files = plot_embeddings_and_loss(W1, vocab_word_index, loss_log, epoch, loss) loss_log.append(loss) loss_log.append(loss) W1, W2= back_propagation(train_X, train_y_one_hot_vector, yhat, Z1, W1, W2, learning_rate) if ((epoch_no == 1) or np.ceil(np.log10(epoch_no + 2)) > saved_epoch_no or (epoch_no + 1) == epoch): print("epoch_no: ", (epoch_no + 1), "\tloss_log:", loss) image_files = plot_embeddings_and_loss(W1, vocab_word_index, loss_log, epoch, max(loss_log), image_files) saved_epoch_no = np.ceil(np.log10(epoch_no + 2)) create_gif(image_files, 'images/word2vec_skipgram.gif')
524c6be0c5e02796ab23b923801a444e726923e4
dominichipwood/euler_project
/30.py
244
3.546875
4
def s5pd(n): #sum of 5th powers of digits digits=[int(t) for t in list(str(n))] return sum(d**5 for d in digits) nums=[] n=2 for n in range(2,1000000): if s5pd(n)==n: nums.append(n) print(nums) print(sum(nums))
8b1152515efff7f1bd5b96aa24528537d58eb9ec
itamar141456/card_proj_with_roei
/test_Card_Game.py
2,413
3.765625
4
from unittest import TestCase from Card_Game import CardGame from player_class import Player from Card_class import Card class TestCardGame(TestCase): def setUp(self): Player1 = Player('roie') Player2 = Player('itamar') self.game1 = CardGame(Player1, Player2, 5) def test_build(self): """ check that tha game is built properly """ self.assertTrue(self.game1.player1.name == 'roie') self.assertTrue(self.game1.player2.name == 'itamar') self.assertTrue(len(self.game1.player1.hand) == 5) self.assertTrue(len(self.game1.player2.hand) == 5) self.assertTrue(len(self.game1.game_deck.cards_list) == 42) for card in self.game1.player1.hand: self.assertNotIn(card, self.game1.player2.hand) def test__new_game(self): """ make shore __new_game doesnt change a thing when called a second time """ self.game1._CardGame__new_game(Player('yoni'), Player('kobi'), 10) self.assertEqual(len(self.game1.player1.hand), 5) self.assertEqual(len(self.game1.player2.hand), 5) self.assertEqual(self.game1.player1.name, 'roie') self.assertEqual(self.game1.player2.name, 'itamar') def test_get_winner_win(self): """ check that the correct player won the game """ self.game1.player1.hand = [Card({"Harts": 3}, 3), Card({"Spades": 2}, 8), Card({"Clubs": 4}, 11)] self.game1.player2.hand = [Card({"Harts": 3}, 5)] self.assertEqual(self.game1.get_winner(), self.game1.player2) def test_get_winner_tie(self): """ checks that when the players tied None will be returned """ self.game1.player1.hand = [Card({"Harts": 3}, 3), Card({"Spades": 2}, 8)] self.game1.player2.hand = [Card({"Harts": 3}, 5), Card({"Clubs": 4}, 11)] self.assertEqual(self.game1.get_winner(), None) def test_get_winner_no_cards(self): """ what happends when the players have no cards or just one player have no cards """ self.game1.player1.hand = [] self.game1.player2.hand = [] self.assertEqual(self.game1.get_winner(), None) self.game1.player2.hand = [Card({"Harts": 3}, 5)] self.assertEqual(self.game1.get_winner(), self.game1.player1)
dd046c13b9c5fa5c8662310764520de556b0ec87
daniel-reich/turbo-robot
/39utPCHvtWqt5vaz9_18.py
2,095
4.34375
4
""" You will be given a list of string `"east"` formatted differently every time. Create a function that returns `"west"` wherever there is `"east"`. Format the string according to the input. Check the examples below to better understand the question. ### Examples direction(["east", "EAST", "eastEAST"]) ➞ ["west", "WEST", "westWEST"] direction(["eAsT EaSt", "EaSt eAsT"]) ➞ ["wEsT WeSt", "WeSt wEsT"] direction(["east EAST", "e a s t", "E A S T"]) ➞ ["west WEST", "w e s t", "W E S T"] ### Notes The input will only be `"east"` in different formats. """ def direction(lst): Revised = [] Counter = 0 Length = len(lst) while (Counter < Length): Sample = lst[Counter] Tweaked = "" Previous = "X" Cursor = 0 Span = len(Sample) while (Cursor < Span): Item = Sample[Cursor] if (Previous == "X") and (Item == "E"): Tweaked = Tweaked + "W" Previous = "E" Cursor += 1 elif (Previous == "X") and (Item == "e"): Tweaked = Tweaked + "w" Previous = "E" Cursor += 1 elif (Previous == "E") and (Item == "a"): Tweaked = Tweaked + "e" Previous = "A" Cursor += 1 elif (Previous == "E") and (Item == "A"): Tweaked = Tweaked + "E" Previous = "A" Cursor += 1 elif (Previous == "A") and (Item == "s"): Tweaked = Tweaked + "s" Previous = "S" Cursor += 1 elif (Previous == "A") and (Item == "S"): Tweaked = Tweaked + "S" Previous = "S" Cursor += 1 elif (Previous == "S") and (Item == "t"): Tweaked = Tweaked + "t" Previous = "X" Cursor += 1 elif (Previous == "S") and (Item == "T"): Tweaked = Tweaked + "T" Previous = "X" Cursor += 1 elif (Item == " "): Tweaked = Tweaked + Item Cursor += 1 else: return "Error!" Revised.append(Tweaked) Counter +=1 return Revised
d237c9652b2f01632a8b88805011fb87c9144419
tkobayas/deeplearningfromscratch
/hamegg/list/sort.py
92
3.796875
4
list = ["B", "X", "F", "G", "C"] list.sort() print (list) list.reverse() print (list)
35b39d0a32b2bf635e8d93e9e4ef2d5091fc5bfb
meihei3/SortCollections
/sortCollections/bogo_sort.py
452
3.671875
4
import random from typing import List def bogo_sort(ary: List[float]): def is_sorted(ls: List[float]): for _p, _next in zip(ls[:-1], ls[1:]): if _p > _next: return False return True while not is_sorted(ary): random.shuffle(ary) return ary if __name__ == '__main__': test_array = [random.randint(0, 10) for i in range(10)] print(test_array) print(bogo_sort(test_array))
90220d82506c3bade29d18489c5be1786098438d
felipeandrademorais/Python
/Basico/Funcoes_python.py
1,489
3.75
4
#Função com Parâmetros Default def login(usuario="root", senha="123"): print("Usuario: ", usuario) print("Senha: ", senha) login("Felipe","FeLi2705")#A passagem de argumentos é opcional #Função com argumentos posicionais e nomeados def dados_pessoais(nome, sobrenome, idade, sexo): print("Nome: {}\nSobrenome: {}\nIdade: {}\nSexo: {}" .format(nome, sobrenome, idade, sexo)) dados_pessoais("Felipe","Andrade",24, True) dados_pessoais(nome="Claudio", sobrenome="Carvalho", idade=30, sexo=True) #Funções Variáticas def lista_de_argumentos(*lista): print(lista) def lista_de_argumentos_associativos(**dicionario): print(dicionario) def argumentos(*args, **kwargs): print(args) print(kwargs) lista_de_argumentos(1,2,3,4,5,6) lista_de_argumentos("Um","Dois","Tres","Quatro") lista_de_argumentos_associativos(a=1, b=2, c=3, d=4) lista_de_argumentos_associativos(um=1, dois=2, tres=3, quatro=4) #Desempacotamento de listas def pessoa(nome, sobrenome, idade): print(nome) print(sobrenome) print(idade) tupla = "Felipe", "Andrade", 24 lista = ["Felipe","Andrade",24] dicionario = {"nome":"Felipe","sobrenome":"Andrade", "idade":24} pessoa(*tupla) pessoa(*lista) pessoa(**dicionario) #Exemplo Desempacotamento lista = [11,10,12] tupla = 11,10,12 def func(a,b,c): print(a) print(b) print(c) lista.sort()#Ordena uma lista func(*lista) l = [*tupla]#joga uma tupla dentro de uma lista l.sort() func(*l)
785e73f4cb8a1c6a2691f7a9c475362d5f9fff48
nicoirm/AI_Car_Raspberry-pi
/Self-driving trolley based on ANN/sigmoid.py
330
3.921875
4
#!/usr/bin/env python """Sigmoid Function""" from numpy import power, e def sigmoid(x_value): """Return the sigmoid value""" return 1.0/(1.0 + power(e, -x_value)) ''' from matplotlib import pyplot as plt import numpy as np for x in range(-100,100,2): y = 1.0/(1 + np.power(np.e, -x)) plt.plot(x,y,'sigmoid') '''
055f8f2a2563c17a1afa964bb5ba21cc0d77fe57
cdavid719/investor
/mainlog.py
539
3.640625
4
from data import Username, Password from user import User import functionslog as function user = User() user.fname = input("Enter your first name >> ") user.lname = input("Enter your last name >> ") user.username = input("Enter your last username >> ") function.actions(user.fname, user.lname, "username") user.password = input("Enter your password >> ") function.actions(user.fname, user.lne, "") if(user.username == Username and user.password == Password): print("User has been authenticated") else: print("Wrong credentials")
77a644dc456306da7d70ffec757ca7f4783b4043
hyprr/pruthvi-IT
/lab7.py
236
4.15625
4
a=int(input("enter the value of a")) b=int(input("entre the value of b")) c=int(input("enter the value of c")) if a>b and a>c: print("a is greater than b") elif b>c: print("b is greater than c") else: print("c is greater than b")
3d881dd453548d8c80c04e5b10d8e7033dbb1f5d
AnjaliG1999/DSA
/Arrays/frequency.py
526
4.0625
4
dict = {} def findFrequency(arr): global dict for key in arr: dict[key] = [dict.get(key, 0) + 1] def frequency1(arr, val): findFrequency(arr) return dict[val] if val in dict else 0 def frequency2(arr, val): count = 0 for key in arr: if key == val: count += 1 return count arr = [1, 3, 5, 3, 6, 7, 1, 0, 3] val = int(input('Enter value to count: ')) # freq = frequency1(arr, val) freq = frequency2(arr, val) print("No. of {}'s in array: {}".format(val, freq))
1799e33a7277f0341e1e5cd2eca5fab027fe4e9b
chawasitCPECMU/Software-Engineering
/CPU-Scheduling-Algorithm/dataset.py
836
3.703125
4
from numpy.random import uniform, shuffle def generate(n=60, distributions=None): """Return a generated list of number by given list of range and distribution tuple eg. spec = [(2, 8, 0.7), (20, 30, 0.2), (35, 40, 0.1)] """ if distributions is None: distributions = [(2, 8, 0.7), (20, 30, 0.2), (35, 40, 0.1)] if n <= 0: raise Exception("n must greater than 0") if sum(map(lambda x: x[2], distributions)) - 1.0 > 1e-7: raise Exception("summation of probability must equal to 1") ret = [] for distribution in distributions: size = int(distribution[2] * n) ret.extend(map(int, uniform(distribution[0], distribution[1], size))) shuffle(ret) return ret if __name__ == '__main__': numbers = generate() print numbers print len(numbers)
597f0ddfb06bd60f19d0bf418e810aad68630224
p-koo/libre
/libre/model_zoo/cnn_local.py
2,603
4.125
4
from tensorflow import keras def model( input_shape, output_shape, activation="relu", units=[24, 48, 96], pool_size=[25, 4], dropout=[0.1, 0.2, 0.5], ): """Creates a keras neural network with the architecture shown below. The architecture is chosen to promote learning in the first layer. Parameters ---------- input_shape: tuple Tuple of size (L,4) where L is the sequence lenght and 4 is the number of 1-hot channels. Assumes all sequences have equal length. output_shape: int Number of output categories. activation: str A string specifying the type of activation. Example: 'relu', 'exponential', ... units: list Optional parameter. A list of 3 integers that can be used to specify the number of filters. It provide more external control of the architecture. dropout: list Optional parameter. A list of 3 probabilities [prob, prob,prob] that can be used to externally control the probabilities of dropouts in the main architecture. Returns ------- Keras Functional Model instance. Example ------- >>> model = cnn_local_model( (200,4), 1 , 'relu', [24, 48, 96], [0.1, 0.2, 0.5] ) """ # input layer inputs = keras.layers.Input(shape=input_shape) # layer 1 nn = keras.layers.Conv1D( filters=units[0], kernel_size=19, padding="same", activation=activation, kernel_regularizer=keras.regularizers.l2(1e-6), )(inputs) nn = keras.layers.BatchNormalization()(nn) nn = keras.layers.Dropout(dropout[0])(nn) nn = keras.layers.MaxPool1D(pool_size=pool_size[0])(nn) # layer 2 nn = keras.layers.Conv1D( filters=units[1], kernel_size=7, padding="same", activation="relu", kernel_regularizer=keras.regularizers.l2(1e-6), )(nn) nn = keras.layers.BatchNormalization()(nn) nn = keras.layers.Dropout(dropout[1])(nn) nn = keras.layers.MaxPool1D(pool_size=pool_size[1])(nn) # layer 3 nn = keras.layers.Flatten()(nn) nn = keras.layers.Dense( units=units[2], activation="relu", kernel_regularizer=keras.regularizers.l2(1e-6), )(nn) nn = keras.layers.BatchNormalization()(nn) nn = keras.layers.Dropout(dropout[2])(nn) # Output layer logits = keras.layers.Dense(output_shape, activation=None, use_bias=True)(nn) outputs = keras.layers.Activation("sigmoid")(logits) # compile model model = keras.Model(inputs=inputs, outputs=outputs) return model
5b44db030c4a35e7e1e914f3f59602f1c4334849
vasilchenkos/stepik-python-basics
/2.4/cytozin.py
453
3.828125
4
"""Вывести количество элементов в строке по введенному символу""" genome = input("Введите строку: ") cnt = 0 for nucle in genome: if nucle == "c": cnt+=1 print(cnt) """Вывести количество элементов в строке по введенному символу без цикла""" genome = input("Введите строку: ") print(genome.count("c"))
acafe633abcaa583cf6a48694a00281818ee4c34
MarineChap/Machine_Learning
/Clustering/Section 24 - K-Means Clustering/K_means.py
2,391
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Part 3 : K-means cluster in following the course "Machine learning A-Z" at Udemy The dataset can be found here https://www.superdatascience.com/machine-learning/ Subject : Mall want segments his clients in function of the Age, Annual Income (k$) and Spending Score (1-100) but it has no idea about the number or the kind of category. Result can be seen here : https://plot.ly/~marine_chap/12 pro : - easy to understand, fast and available in lot of tools con : - Important problematics with the centroid initialization Created on Wed Feb 28 17:22:19 2018 @author: marinechap """ # Import libraries import pandas as pd from sklearn.cluster import KMeans import plotly.plotly as py import matplotlib.pyplot as plt import display_graph_online as dgo import matplotlib.colors as cl # Parameters name_file = 'Mall_Customers.csv' nb_indep_var = 4 # Import dataset dataset = pd.read_csv(name_file) indep_var = dataset.iloc[:,2:5].values """ Elbow method for the K-means cluster """ wcss = [] for i in range(1,11): cluster = KMeans(n_clusters = i, init = 'k-means++') cluster.fit(indep_var) wcss.append(cluster.inertia_) plt.figure() plt.plot(range(1,11), wcss, color = 'r') plt.title('WCSS result in function of the number of clusters') plt.xlabel('number of clusters') plt.ylabel('WCSS') plt.savefig('WCSS.png', bbox_inches='tight') plt.show() nb_cluster = 3 cluster = KMeans(n_clusters = nb_cluster, init = 'k-means++') k_mean = cluster.fit_predict(indep_var) centroid = cluster.cluster_centers_ """ Display results """ data, layout = dgo.display_graph(indep_var, nb_cluster, k_mean, 'K-means clustering') colorNames = list(cl._colors_full_map.values()) for cluster_index in range(0, nb_cluster): centroid_data = dict( mode = "markers", name = "centroid {0}".format(cluster_index), type = "scatter3d", marker = dict( size = 10, color = colorNames[cluster_index], ), x = centroid[cluster_index, 0], y = centroid[cluster_index, 1], z = centroid[cluster_index, 2] ) data.append(centroid_data) fig = dict( data = data, layout = layout ) py.plot(fig, filename= 'Hierachical clustering')
6d9beee211571c771d5359d7f3f1e71a6565efdf
rymo90/kattis
/eligibility.py
456
3.5
4
n = int(input()) for _ in range(n): data = input().split() name= data[0] temp= data[1] postSecondStudieYear = temp[0:4] temp2= data[2] bithYear= temp2[0:4] course= data[3] if int(postSecondStudieYear) >= 2010 or int(bithYear) >= 1991: print(name+" "+"eligible") else: if int(course) > 40: print(name+" "+"ineligible") else: print(name+" "+"coach petitions")
6e08cd0ea3a664a95c3bfe9a5e457d12dcf9f50f
phpons/mutation-testing-calculator
/src/calculator.py
490
3.65625
4
def is_number(a): return isinstance(a, (int, float)) def validate_input(a, b): if not is_number(a) or not is_number(b): raise ValueError("Input values must be numbers.") def sum(a, b): validate_input(a, b) return a + b def subtract(a, b): validate_input(a, b) return a - b def mult(a, b): validate_input(a, b) return a * b def div(a, b): validate_input(a, b) if b == 0: raise ValueError("Can\'t divide by zero.") return a/b
fb1efc6afd4f77901699f5ebb894f7eeb4530f5c
vinitony12/calc
/add.py
112
3.671875
4
x = eval(input('Enter the first no:')) y = eval(input('Enter the second no:')) z = x - y print('The diff is',z)
58ae65d067f889d967d6270a31063a935959e995
marekbojko/stochastic-processes
/discrete/utils.py
1,357
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Oct 20 11:56:26 2019 @author: Marek """ import numpy as np import itertools class Checks(object): """Mix-in class containing input value checking functions.""" def _check_increments(self, n): if not isinstance(n, int): raise TypeError("Number of increments must be an integer.") if n <= 0: raise ValueError("Number of increments must be positive.") def _check_number(self, value, name): if not isinstance(value, (int, float)): raise TypeError(name + " value must be a number.") def _check_positive_number(self, value, name): self._check_number(value, name) if value <= 0: raise ValueError(name + " value must be positive.") def _check_nonnegative_number(self, value, name): self._check_number(value, name) if value < 0: raise ValueError(name + " value must be nonnegative.") def _check_zero(self, zero): if not isinstance(zero, bool): raise TypeError("Zero inclusion flag must be a boolean.") def concat_arrays(l): """Concatenate a list of numpy arrays""" pol = [] [pol.append(list(j)) for j in l] pol = list(itertools.chain.from_iterable(pol)) return np.array(pol)
297d05baf8a2fc57dbb1c45881c0982f8970d600
NimishVerma/PyDSALGO
/findWaysToClimb.py
668
4.21875
4
""" This problem was asked by Amazon. There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters. For example, if N is 4, then there are 5 unique ways: 1, 1, 1, 1 2, 1, 1 1, 2, 1 1, 1, 2 2, 2 """ def findSteps(N, ways=[1,2]): if N == 0 or N==1: return 1 else: return findSteps(N-1) + findSteps(N-2) def DP_findSteps(N): nums = [0]*(N+1) nums[0] = 1 nums[1] = 1 for i in range(2,N+1): nums[i] = nums[i-1]+nums[i-2] return nums[N] print(DP_findSteps(4))
08e941e2a4d0e596e7154c5f43bdffc758941eda
johan-bh/Pygame-Game
/scoreboard.py
2,597
3.53125
4
import pygame.font from pygame.sprite import Group from ship import Ship class Scoreboard(): """A class to keep track of scores.""" def __init__(self,ai_settings,screen,stats): self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats #Font settings and score info self.text_color = (30,30,30) self.font = pygame.font.SysFont(None,35) #Prepare the initial score and level images self.prep_score() self.prep_ships() self.prep_high_score() self.prep_level() def prep_score(self): """Turn the initial score into a rendered image.""" rounded_score = int(round(self.stats.score,-1)) score_string = "Score: " + "{:}".format(rounded_score) self.score_image = self.font.render(score_string, True, self.text_color, self.ai_settings.bg_color) #Display the score at the top right corner of the screen. self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = self.screen_rect.top = 20 def prep_high_score(self): """Turn the high score into a rendered image.""" high_score = int(round(self.stats.high_score, -1)) high_score_string = "High Score: " + "{:}".format(high_score) self.high_score_image = self.font.render(high_score_string, True, self.text_color, self.ai_settings.bg_color) #Display the score at the top of the screen. self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = self.screen_rect.top def prep_level(self): """Turn the current level into a rendered image.""" self.level_image = self.font.render("Level: " + str(self.stats.level), True, self.text_color,self.ai_settings.bg_color) #Display the score 10 pixels below the scoreboard. self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): """"Turn the current amount of ships into a rendered image.""" self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_settings, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship) def show_score(self): """Blit the score, high score and level to the screen.""" self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, self.high_score_rect) self.screen.blit(self.level_image, self.level_rect) #Draw the ships to the screen. self.ships.draw(self.screen)
b7a1f37b71ccff294540c87e749e59601549ebe6
eazow/leetcode
/79_word_search.py
1,247
3.6875
4
# -*- coding:utf-8 -*- class Solution(object): def exist(self, board, word): """ :param board: List[List[str]] :param word: str :return: bool """ if board is None or len(board) == 0 or len(board[0]) == 0: return word is None or word == "" for i in xrange(len(board)): for j in xrange(len(board[0])): if self.dfs(board, i, j, word): return True return False def dfs(self, board, row, col, word): if len(word) == 0: return True if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or board[row][col] != word[0]: return False board[row][col] = "#" result = self.dfs(board, row+1, col, word[1:]) or \ self.dfs(board, row-1, col, word[1:]) or \ self.dfs(board, row, col-1, word[1:]) or \ self.dfs(board, row, col + 1, word[1:]) board[row][col] = word[0] return result board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] assert Solution().exist(board, "ABCCED") == True assert Solution().exist(board, "SEE") == True assert Solution().exist(board, "ABCB") == False
701dfbd03f54e73557b33def4183a44666826ed8
wxx17395/Leetcode
/python code/剑指offer/39. 数组中出现次数超过一半的数字.py
1,003
3.765625
4
""" 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 你可以假设数组是非空的,并且给定的数组总是存在多数元素。 示例 1: 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 输出: 2 限制: 1 <= 数组长度 <= 50000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: def majorityElement(self, nums: list) -> int: n = len(nums) if n == 1: return nums[0] cur, count = nums[0], 1 for i in range(1, n): if nums[i] == cur: count += 1 else: count -= 1 if count == 0: cur = nums[i] count = 1 return cur if __name__ == '__main__': print(Solution().majorityElement([1, 2, 2, 3]))
a44e157902000894cdd2e36be5548d6f4c23d609
phibzy/InterviewQPractice
/Solutions/MinimumRemoveToMakeValidParentheses/minRemove.py
3,317
3.828125
4
#!/usr/bin/python3 """ @author : Chris Phibbs @created : Tuesday Feb 23, 2021 11:48:12 AEDT @file : minRemove """ # Only parentheses? Letters/numbers as well? # Length of string? Empty string? Max length? # Guaranteed to be at least one parenthese? # Any rules regarding starting with open/closing parentheses? # Are we returning the minimum number we need to remove? # Or are we returning the actual valid string? """ Algo: Go through string. Whenever you encounter an open bracket, add its index to stack. If you encounter a closed bracket and we have a non-empty stack, pop top element off. Basically we're checking that each open bracket has a matching closing bracket. If we encounter a closed bracket and there's no stack, then add its index to closeBrackets list. If we don't have anything on the stack or in closedBrackets list, the string is valid. Otherwise, remove all indices in the two lists from original string, returning result. TC: O(N) - We go through string twice, once to find wrong parentheses, the other time to concatenate resulting string SC: O(N) - Worst case every character in original string is invalid, and we have to store all of them in lists """ class Solution: def minRemoveToMakeValid(self, s): # If empty string, just return it straight back if not s: return s # Create a stack for keeping track of parentheses stack = list() closedBrackets = list() # Otherwise, go through whole list for i in range(len(s)): nextChar = s[i] # If open bracket, put index on stack if nextChar == "(": stack.append(i) if nextChar == ")": # If matching open bracket, pop it off stack if stack: stack.pop() # Otherwise, add to closedBrackets list else: closedBrackets.append(i) # # If no stack or closedBrackets, string doesn't need to be changed # if not stack and not closedBrackets: return s # print(stack, closedBrackets) # Order the lists into one deque toRemove = self.combineLists(stack, closedBrackets) # print(toRemove) # Remove all given indices output = "" lastIndex = 0 for i in toRemove: output += s[lastIndex:i] lastIndex = i + 1 # Add remainder of list to output output += s[lastIndex:] return output # Helper function to combine lists def combineLists(self, stack, closedBrackets): i, j = 0, 0 # Put indices in order toRemove = list() while i < len(stack) and j < len(closedBrackets): if stack[i] < closedBrackets[j]: toRemove.append(stack[i]) i += 1 else: toRemove.append(closedBrackets[j]) j += 1 # If we run out of one list, add the rest of # the other on the end if i < len(stack): toRemove += stack[i:] if j < len(closedBrackets): toRemove += closedBrackets[j:] return toRemove
c52becc40f609d5e57b10e02a710b1e99b8fa11e
jaroldhakins/AirBnB_clone
/models/engine/file_storage.py
1,632
3.671875
4
#!/usr/bin/python3 """ Write a class FileStorage """ import json from os.path import exists from models.base_model import BaseModel from models.user import User from models.amenity import Amenity from models.city import City from models.place import Place from models.review import Review class FileStorage: """ This class serializes instances to a JSON file and deserializes JSON file to instances """ __file_path = "file.json" __objects = {} def all(self): """ returns the dictionary __objects """ return FileStorage.__objects def new(self, obj): """ sets in __objects the obj with key <obj class name>.id """ name = obj.__class__.__name__ identifier = obj.id FileStorage.__objects[name + "." + identifier] = obj def save(self): """ serializes __objects to the JSON file (path: __file_path) """ to_json = {} for key, value in FileStorage.__objects.items(): to_json[key] = value.to_dict() with open(FileStorage.__file_path, 'w') as file: json.dump(to_json, file) def reload(self): """ deserializes __objects to the JSON file (path: __file_path) """ if exists(self.__file_path): try: with open(FileStorage.__file_path, 'r') as file: dict_obj = json.load(file) for k, v in dict_obj.items(): self.__objects[k] = eval(f'{v["__class__"]}(**v)') except Exception: pass
8987dcfd442fd2ef6da2469909a6a811b97f8143
asmaHelmy/improve_education_v1.0.0
/helper.py
3,812
4.1875
4
import pandas as pd def train_cats(df): ''' this function is to help proveide categorical type (encoding) for the categorical variables. # Arguments df : data frame that holds training data set # Return it provide an inplace process to interpret categorical variables ''' for label, content in df.iteritems(): if df[label].dtypes not in ['int', 'float64']: df[label] = content.astype('category').cat.as_ordered() def applay_cats(df, trn): ''' this function can be used to give a categorical type for df categorical variables using the same way of coding used in the trainging set. # Arguments df: data frame --test or validation data set trn: data frame -- training data set # Return ''' for label, content in df.items(): if trn[label].dtype.name == 'category': df[label] = pd.Categorical(content, categories=trn[label].cat.categories, ordered=True) ################################################### def courses_one_hot_encodeing(Courses, df): st_courses = list(df['Courses'].str.split(', ')) one_hot = dict() temp = [] for course in Courses: for index_, list_ in enumerate(st_courses): if course not in list_: temp.append('0') else: temp.append('1') one_hot[course] = temp temp = [] one_hot_df = pd.DataFrame(one_hot) df = df.drop('Courses', axis = 1) df = df.join(one_hot_df) return df ################################################### def attribute_value_converter(student_df): ''' this method converts attribute values from arbic to english # Arguments student_df : data frame of students data #Return ''' student_df['FarHome'] = student_df['FarHome'].map( {"ايوه" : "Yes", "لا" : "No"}) student_df['HasAJob'] = student_df['HasAJob'].map( {"ايوه" : "YesHJ", "لا" : "NoHJ"}) student_df['FinantialLevel'] = student_df['FinantialLevel'].map( {"عالي" : "High", "متوسط" : "Average", "ضعيف" : "Low"}) student_df['GroupsResources'] = student_df['GroupsResources'].map( {"اه، باخد منها محاضرات أحيانًا" : "Follow", "مش متابع والله" : "Avoide",}) student_df['FrequentAbcense'] = student_df['FrequentAbcense'].map( {"اه" : "Yes", "لا" : "No"}) student_df['ExtraActivities'] = student_df['ExtraActivities'].map( {"اه" : "YesXA", "لا" : "NoXA"}) student_df['HealthProblems'] = student_df['HealthProblems'].map( {"اه" : "Yes", "لا" : "No"}) student_df['ParentsHaveDegree'] = student_df['ParentsHaveDegree'].map( {"اه" : "Yes", "لا" : "No"}) student_df['EnglishLevel'] = student_df['EnglishLevel'].map( {"لغتي التانية يا جدععع" : "Advanced", "متوسط" : "Intermediate", "ضعيف": "beginner"}) student_df['StudentGuardian'] = student_df['StudentGuardian'].map( {"بابا" : "Father", "ماما" : "Mother", "الاتنين": "Both", "حد تاني" : "Other"}) student_df['InvolvmentLevel'] = student_df['InvolvmentLevel'].map( {"ملتزم" : "High", "بحضر نص نص" : "Average", "مش بحضر": "Low"}) return student_df def one_hot_encoding(features, df): for feature in features: one_hot = pd.get_dummies(df[feature]) df = df.drop(feature, axis = 1) df = df.join(one_hot) return df def numericalize(df): for n, c in df.items(): if not is_numeric_dtype(c): df[n] = col.cat.codes
253ddfc40318017a57c7afdc250f8be4c70f26a3
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/a01530f42bad4cd6a0c4c78378bfedbd.py
465
4.09375
4
# # Skeleton file for the Python "Bob" exercise. # def hey(what): #If there is no characters then return no talking case if not what.strip(): return('Fine. Be that way!') #Checks if the string is all capitals if what.isupper(): return('Whoa, chill out!') #Check for question mark at the end and returns case if what.strip().endswith('?'): return('Sure.') #Once we have checked all other cases then we have final case return('Whatever.')
fa8185e18ba45b8a10e7c84a701931b032ed5d98
g0ve/IN3110
/assignment4/blur.py
1,187
3.5
4
import argparse from blur_1 import main as blur_1 from blur_2 import main as blur_2 from blur_3 import main as blur_3 """ This program is a user interface. It has diffrent options, which all can be viewed with --help. This makes it possible to run all of the 3 implementation of image blurring. """ parser = argparse.ArgumentParser(description='Blur image program') parser.add_argument("-pp","--purePython", help="Blurs an image with pure python code", action='store_true') parser.add_argument("-np","--numpy", help="Blurs an image with with help of Numpy", action='store_true') parser.add_argument("-nb","--numba", help="Blurs an image with help of Numba", action='store_true') parser.add_argument("-i","--input", help="If you want to specify a input file :)", default='beatles.jpg') parser.add_argument("-o","--output", help="If you want to specify a output file :)", default='blurred_image.jpg') args = parser.parse_args() if args.purePython: blur_1(args.input, args.output) elif args.numpy: print(args.output) blur_2(args.input, args.output) elif args.numba: blur_3(args.input, args.output) else: print("This didnt quit work. Try: $python blur.py --help")
e6d4f0f18eccead8c0ee124b7b2c62c6904bfc96
AngelValAngelov/Python-Advanced-Exercises
/Multidimensional Lists - Exercise/01. Diagonal Difference.py
409
3.90625
4
matrix_size = int(input()) matrix = [] for _ in range(matrix_size): row = input().split() matrix.append([int(x) for x in row]) primary_diagonal_sum = 0 secondary_diagonal_sum = 0 for i in range(matrix_size): primary_diagonal_sum += matrix[i][i] secondary_diagonal_sum += matrix[i][-i - 1] difference = abs(primary_diagonal_sum - secondary_diagonal_sum) print(difference)
8b4a42ba3793428ca9d602971ebc23eae3429db1
alferesx/programmingbydoing
/SpaceBoxing.py
804
4
4
weight = float(input("Weight: ")) print("1-Venus") print("2-Mars") print("3-Jupiter") print("4-Saturn") print("5-Uranus") print("6-Neptune") planet = int(input("Choose a planet: ")) if planet == 1: gravity = 0.78 weight = weight * gravity print("Weight: " + weight) elif planet == 2: gravity = 0.39 weight = weight * gravity print("Weight: " + weight ) elif planet == 3: gravity = 2.65 weight = weight * gravity print("Weight: " + weight ) elif planet == 4: gravity = 1.17 weight = weight * gravity print("Weight: " + weight ) elif planet == 5: gravity = 1.05 weight = weight * gravity print("Weight: " + weight ) elif planet == 6: gravity = 1.23 weight = weight * gravity print("Weight: " + weight ) else: print("This option is not avaiable")
d60c88c956839b5a85914645dc8057a42727f178
Plotkine/HackerRank
/Hard/en_cours_Matrix_Layer_Rotation.py
1,431
3.703125
4
#!/bin/python3 import math import os import random import re import sys from copy import deepcopy # Complete the matrixRotation function below. def matrixRotation(matrix,r): res = deepcopy(matrix) m = len(matrix) n = len(matrix[0]) for _ in range(r): ring = 0 while ring <= min(m,n) / 2: resCopy = deepcopy(res) i = ring j = ring #going right while j + 1 < n - ring: res[i][j] = resCopy[i][j+1] j += 1 #going down while i + 1 < m - ring: res[i][j] = resCopy[i+1][j] i += 1 #going left while j - 1 >= ring: res[i][j] = resCopy[i][j-1] j -= 1 #going up while i - 1 >= ring: res[i][j] = resCopy[i-1][j] i -= 1 ring += 1 #print("") for i in range(len(res)): for j in range(len(res[0]) - 1): print(str(res[i][j])+" ",end='') print(str(res[i][len(res[0]) - 1]),end='') if i != len(res) - 1: print("\n",end='') if __name__ == '__main__': mnr = input().rstrip().split() m = int(mnr[0]) n = int(mnr[1]) r = int(mnr[2]) matrix = [] for _ in range(m): matrix.append(list(map(int, input().rstrip().split()))) matrixRotation(matrix, r)
9a8be9762b0923d6abb2c582098866119efe4866
jsillman/astr-119-hw-1
/variables_and_loops.py
456
3.9375
4
import numpy as np #importing numpy def main(): i = 0 #initialize i to 0 n = 10 #and n to 10 as integers x = 119.0 #initialize x to 119 as a float y = np.zeros(n,dtype=float) #array of 10 zeros as floats for i in range(n): #loop from 0 to 9 y[i] = 2.0 * float(i) + 1.0 #setting y elements to 2i+1 as floats for y_element in y: #print each element of y print(y_element) if __name__ == "__main__": main() #run
629bf83bc9c5c83fe87774222080b9db36f085e6
JavierEsteban/TodoPython
/Ejercicios/OperadoresBasicos/Python -Ojala/Clase 2.py
303
3.609375
4
#Trabajando con Fechas from datetime import time from datetime import date from datetime import datetime def main(): fecha = date.today() print(fecha) print(fecha.day) print(fecha.year) print(fecha.month) print(str(fecha).replace("-","")) if __name__ == "__main__": main()
d5b7118fe34a8f2319cfc3cb24a09f89f8e6ee5f
FrankFang0830/pyc1
/lab1-2.py
563
3.828125
4
data = [('John', ('Physics', 80)), ('Daniel', ('Science', 90)), ('John', ('Science', 95)), ('Mark', ('Maths', 100)), ('Daniel', ('History', 75)), ('Mark', ('Social', 95))] def sort_by_course_name(o1: tuple) -> str: return o1[0] if __name__ == '__main__': result = {} for element in data: person, score = element if person in result: result[person].append(score) result[person].sort(key=sort_by_course_name) else: result[person] = [score, ] print("result = ", result)
1359fcb2241b2dea2f53da9b998a93f0bdb9bd0c
BryanTorresCalle/Practica3_ciber
/punto2.py
1,121
3.515625
4
import time from hashlib import sha256 import random as rand import matplotlib.pyplot as plt def punto2(): n = int(input("Ingrese un número entre 1 y 10 ")) interacciones = 0 while n < 1 or n > 11: n = int(input("Ingrese un número entre 1 y 10 ")) print ("Ingrese un n valido") while True: inicio = time.time() x = str(rand.randint(1,100000)) hash_val = sha256(x.encode()).hexdigest() interacciones += 1 if hash_val[0:n] == n*'0': fin = time.time() tiempo = float(fin - inicio) return [interacciones, tiempo,n] # Press the green button in the gutter to run the script. if __name__ == '__main__': listTime = [] listIterations = [] listN = [] n = [1,2,3,4,5] for n in range (5): returns = punto2() listTime.append(returns[1]) listIterations.append(returns[0]) listN.append(returns[2]) plt.plot(listN, listIterations) plt.ylabel('Cantidad de iteraciones') plt.xlabel('n seleccionado') plt.show() print(listN) print(listIterations)
712460951c008d5a70849ed6a6dd7183cd7226b1
RasPat1/withdrawlolz
/project_euler/p9.py
727
4.25
4
""" A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.""" import itertools import math def p9_bf(abc_sum): loop_count = 0 product = 0 for a, b in itertools.permutations(range(1, abc_sum), 2): c = math.sqrt(a**2 + b**2) sum = a + b + c if (a + b + c) == abc_sum: product = a * b * c break loop_count += 1 print(f'{loop_count} loops counted') return product abc_sum = 1000 solution = p9_bf(abc_sum) print(solution) # Let's see if we can do something different. # How do we solve for pythagorean triples? #
76ade0d85f202b89622f90c57b0816018cd983a7
qz267/leet-code-fun
/PY/wordSearch/main.py
1,087
3.65625
4
''' Created on May 16, 2013 @author: Yubin Bai ''' def wordSearch(matrix, w): ''' search for words in matrix ''' def _search(x, y, step, w): ''' backtrack ''' if step == len(w): result[0] = True return if result[0] or x < 0 or x >= len(matrix) or y < 0 or y >= len(matrix[0]): return if matrix[x][y] == w[step]: temp = matrix[x][y] matrix[x][y] = -1 _search(x - 1, y, step + 1, w) _search(x + 1, y, step + 1, w) _search(x, y + 1, step + 1, w) _search(x, y - 1, step + 1, w) matrix[x][y] = temp result = [False] for i in range(len(matrix)): for j in range(len(matrix[0])): _search(i, j, 0, w) if result[0]: return True return False if __name__ == '__main__': matrix = [ list("ABCE"), list("SFCS"), list("ADEE") ] words = ['SEE', 'ABCB', 'ABCCED'] for w in words: print(wordSearch(matrix, w))
51469703dcca375964c1d8834c8f35b0587344f1
sunilmummadi/Linked-List-1
/reverse_Linked_List.py
1,593
3.90625
4
# Leetcode 206. Reverse Linked List # Time Complexity : O(n) where n is the size of the array # Space Complexity : O(n) where n is the size of the recurssive stack # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Approach: Move head to the last node in the list recurrsively and store it. Once the end is reached # head points to the last but one element due to recurssive stack pop. Start reversing the next pointers # of the last node i.e. head.next.next to point to head. Simultaneously delete the previous order next pointer # return the last element as its the start of the reversed list # Your code here along with comments explaining your approach # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseList(self, head: ListNode) -> ListNode: # Base case where list is empty or has one node if not head or not head.next: return head # Move head to the last node in the list recurrsively and store it last = self.reverseList(head.next) # Once the end is reached head points to the last but one element due to # recurssive stack pop. # start reversing the next pointers of the last node i.e. head.next.next to point to head head.next.next = head # Simultaneously delete the previous order next pointer head.next = None # return the last element as its the start of the reversed list return last
0bd6707cc54dbc678638a2978d7c4fb701dd4e43
yibwu/leetcode
/src/sum_of_even_numbers_after_queries_985.py
1,032
3.515625
4
class Solution: def sum_even_after_queries(self, A, queries): res = [] for q in queries: val = q[0] i = q[1] tmp = A[i] A[i] += val if not res: res.append(self.get_sum_of_even(A)) else: if tmp % 2 == 0: if A[i] % 2 == 1: res.append(res[-1] - tmp) else: res.append(res[-1] + val) else: if A[i] % 2 == 1: res.append(res[-1]) else: res.append(res[-1] + A[i]) return res def get_sum_of_even(self, numbers): numbers = list(filter(lambda x: x % 2 == 0, numbers)) return sum(numbers) if __name__ == '__main__': obj = Solution() A = [1, 2, 3, 4] queries = [[1, 0], [-3, 1], [-4, 0], [2, 3]] res = obj.sum_even_after_queries(A, queries) print(res)
e5bcdaa58257ecad81638e89946f0dd0714797a6
vraj152/projectcs520
/readingData.py
2,419
3.5
4
import numpy as np """ This method reads entire file and returns as a list Params: souce_file = file path total_images = dataset size length = length of pixel width = length of pixel Returns: Entire file in list """ def load_data(source_file, total_images, length, width): datasetFile = open(source_file) data_line = datasetFile.readlines() image_data= [] for i in range(total_images): temp_data = [] for j in range(length*i, length*(i+1)): temp_data.append(data_line[j]) image_data.append(temp_data) return image_data """ This method returns the labels of training data. Params: Takes path of the input file returns: list of all the labels """ def load_label(source_file): label_file = open(source_file) label_lines = label_file.readlines() labels = [] for i in range(len(label_lines)): labels.append(label_lines[i].strip()) return labels """ This method requires entire data passed in list, and will return list of numpy array Params: image_data = list length = length of pixel width = length of pixel Returns: List of Numpy array And array is representation of given data """ def matrix_transformation(image_data, length, width): total_data = len(image_data) final_data = [] for i in range(total_data): mat = np.zeros((length, width)) single_image = image_data[i] single_image_length = len(single_image) for j in range(single_image_length): single_line = single_image[j] single_line_length = len(single_line) for k in range(single_line_length): if(single_line[k] == '+'): mat[j][k] = 1 if(single_line[k] == '#'): mat[j][k] = 2 final_data.append(mat) return final_data def matrix_transformation_test(image_data, length, width): mat = np.zeros((length, width)) single_image = image_data single_image_length = len(single_image) for j in range(single_image_length): single_line = single_image[j] single_line_length = len(single_line) for k in range(single_line_length): if(single_line[k] == '+'): mat[j][k] = 1 if(single_line[k] == '#'): mat[j][k] = 2 return mat
1e96e2a651e0fbc0908f6643943768cc63ef4625
adam-weiler/GA-OOP-Inheritance-Part-3
/system.py
2,367
4.03125
4
class System(): all_bodies = [] #Stores all bodies from every solar system. def __init__(self, name): self.name = name self.bodies = [] #Stores only bodies from this solar system. def __str__(self): return f'The {self.name} system.' def add(self, celestial_body): if celestial_body not in self.bodies: #Checks if celestial_body is not in the bodies list yet. System.all_bodies.append(celestial_body) self.bodies.append(celestial_body) return f'Adding {celestial_body.name} to the {self.name} system.' else: return f'You can\'t add {celestial_body.name} again.' def list_all(self, body_type): for body in self.bodies: #Iterates through each body in self.bodies list. if isinstance(body, body_type): #If current body is of body_type. ie: Planet. print(body) #Prints the class-specific __str__ method. @classmethod def total_mass(cls): total_mass = 0 for body in cls.all_bodies: total_mass += body.mass return total_mass class Body(): def __init__(self, name, mass): self.name = name self.mass = mass @classmethod def list_all(self, body_type): for body in System.bodies: #Iterates through each body in System.bodies list. if isinstance(body, body_type): #If current body is of body_type. ie: Planet. print(body) #Prints the class-specific __str__ method. class Planet(Body): def __init__(self, name, mass, day, year): super().__init__(name, mass) self.day = day self.year = year def __str__(self): return f'-{self.name} : {self.day} hours per day - {self.year} days per year - weighs {self.mass} kg.' class Star(Body): def __init__(self, name, mass, star_type): super().__init__(name, mass) self.star_type = star_type def __str__(self): return f'-{self.name} : {self.star_type} type star - weighs {self.mass} kg.' class Moon(Body): def __init__(self, name, mass, month, planet): super().__init__(name, mass) self.month = month self.planet = planet def __str__(self): return f'-{self.name} : {self.month} days in a month - in orbit around {self.planet.name} - weighs {self.mass} kg.'
232de43b0ba94630052e4af70341c7ea4a517328
FawneLu/leetcode
/tree_traverse.py
1,664
4.1875
4
#递归 ##前序 def recursion_preorder(self,node): if not node: return else: print(node.elem,end=' , ') self.recursion_preorder(node.left) self.recursion_preorder(node.right) ##中序 def recursion_inorder(self,node): if not node: return else: self.recursion_inorder(node.left) print(node.elem,end=' , ') self.recursion_inorder(node.right) ##后序 def recursion_postorder(self,node): if not node: return else: self.recursion_postorder(node.left) self.recursion_postorder(node.right) print(node.elem,end=' , ') #非递归 ##前序 def nonrecursion_preorder(self,node): if not node: return stack.append(node) while stack: curr_node=stack.pop() if not curr_node: continue else: print(curr_node,end=' ') stack.append(node.right) stack.append(node.left) def nonrecursion_preorder(self,node): if not node: return stack=[] while stack or node: while node: print(node,end=' , ') stack.append(node) node=node.left node=stack.pop() node=node.right ##中序遍历 def nonrecursion_inorder(self,node): if not node: return while stack or node: while node: stack.append(node) node=node.left node=stack.pop() print(node,end=' , ') node=node.right ##后序遍历 def nonrecursion_postorder(self,node): if not node: return stack,res,last_visit=[],[],None while stack or node: while node: stack.append(node) node=node.left curr_node=stack[-1] if not curr_node.right or curr_node.right==last_visit: item=stack.pop() res.append(item.value) last_visit=item elif curr_node.right: node=curr_node.right return res
8f87b699dbbca585d0437251a0ed5b7d45147f7d
rkantamneni/CS550-FallTerm
/hw_assignments:class_notes/class926.py
646
3.875
4
import sys import random for x in range(1): orig=random.randint(1,10) again='y' while again=='y': num = int(input('Write a number between 1 and 10: ')) if num==orig: print('You guessed correct') else: print('You guessed incorrect') if num>orig: print('Too high') elif num<orig: print('Too low') again = input('Want to play again? (y/n)') print('Thanks for playing.') ''' import sys num = int(input('How fast were you going?: ')) birth = input('Is today your birthday (y/n): ') if birth=='y': num=num-5 if num<60: print('No ticket') elif num<80 and num>60: print('Small ticket') elif num>80: print('Big ticket') '''
b95232d64e40dd0b888ed16755553a86556fa19e
carolinegbowski/exercises_day_1
/08-sum-of-divisors.py
333
3.640625
4
def divisor_data(num): data = [] divisors = [divisor for divisor in range(1,(num + 1)) if (num % divisor == 0)] data.append(divisors) sum_of_divisors = sum(divisors) data.append(sum_of_divisors) number_of_divisors = len(divisors) data.append(number_of_divisors) return data print(divisor_data(60))
7d2fcf6dab55913a82951cc6aa29802481865315
vikinglion/Python
/python_work/valid_parentheses.py
682
3.546875
4
#!/usr/bin/env python # -*- coding=utf-8 -*- SYMBOLS = {')': '(',} SYMBOLS_L, SYMBOLS_R = SYMBOLS.values(), SYMBOLS.keys() def check(s): arr = [] for c in s: if c in SYMBOLS_L: # 左符号入栈 arr.append(c) elif c in SYMBOLS_R: # 右符号要么出栈,要么匹配失败 print(arr) if arr and arr[-1] == SYMBOLS[c]: arr.pop() else: return False if len(arr) != 0:return False else:return True print(check("(dfsadf)()")) print(check("(()")) print(check("fnva(mfd)gfv(yncxw()lcmx)lwql((i))")) print(check("())"))
ef202ab8f94cbdfc846e7707834373cd9d2d73c3
adamfitzhugh/python
/kirk-byers/Scripts/Week 7/exercise3b.py
889
4.0625
4
""" Expand the data structure defined earlier in exercise3a. This time you should have an 'interfaces' key that refers to a dictionary. Use Python to read in this YAML data structure and print this to the screen. The output of your Python script should look as follows (in other words, your YAML data structure should yield the following when read by Python). You YAML data structure should be written in expanded YAML format. {'interfaces': { 'Ethernet1': {'mode': 'access', 'vlan': 10}, 'Ethernet2': {'mode': 'access', 'vlan': 20}, 'Ethernet3': {'mode': 'trunk', 'native_vlan': 1, 'trunk_vlans': 'all'} } } """ from __future__ import print_function, unicode_literals import yaml from pprint import pprint file = 'exercise3b.yml' with open(file) as f: data = yaml.load(f) print() pprint(data) print()
1878bd997f5dbb47bfcca12604392d00d5cbb688
mkyu0917/pystudy
/quiz/quiz01_3.py
706
3.765625
4
students = [ { "name": "kim", "kor" : 80, "kor" : 90, "math" : 80 }, { "name": "Lee", "kor" : 90, "kor" : 85, "math" : 85 } ] score = dict() print(score) avg =250/3 total =(80+90+80) keys = ('name','kor','eng','avg','sum') values = ("Kim", 80, 90, 80, avg, total) score = dict(zip(keys, values)) print(score) score2 = dict() avg = 260/3 total =(85+90+85) keys = ('name', 'kor','eng','avg','sum') values = ("Lee", 90, 85, 85, avg, total) score2 = dict(zip(keys, values)) print(score2) #students=[score,score2] print(students)
2dd9904e49dc6509fe5ae4ae0e3687d9ae9038b9
gbpaixao/FamousProblems
/Graphs/Prim/prim_heap.py
1,966
3.90625
4
# Prim algorithm # The strategy of using heap was to add tuples of (edge_weight, x_position, y_position) in order # to collect the edge with mininum weight at each iteration # input where n is weight of each edge # 0,2,1,0,0 # 2,0,1,2,3 # 1,1,0,0,4 # 0,2,0,0,2 # 0,3,4,2,0 from heapq import heappop, heappush import random as rand def printGraph(g): for row in g: print (row) print ("---------------------------\n") def fillGraph (inputfile): graph = [] f = open(inputfile,"r+") numberOfVertexes = 0 for row in f: row = row.split(',') row = [int(x) for x in row] graph.append(row) numberOfVertexes += 1 f.close() return graph, numberOfVertexes def findEdge (heap, T): aux = heappop(heap) while aux[2] in T: aux = heappop(heap) return aux[1],aux[2] # method to insert the edges of the vertexes on T on the heap def insertHeap (g, heap, vertex, T): for j, element in enumerate(g[vertex]): if element != 0 and j not in T: # this is to eliminate the mirror in non directional graphs heappush(heap,(element,vertex,j)) return heap def prim (g, n): Tmin = set() # set of minimum tree T = set() # set of visited vertexes N = set() # set of non-visited vertexes for idx in range(n): N.add(idx) i = rand.randrange(0,n) cost = 0 heap = [] heap = insertHeap(g,heap,i,T) T.add(i) N.remove(i) while len(T) != n: ex, ey = findEdge(heap,T) T.add(ey) N.remove(ey) Tmin.add(ey) Tmin.add(ex) heap = insertHeap(g,heap,ey,T) print (ex,'->',ey,':',g[ex][ey]) cost = cost + g[ex][ey] print ("Custo da árvore geradora mínima:",cost) def main(): inputfile = "graphs/g1.txt" # Open file g, n = fillGraph(inputfile) # Fill graph print ("Grafo Original: ") printGraph(g) # Print graph prim(g,n) main()
43d404cf60504c9cdaed69a9651b1982f2a5b295
hawkinmogen/Python-CheckiO-Problems
/Convert to Roman Numerals/convert2RomanNums.py
613
3.859375
4
# Link to my solution on CheckiO: # https://py.checkio.org/mission/roman-numerals/publications/hawkinmogen/python-3/first/share/7e771838405cfd368ffb68b6f0e16292/ def checkio(data): result="" NUMERALS=(('M',1000),('CM',900),('D',500),('CD',400),('C',100),('XC',90), ('L',50),('XL',40),('X',10),('IX',9),('V',5),('IV',4),('I',1)) #Adds the largest roman numeral that is < 'data' to 'result' and substracts the value from 'data'... #until 'data'= 0 for numeral, number in NUMERALS: while number<=data: data-=number result+=numeral return result
820d6b68f60f7ee454b1b97a2152eb1a769d10c9
Akshat1276NSP/CBJRWDhome_assignment
/Python revision full course/8.py
225
3.796875
4
story = "asd qwe rty uio pas dfg hjk lzx cvb nm asdiha piqwjeo jakjsscmbd" #string functions print(len(story)) print(story.endswith("UUUUUUUUUUUUUU")) print(story.count("a")) print(story.capitalize) print(story.find("Har"))
d349ca11d405495089fc3faa52d6b41408ecfded
PilarPinto/holbertonschool-higher_level_programming
/0x03-python-data_structures/1-element_at.py
242
3.5
4
#!/usr/bin/python3 def element_at(my_list, idx): if idx < 0: return (None) if idx > len(my_list): return (None) for number in range(0, len(my_list)): if (number == idx): return(my_list[number])
0dcde054b1b28afb53ad264ccb1d925e2fba5462
gameboy1024/ProjectEuler
/src/problem_77.py
925
3.671875
4
# -*- coding: utf-8 -*- ''' Prime summations Problem 77 It is possible to write ten as the sum of primes in exactly five different ways: 7 + 3 5 + 5 5 + 3 + 2 3 + 3 + 2 + 2 2 + 2 + 2 + 2 + 2 What is the first value which can be written as the sum of primes in over five thousand different ways? Answer: 71 Completed on Thu, 22 Jan 2015, 11:59 https://projecteuler.net/problem=77 @author Botu Sun ''' from lib.math_utils import PrimeChecker prime_checker = PrimeChecker(1E5) def Function(x, y, map, prime_checker): if x == 0: return 1 if x < 2: return 0 if (x, y) in map: return map[(x, y)] sum = 0 for p in prime_checker.get_prime_list(): if p <= x and p <= y: tmp = Function(x - p, p, map, prime_checker) sum += tmp else: break map[(x, y)] = sum return sum map = {} i = 1 while (Function(i, i - 1, map, prime_checker) <= 5000): i += 1 print i
ad7bda035e84700fb77bc7bb16cfda78089aeb21
bellatrixdatacommunity/data-structure-and-algorithms
/leetcode/linked-list/remove-linked-list-elements.py
1,620
3.84375
4
''' 203. [Remove Linked List Elements](https://leetcode.com/problems/remove-linked-list-elements/) Remove all elements from a linked list of integers that have value val. Example: Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 ''' # Solution # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if not head: return head head_ref = ListNode(None) new_pointer = head_ref while head: if head.val != val: new_node = ListNode(head.val) head_ref.next = new_node head_ref = head_ref.next head = head.next head = None head_ref = None return new_pointer.next # Runtime: 84 ms # Memory Usage: 18.5 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: if not head: return head head_ref = ListNode(None) head_ref.next = head new_pointer = head_ref while head_ref: if head_ref.val == val: temp = head_ref.next head_ref = prev head_ref.next = temp else: prev = head_ref head_ref = head_ref.next return new_pointer.next # Runtime: 72 ms # Memory Usage: 16.9 MB
3f1fb96b6cc36f251c4499098079362c0aa4b1fb
rain-zhao/leetcode
/py/Task238.py
1,610
3.515625
4
# 给你一个长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。 #   # 示例: # 输入: [1,2,3,4] # 输出: [24,12,8,6] #   # 提示:题目数据保证数组之中任意元素的全部前缀元素和后缀(甚至是整个数组)的乘积都在 32 位整数范围内。 # 说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 # 进阶: # 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。) from typing import List class Solution: # 左边乘一遍右边乘一遍 def productExceptSelf(self, nums: List[int]) -> List[int]: l = len(nums) left = [1] * l right = [1] * l for i in range(l - 1): left[i + 1] = left[i] * nums[i] for i in range(l - 1, 0, -1): right[i - 1] = right[i] * nums[i] res = [] for a, b in zip(left, right): res.append(a * b) return res # 原地操作 def productExceptSelf2(self, nums: List[int]) -> List[int]: l = len(nums) res = [1] * l # left to right cur = 1 for i in range(l - 1): cur *= nums[i] res[i + 1] = cur # right to left cur = 1 for i in range(l - 1, 0, -1): cur *= nums[i] res[i - 1] *= cur return res nums = [1, 2, 3, 4] obj = Solution() print(obj.productExceptSelf2(nums))
f0f05ac675cf03380a7ed79a441e942d5101dc6d
ai-times/infinitybook_python
/chap12_p244_code1.py
252
3.578125
4
n = int(input("어떤 수를 판별해줄까요? ")) success = True t=2 while t<n : if n%t == 0 : success = False break t += 1 if success == True : print("소수 입니다.") else : print("소수가 아닙니다.")
0db9989084c71d6b718536820a9403ea783947ba
DarrenGibson/Python-Udemy-Course
/falseevaluations.py
683
3.59375
4
#=================================================================# # false evaluations #-----------------------------------------------------------------# ''' Date : Tue 14 Aug 2018 04:02:21 PM PDT Author : Darren Gibson Title : Python Udemy Course Resources : https://www.udemy.com/python-the-complete-python-developer-course/learn/v4/t/lecture/3812186?start=0 ''' ''' NOTES: ''' print("""false: {} none: {} 0: {} 0.0: {} empty list []: {} empty tuple (): {} empty string '': {} empty string "": {} empty mapping {{}}: {} """.format(False, bool(None), bool(0), bool(0.0), bool([]), bool(()), bool(''), bool(""), bool({})))
b64ee0acc25c260a83feb941d750f075e60812c8
purujeet/internbatch
/grat4.py
278
4.1875
4
w=int(input('w:')) x=int(input('X:')) y=int(input('y:')) z=int(input('z:')) if w>=x and w>=y and w>=z: print('w is greater') elif x>=w and x>=y and x>=z: print('x is greater') elif y>=w and y>=x and y>=z: print('y is greater') else: print('z is greater')
b9833255433dc4712d348e7ab89b3235381ecf55
mjip/Decoding-Running-Key-Ciphers
/code/FinalProject.py
28,895
3.546875
4
#!/usr/bin/python3 import random import sys import time import string import re import argparse from math import inf from math import log import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import MultinomialNB from sklearn.svm import LinearSVC def accuracy(correct, guess): """ Evaluates how accurate the output of the testing method is. Checks whether each letter or vector of the guess matches the corresponding letter or vector of the correct sentence and returns how many are right, as a percent. Args: correct: string or vector that is the correct sentence. guess: string or vector that is the output of the testing method. Returns: The accuracy of the guess based on what the correct answer is. acc: float representing what percentage of vectors or characters in the guess match the character at the same index in the correct sentence. """ acc = 0. if len(correct) == 0: return 0 for n in range(len(correct)): if correct[n] == guess[n]: acc += 1. return acc / len(correct) def devectorize(vector, n_grams): """ Transforms inputs from vectors to sentences. Goes through the vector and replaces each entry with its associated n-gram. For n > 1, the first vector is put in full and the rest have only their last letter put in. Args: vector: vector representing the sentence. n_grams: n-grams from which to create the sentence. Returns: plaintext: the plaintext sentence. """ plaintext = [n_grams[vector[0]]] for n in range(1, len(vector)): plaintext.append(n_grams[vector[n]][-1]) plaintext = ''.join(plaintext) return plaintext def generate_ngrams(alphabet, limit): """ Generates all possible n-grams from 1 to the limit. Goes through the alphabet in a loop to generate a list of lists of n-grams from 1 to the limit. Args: alphabet: list of the symbols from which the n-grams will be generated. limit: the maximum length of the n-grams generated. Returns: n_grams: a list of lists of n-grams up to the limit. """ print('Generating 1-grams') n_grams = [alphabet] for n in range(1, limit): print('Generating %d-grams' % (n + 1)) new_grams = [] for gram in n_grams[-1]: for letter in alphabet: new_grams.append('%s%s' % (gram, letter)) n_grams.append(new_grams) print('Done generating n-grams\n') return n_grams def get_hmms(sentences, n_grams, smoothing=True): """ Creates the hidden Markov models for all n-grams. Going through input sentences, the frequency of each n-gram is counted, as well as the n-gram which follows. These frequencies are smoothed with add-1 smoothing by default, but may be unsmoothed. Args: sentences: list of sentences on which to train the HMMs. n_grams: list of lists of n-grams for which to make HMMs. smoothing: boolean for whether to smooth with add-1 smoothing or not. Returns: hmms: a list of dicts which represent the HMMs and their initial and transition probabilities, as well as the frequencies of the n-grams. """ initial = 0. hmm_type = 'unsmoothed' if smoothing: initial = 1. hmm_type = 'smoothed' inits = [{} for grams in n_grams] inits_counts = [initial*len(grams) for grams in n_grams] transitions = [{} for grams in n_grams] trans_counts = [{} for grams in n_grams] freqs = [{} for grams in n_grams] freqs_counts = [initial*len(grams) for grams in n_grams] for n in range(len(n_grams)): print('Generating %s Markov model for %d-grams' % (hmm_type, (n+1))) for gram in n_grams[n]: inits[n].update({gram : initial}) freqs[n].update({gram : initial}) transitions[n].update({gram : {}}) next_grams = get_next_gram(gram, n_grams[n]) trans_counts[n].update({gram : initial * len(next_grams)}) for next_gram in next_grams: transitions[n][gram].update({next_gram : initial}) for sentence in sentences: if len(sentence) < len(n_grams): continue for n in range(len(n_grams)): start = sentence[:n+1] inits[n][start] += 1. inits_counts[n] += 1. for i in range(len(sentence)): for n in range(len(n_grams)): if i+n+1 < len(sentence): gram = sentence[i:i+n+1] freqs[n][gram] += 1. freqs_counts[n] += 1. if i+n+2 < len(sentence) and n > 0: next_gram = sentence[i+1:i+n+2] transitions[n][gram][next_gram] += 1. trans_counts[n][gram] += 1. for n in range(len(n_grams)): for gram in inits[n].keys(): prob = inits[n][gram] / inits_counts[n] if prob == 0: inits[n][gram] = -1 * inf else: inits[n][gram] = log(prob) for gram in freqs[n].keys(): prob = freqs[n][gram] / freqs_counts[n] if prob == 0: freqs[n][gram] = -1 * inf else: freqs[n][gram] = log(prob) for gram in transitions[n].keys(): for next_gram in transitions[n][gram].keys(): if trans_counts[n][gram] == 0: trans_counts[n][gram] = 1 prob = transitions[n][gram][next_gram] / trans_counts[n][gram] if prob == 0: transitions[n][gram][next_gram] = -1 * inf else: transitions[n][gram][next_gram] = log(prob) transitions[0] = {letter : inits[0].copy() for letter in inits[0].keys()} print('Done generating %s Markov models\n' % hmm_type) return [[inits[n], transitions[n], freqs[n]] for n in range(len(n_grams))] def get_next_gram(stem, grams): """ Yields every n-gram that can follow the stem n-gram. Args: stem: n-gram string for which we want possible following n-grams. grams: all n-grams of the same length as the stem. Returns: next_grams: list of n-grams which may follow the stem. That is, an n-gram whose first n-1 letters match the last n-1 letters of the stem. """ next_grams = [] for gram in grams: if gram[:len(gram)-1] == stem[1:]: next_grams.append(gram) return next_grams def print_to_file(guesses, correct, formatting, filename, viterbi=False): """ Prints the guesses to a .txt file for further examination. For each guess, the sentence is formatted as the original correct sentence was, then appended to a string in the form guess -- correct. These guesses are then printed to file. Args: guesses: list of tuple strings representing the decoding guesses. correct: the correct sentences. formatting: the dict that has how each correct sentence is formatted. filename: the name of the file to print to. viterbi: boolean for whether this is for the results of Viterbi or not. """ intro_message = ('Each line represents the output guess of decoding using ' 'the method indicated by the filename.\nEach line is of ' 'the form:') form = '\n[correct]\n[message guess]\n[key guess]\n\n' if not viterbi: form = '\n[correct]\n[guess]\n\n' to_print = [intro_message, form] if not viterbi: for n in range(len(guesses)): format_to_follow = correct[n] message = list(guesses[n]) for m in range(len(format_to_follow)): letter = format_to_follow[m] if not letter.isalpha(): message.insert(m, letter) message = ''.join(message) line = '%s\n%s\n\n' % (correct[n], message) to_print.append(line) else: for n in range(len(guesses)): format_to_follow = correct[n] message_guess = list(guesses[n][0]) key_guess = list(guesses[n][1]) for m in range(len(format_to_follow)): letter = format_to_follow[m] if not letter.isalpha(): message_guess.insert(m, letter) key_guess.insert(m, letter) message_guess = ''.join(message_guess) key_guess = ''.join(key_guess) line = '%s\n%s\n%s\n\n' % (correct[n], message_guess, key_guess) to_print.append(line) filename += '.txt' file = open('cache/' + filename, 'w+') file.write(''.join(to_print)) file.close() def vectorize(sentence, n_grams, n): """ Transforms a sentence into a vector representing itself in n-gram form. Runs through the sentence and for each n-gram that appears, appends the index of that n-gram to the vector for the sentence, then returns that vector. Args: sentence: string to vectorize. n_grams: list of n-grams to create vectors out of. n: the length of each n-gram. Returns: vector: list which is the vector representation of the sentence. """ vector = [] for i in range(len(sentence)-n+1): sentence_gram = sentence[i:i+n] vector.append(n_grams.index(sentence_gram)) return vector def viterbi(sentence, markov_models): """ Runs through the Viterbi algorithm for the largest order Markov model. Initializes one or more pre-trellises which run Viterbi for the beginning of the sentence, and then the trellis for the Markov model in question is qcalculated using transition probabilities from the pre-trellises for initial probabilities. Then returns the most likely (message, key) pair, with the first being arbitrarily selected as the message. Args: sentence: the sentence on which Viterbi is run. markov_models: the Markov models which Viterbi uses for probabilities. Returns: message_key: tuple that contains the message and key. The message is the first and the key is the second. The real message may be the key, but the first is arbitrarily chosen as the message. """ if len(markov_models) == 1: return viterbi_unigram(sentence, markov_models[0]) alphabet = list('abcdefghijklmnopqrstuvwxyz') trellis = [{}] # Initializes the trellis for the start of the sentence with the # "pre-trellises", plus the start of the trellis for the n-grams in # question. for n in range(len(markov_models)): states = list(markov_models[n][0].keys()) trans = markov_models[n][1] freqs = markov_models[n][2] if n == 0: init = markov_models[n][0] for state in states: key = alphabet[(alphabet.index(sentence[0]) \ - alphabet.index(state)) % 26] emit = freqs[state] + freqs[key] trellis[0].update({state : {'prob' : init[state] + emit, 'prev' : None, 'key' : key}}) else: trellis.append({}) for state in states: key = '' for n in range(len(state)): letter = alphabet[(alphabet.index(sentence[n]) \ - alphabet.index(state[n])) % 26] key = '%s%s' % (key, letter) emit = freqs[state] + freqs[key] prev_trans = markov_models[n-1][1] prev_states = list(prev_trans.keys()) if n > 1: prev_states = [gram for gram in prev_states if gram == state[:-1]] max_trans = prev_trans[prev_states[0]][state[1:]] previous = prev_states[0] for prev in prev_states: if prev_trans[prev][state[1:]] > max_trans: max_trans = prev_trans[prev][state[1:]] previous = prev trellis[n].update({state : {'prob' : max_trans + emit, 'prev' : previous, 'key' : key}}) states = list(markov_models[-1][0].keys()) trans = markov_models[-1][1] freqs = markov_models[-1][2] # Filling the rest of the trellis. num_grams = len(trellis) - 1 for i in range(1, len(sentence)-len(markov_models)+1): trellis.append({}) for state in states: key = '' for n in range(len(state)): letter = alphabet[(alphabet.index(sentence[i+n]) \ - alphabet.index(state[n])) % 26] key = '%s%s' % (key, letter) emit = freqs[state] + freqs[key] prev_states = [gram for gram in states if gram[1:] == state[:-1]] best_transition = trellis[num_grams+i-1][prev_states[0]]['prob'] \ + trans[prev_states[0]][state] previous = prev_states[0] for prev_state in prev_states[1:]: trans_prob = trellis[num_grams+i-1][prev_state]['prob'] \ + trans[prev_state][state] if trans_prob > best_transition: best_transition = trans_prob previous = prev_state max_trans_prob = best_transition + emit trellis[num_grams+i].update({state : {'prob' : max_trans_prob, 'prev' : previous, 'key' : key}}) pct = int(round((100. * float(i)) / \ (len(sentence) - len(markov_models) + 1))) sys.stdout.write('\rPercent of sentence decoded: {}%'.format(pct)) sys.stdout.flush() sys.stdout.write('\r ') sys.stdout.flush() # Finds the best message and key pair from the highest probabilities. best_message = [] best_key = [] max_prob = max(state['prob'] for state in trellis[-1].values()) prev_state = None #Finding the most probable final state. for state in trellis[-1].keys(): if trellis[-1][state]['prob'] == max_prob: best_message.append(state[-1]) best_key.append(trellis[-1][state]['key'][-1]) prev_state = state break # Walking along previous states to build the best probability sentence. for i in range(len(trellis) - 2, -1, -1): best_message.insert(0, trellis[i+1][prev_state]['prev'][-1]) prev_state = trellis[i+1][prev_state]['prev'] best_key.insert(0, trellis[i][prev_state]['key'][-1]) message_key = (''.join(best_message), ''.join(best_key)) return message_key def viterbi_unigram(sentence, markov_model): """ Runs through the Viterbi algorithm for a unigram Markov model. Args: sentence: string on which the algorithm is run. markov_model: unigram Markov model to run Viterbi with. Returns: message_key: tuple that contains the message and key. The message is the first and the key is the second. The real message may be the key, but the first is arbitrarily chosen as the message. """ states = list(markov_model[0].keys()) init = markov_model[0] trans = markov_model[1] freqs = markov_model[2] alphabet = list('abcdefghijklmnopqrstuvwxyz') trellis = [{}] # Initialize the Viterbi trellis. for state in states: key = alphabet[(alphabet.index(sentence[0]) \ - alphabet.index(state)) % 26] emit = freqs[state] + freqs[key] trellis[0].update({state : {'prob' : init[state] + emit, 'prev' : None, 'key' : key}}) # Fill the rest of the trellis based on the sentence. for i in range(1, len(sentence)): trellis.append({}) for state in states: best_transition = trellis[i-1][states[0]]['prob'] \ + trans[states[0]][state] previous = states[0] for prev_state in states[1:]: trans_prob = trellis[i-1][prev_state]['prob'] \ + trans[prev_state][state] if trans_prob > best_transition: best_transition = trans_prob previous = prev_state key = alphabet[(alphabet.index(sentence[i]) \ - alphabet.index(state)) % 26] emit = freqs[state] + freqs[key] max_trans_prob = best_transition + emit trellis[i].update({state : {'prob' : max_trans_prob, 'prev' : previous, 'key' : key}}) # Finds the best message and key pair from the highest probabilities. best_message = [] best_key = [] max_prob = max(state['prob'] for state in trellis[-1].values()) prev_state = None #Finding the most probable final state. for state in trellis[-1].keys(): if trellis[-1][state]['prob'] == max_prob: best_message.append(state) best_key.append(trellis[-1][state]['key']) prev_state = state break # Walking along previous states to build the best probability sentence. for i in range(len(trellis) - 2, -1, -1): best_message.insert(0, trellis[i+1][prev_state]['prev']) prev_state = trellis[i+1][prev_state]['prev'] best_key.insert(0, trellis[i][prev_state]['key']) message_key = (''.join(best_message), ''.join(best_key)) return message_key def preprocess(filename, length): """ Reads in sentences from a file and cleans them before converting into the plaintexts/ciphertexts to test and train on. It first reads in sentences and splits into plaintext and keys. It also creates a dict that keeps track of what each sentence initially looks like before it is stripped (sent to lowercase and removal of spaces and punctuation) for later formatting purposes. Args: filename: the path to the file that contains the sentences to be preprocessed. length: the minimum sentence length for each sentence Returns: (plaintext, ciphertext, orig_sentences_dict) The plaintext and ciphertext lists created from the preprocessed data and the dict mapping the scrubbed sentences to their raw form. """ with open(filename,'r') as f: sentences = f.readlines() orig_sentences = {} punctuated_sentences = [''] * len(sentences) whitespace_sentences = [] for n in range(len(sentences)): try: stripped = ''.join(sentences[n].strip('.\n').split(' ')).lower() except: break while len(stripped) < length: try: stripped += ''.join(sentences[n+1].strip('.\n').split(' ')).lower() except: break del sentences[n+1] orig_sentences.update({stripped : sentences[n].strip('\n')}) punctuated_sentences[n] = stripped punctuation_table = str.maketrans(dict.fromkeys(string.punctuation)) whitespace_sentences = [s.translate(punctuation_table) for s in punctuated_sentences] sentences = [re.sub(r'\s+', '', s) for s in whitespace_sentences if s != ''] sentences = [re.sub(r'\\xla', '', s) for s in whitespace_sentences] sentences = [''.join([i for i in s if i.isalpha()]) for s in sentences] sentences = [''.join([i for i in s if not i.isdigit()]) for s in sentences] sentences = [s for s in sentences if s != ''] sentences = set(sentences) plaintext = [sentences.pop() for n in range(int(len(sentences) / 2))] running_key = list(sentences) alphabet = list('abcdefghijklmnopqrstuvwxyz') ciphertext = [] # Generating ciphertext from sentences and running keys. for n in range(len(plaintext)): plain = plaintext[n] key = running_key[n] while len(plain) > len(key): key += key if len(plain) < len(key): key = key[0:len(plain)] crypt = [] for x in range(len(plain)): plain_char = alphabet.index(plain[x]) key_char = alphabet.index(key[x]) crypt.append(alphabet[(plain_char + key_char) % 26]) ciphertext.append(''.join(crypt)) return (plaintext, ciphertext, orig_sentences) def main(): # ---------------------------------------------------------------------------- # Parses commandline arguments that potentially specify the training/testing # corpus paths and the number of ngrams to evaluate on. parser = argparse.ArgumentParser() parser.add_argument("--path", help="path to where training/testing corpus are", default="../docs/") parser.add_argument("--train", help="training text filename", default="brown0000.txt") parser.add_argument("--test", help="testing text filename", default="brown0000.txt") parser.add_argument("--ngrams", help="value of n for ngrams to use", default=2) parser.add_argument("--length", help="minimum plain/ciphertext length", default=100) args = parser.parse_args() # --------------------------------------------------------------------------- # Preprocess training/testing data specified same_corpora = False if args.train == args.test: plaintext, ciphertext, orig_sentences = preprocess(args.path + args.train, args.length) same_corpora = True else: plain_test, cipher_test, orig_sentences_test = preprocess(args.path + args.test, args.length) plain_train, cipher_train, orig_sentences_train = preprocess(args.path + args.train, args.length) # --------------------------------------------------------------------------- # Splitting into training and testing sets. Default partition is 80/20 if same. if same_corpora: train_len = int((len(plaintext) * 4) / 5) plain_train = plaintext[:train_len] plain_test = plaintext[train_len:] cipher_train = ciphertext[:train_len] cipher_test = ciphertext[train_len:] orig_test = {} # Generating all n-grams up to the specified length. alphabet = list('abcdefghijklmnopqrstuvwxyz') n_grams = generate_ngrams(alphabet, args.ngrams) # Creating baseline for comparison, where each letter is just guessed. baseline_acc = 0. baseline_guesses = [] for n in range(len(cipher_test)): sentence = cipher_test[n] baseline_guess = '' for letter in sentence: letter_guess = random.randint(0, 25) baseline_guess = ''.join([baseline_guess, alphabet[letter_guess]]) baseline_guesses.append(baseline_guess) baseline_acc += accuracy(plain_test[n], baseline_guess) filename = 'baseline' print_to_file(baseline_guesses, plain_test, orig_test, filename) baseline_acc /= len(cipher_test) print('Accuracy of baseline: %.5f' % baseline_acc) # Turning each sentence into vectors of n-grams. plain_train_vec = [[] for n in range(len(n_grams))] cipher_train_vec = [[] for n in range(len(n_grams))] plain_test_vec = [[] for n in range(len(n_grams))] cipher_test_vec = [[] for n in range(len(n_grams))] print('\nGetting n-gram vectors from sentences') for n in range(len(n_grams)): for m in range(len(plain_train)): plain_train_vec[n].extend(vectorize(plain_train[m], n_grams[n], n+1)) cipher_train_vec[n].extend(vectorize(cipher_train[m], n_grams[n], n+1)) for m in range(len(plain_test)): plain_test_vec[n].extend(vectorize(plain_test[m], n_grams[n], n+1)) cipher_test_vec[n].extend(vectorize(cipher_test[m], n_grams[n], n+1)) # Testing multinomial Naive Bayes. print('\nTesting multinomial Naive Bayes') naive_bayes = MultinomialNB() for n in range(len(plain_train_vec)): cipher = np.array(cipher_train_vec[n]).reshape(-1, 1) plain = np.array(plain_train_vec[n]).reshape(-1, 1).ravel() naive_bayes.fit(cipher, plain) test = np.array(cipher_test_vec[n]).reshape(-1, 1) predict = naive_bayes.predict(test).tolist() predictions = [] nb_accuracy = 0. for sentence in plain_test: sentence_length = len(sentence) prediction = predict[:sentence_length-n] str_predict = devectorize(prediction, n_grams[n]) predictions.append(str_predict) nb_accuracy += accuracy(sentence, str_predict) nb_accuracy /= len(plain_test) print('Accuracy of %d-gram Naive Bayes: %.5f' % ((n+1), nb_accuracy)) filename = 'naive_bayes_%d-grams' % (n+1) #print_to_file(predictions, plain_test, orig_test, filename) # Testing logistic regression. print('\nTesting logistic regression') log_reg = LogisticRegression() for n in range(len(plain_train_vec)): cipher = np.array(cipher_train_vec[n]).reshape(-1, 1) plain = np.array(plain_train_vec[n]).reshape(-1, 1).ravel() log_reg.fit(cipher, plain) test = np.array(cipher_test_vec[n]).reshape(-1, 1) predict = log_reg.predict(test).tolist() predictions = [] lr_accuracy = 0. for sentence in plain_test: sentence_length = len(sentence) prediction = predict[:sentence_length-n] str_predict = devectorize(prediction, n_grams[n]) predictions.append(str_predict) lr_accuracy += accuracy(sentence, str_predict) lr_accuracy /= len(plain_test) print('Accuracy of %d-gram logistic regression: %.5f' % ((n+1), lr_accuracy)) filename = 'logistic_regression_%d-grams' % (n+1) #print_to_file(predictions, plain_test, orig_test, filename) # Testing support vector machine. print('\nTesting support vector machine') svm = LinearSVC() for n in range(len(plain_train_vec)): cipher = np.array(cipher_train_vec[n]).reshape(-1, 1) plain = np.array(plain_train_vec[n]).reshape(-1, 1).ravel() svm.fit(cipher, plain) test = np.array(cipher_test_vec[n]).reshape(-1, 1) predict = svm.predict(test).tolist() predictions = [] svm_accuracy = 0. for sentence in plain_test: sentence_length = len(sentence) prediction = predict[:sentence_length-n] str_predict = devectorize(prediction, n_grams[n]) predictions.append(str_predict) svm_accuracy += accuracy(sentence, str_predict) svm_accuracy /= len(plain_test) print('Accuracy of %d-gram support vector machine: %.5f' % ((n+1), svm_accuracy)) filename = 'svm_%d-grams' % (n+1) #print_to_file(predictions, plain_test, orig_test, filename) print() # Creating the hidden Markov models. hmms_smoothed = get_hmms(plain_train, n_grams) hmms_unsmoothed = get_hmms(plain_train, n_grams, False) # Testing the hidden Markov models with Viterbi. for n in range(len(hmms_smoothed)): print('Running Viterbi on %d-gram Markov models' % (n+1)) smoothed_acc = 0. smoothed_guesses = [] unsmoothed_acc = 0. unsmoothed_guesses = [] for m in range(len(cipher_test)): sentence = cipher_test[m] smoothed_guess = viterbi(sentence, hmms_smoothed[:n+1]) smoothed_guesses.append(smoothed_guess) smoothed_acc += accuracy(plain_test[m], smoothed_guess[0]) unsmoothed_guess = viterbi(sentence, hmms_unsmoothed[:m+1]) unsmoothed_guesses.append(unsmoothed_guess) unsmoothed_acc += accuracy(plain_test[m], unsmoothed_guess[0]) sys.stdout.write('\r') sys.stdout.flush() filename = 'smoothed_HMM_%d-grams' % (n+1) print_to_file(smoothed_guesses, plain_test, orig_test, filename, True) smoothed_acc /= len(cipher_test) print('Accuracy of smoothed %d-gram HMM: %.5f' % ((n+1), smoothed_acc)) filename = 'unsmoothed_HMM_%d-grams' % (n+1) print_to_file(unsmoothed_guesses, plain_test, orig_test, filename, True) unsmoothed_acc /= len(cipher_test) print('Accuracy of unsmoothed %d-gram HMM: %.5f' % ((n+1), unsmoothed_acc)) print() if __name__ == '__main__': main()
62faa56ee8c2d7916a03b304a1351da410594347
eldanielh31/FiguritasTurtle
/Figuras/Pentagono.py
389
3.703125
4
from turtle import Turtle class Pentagono: def __init__(self, lado): self.lado = lado def getLado(self): return self.lado def setLado(self, nuevoLado): self.lado = nuevoLado def construir(self, tortuga): for _ in range(5): tortuga.pencolor("yellow") tortuga.forward(self.lado) tortuga.left(72)
58e444e06552672f0b021fd573532350d906332b
D-cyber680/100_Days_Of_Code_Python
/NATO+Phonetic+Alphabet+for+the+Code+Exercise/main.py
647
4.25
4
# Keyword Method with iterrows() # {new_key:new_value for (index, row) in df.iterrows()} import pandas data = pandas.read_csv("nato_phonetic_alphabet.csv") #TODO 1. Create a dictionary in this format: phonetic_dict = {row.letter: row.code for (index, row) in data.iterrows()} print(phonetic_dict) #TODO 2. Create a list of the phonetic code words from a word that the user inputs. var_hand = True while var_hand: word = input("Enter a word: ").upper() try: output_list = [phonetic_dict[letter] for letter in word] except: print("Thats not a valid word") else: var_hand = False print(output_list)
4617e499f9a78bdbb6bdb53d689670d7baa9a1ba
iscorgis/GH_BK_Exercises_PY
/POO/Kata_4.py
1,310
3.546875
4
class Animal(): #Properties __especie = '' __peso = 0 __altura = 0.0 #methods def __init__(self,especie,peso,altura): self.__especie = especie self.__peso = peso self.__altura = altura #getters / setters #Investigar decoradores def get_especie(self): pass def get_peso(self): pass def get_altura(self): pass def set_especie(self,especie): self.__especie = especie def set_peso(self,peso): self.__peso = peso def set_altura(self,altura): self.__altura = altura def comer(self): print('Estoy comiendo') def cazar(self): print('Voy a dormir') def dormir(self): print('Voy a dormir') class Leon(Animal): def __init__(self,altura, peso): super().__init__('Leon',altura,peso) class Mascota(): __nombre = '' __dueño = '' def __init__(self,nombre, dueño): self.__nombre = nombre self.__dueño = dueño def sentarse(self): print('Me siento') class Perro(Animal,Mascota): def __init__(self,nombre,dueño,altura, peso): Animal.__init__('Perro', altura, peso) Mascota.__init__(nombre,dueño) Kali = Perro('Kali','Manu',0.5,25) Kali.cazar() Kali.sentarse() print()
9dfdc5b761da0dbf85be87240836f6ff58fcd573
ajwwlswotjd/2020_python_class
/ex8.py
497
3.71875
4
# 구구단 게임[2단계] # 1. 구구단 문제를 출제하기 위해, 숫자 2개를 랜덤하게 저장한다. # 2. 저장된 숫자를 토대로 구구단 문제를 출력한다. # 예) 3 x 7 = ? # 3. 문제에 해당하는 정답을 입력받는다. # 4. 정답을 비교 "정답" 또는 "땡"을 출력한다. import random as rnd num1 = rnd.randint(1,9) num2 = rnd.randint(1,9) if int(input("%d x %d = ? : " % (num1,num2))) == num1 * num2 : print("정답") else : print("땡")
bff98681a315080fbad6f15850919540c3d2921d
malachyo/BFS
/uniqueinorder.py
598
3.859375
4
# def unique_in_order(sequence): # pos = 0 # newstr = "" # for x in sequence: # pos += 1 # x = pos # if x == pos-1: # newstr = sequence.replace(x, "") # # print(newstr) # # # unique_in_order('AAABCBDBAABDBDCC') def unique_in_order(sequence): sequence = " ".join(sequence) list = sequence.split() print(list) for x in list: if list.index(x) + 1 == list.index(x): list.remove(x) elif list.index(x) - 1 == list.index(x): list.remove(x) print(list) unique_in_order('AAABCBDBAABDBDCC')
ff33ee4666ea407b79984cbdf73248c8bdf2343d
DongliangGao/DoubanMovieSpider
/douban/mysql.py
1,828
3.515625
4
# -*- coding:utf-8 -*- import MySQLdb class MySQL: ''' 数据库操作:连接、建表、插入数据 ''' def __init__(self): try: self.db = MySQLdb.connect('localhost', 'root', 'password', 'douban', charset = 'utf8') try: self.cur = self.db.cursor() except MySQLdb.Error, e: print '获取操作游标失败%d:%s' % (e.args[0], e.args[1]) except MySQLdb.Error, e: print '连接数据库失败%d:%s' % (e.args[0], e.args[1]) def createTable(self, db, cursor): ''' 建立数据表:doubanmovie :param db: 数据库 :param cursor: 游标 :return: ''' try: cursor.execute('DROP TABLE IF EXISTS DOUBANMOVIE;') sql = ''' CREATE TABLE DOUBANMOVIE( NAME VARCHAR(200) NOT NULL, DIRECTOR VARCHAR(200), ACTOR VARCHAR(200), YEARS VARCHAR(50) NOT NULL, COUNTRY VARCHAR(100), CATEGORY VARCHAR(100), RATING FLOAT NOT NULL, QUOTE VARCHAR(200) ); ''' cursor.execute(sql) except MySQLdb.Error, e: db.rollback() print '创建数据表失败%d:%s' % (e.args[0], e.args[1]) def insertData(self, dic): ''' 传入字典,根据字典内容,插入数据 :param dic: 包含数据的字典 :return: ''' cols = ', '.join(dic.keys()) values = '", "'.join(dic.values()) sql = 'INSERT INTO DOUBANMOVIE (%s) VALUES (%s);' % (cols, '"'+values+'"') try: self.cur.execute(sql) except MySQLdb.Error, e: print '插入数据失败%d:%s' % (e.args[0], e.args[1])
d46abce1ecd81fa8ae33512baa111758db16b3e7
hello-wangjj/Introduction-to-Programming-Using-Python
/chapter10/10.18.py
958
3.765625
4
def main(): queens=8*[-1] queens[0]=0 k=1 while k>=0 and k <=7: # Find a position to place a queen in the kth row j = findPosition(k,queens) if j < 0: queens[k] = -1 k -= 1 # back track to the previous row else: queens[k] = j k += 1 printResult(queens) def findPosition(k,queens): start=0 if queens[k]==-1 else (queens[k]+1) for j in range(start,8): if isValid(k,j,queens): return j return -1 def isValid(k,j,queens): for i in range(k): if queens[i]==j: return False row=k-1 column=j-1 while row>=0 and column>=0: # pass if queens[row]==column: return False row-=1 column-=1 return True def printResult(queens): for i in range(8): print(str(i) + ", " + str(queens[i])) print() # Display the output for i in range(8): for j in range(queens[i]): print("| ", end = "") print("|Q|", end = "") for j in range(queens[i] + 1, 8): print(" |", end = "") print() main()
9177ad9cb2ef06f9b520edd715f000185b15be5a
FruitSenpai/Genesis
/GenesisProgram/Scripts/Graph/admix/AdmixGroup.py
926
3.84375
4
class AdmixGroup: """Stores Group attributes as well as all individuals belonging to the group.""" name = "" orderInGraph = 0 dominance = 1 def __init__(self, name, order): """Initializes an AdmixGroup object along with its properties.""" self.name = name self.orderInGraph = order self.dominance = 1 #initialize to 1 because the initialization of this group implies that at least one individual exists in this group self.individuals = [] #list of individuals belonging to this group self.hidden = False def setOrder(self, order): """Set the order of appearance of this group in the graph.""" self.orderInGraph = order def setDominance(self, dom): """Set the dominance(population) of this group.""" self.dominance = dom def setGroupHidden(self, hide): """Set the visibility of this group and its individuals""" self.hidden = hide for person in self.individuals: person.setHidden(hide)
f6a4164191417772d3f382dc19774a1334e2df02
Ishaangg/python-projects
/radius_of_circle.py
101
3.75
4
radius = 20 area = radius * radius * 3.142 print("the area of circle of radius", radius, "is", area)
98c6216fec9a4e06a88210d5c376708d0f6b124f
techmexdev/Networking
/udp_server.py
674
3.5
4
from socket import * server_port = 3000 # create UDP socket server_socket = socket(AF_INET, SOCK_DGRAM) # bind socket to local port server_socket.bind(('localhost', server_port)) print(f'UDP server ready on port {server_port}... ') while True: # read from UDP socket we just created # 4096 is reccomended buffer size: https://docs.python.org/3/library/socket.html#socket.socket.recv message, client_address = server_socket.recvfrom(4096) print(f'received message {message} from {client_address}') reply = message.decode().upper() print(f'sending message {reply} to {client_address}\n') server_socket.sendto(reply.encode(), client_address)
2de1c25685595bd71474cd33ec96024fa07fa572
nisarbasha/pythonClass
/Day1/math_class.py
486
3.5625
4
import math x = abs(-7.25) print(x) print("***************") x = pow(5, 3) print(x) print("***************") x = math.sqrt(49) print(x) print("***************") x = math.ceil(1.8) y = math.floor(1.4) print(x) print(y) print("***************") x = math.pi print(x) print("***************") print(math.isclose(50, 100, abs_tol=40)) c = float(input("enter your percentage")) x = math.isclose(c, 1.9, abs_tol=0.2) if x: print("magesh selected") else: print("Not Selected")
2ac6b46be7824d70a827399b7f2e6ad7f5f69c08
cebarrales/quartic_rxn
/test.py
1,427
3.703125
4
#!/usr/bin/python3 ''' This module calls the quartic_rxn function that found the optimized coefficient of the equation a*x**4 + b*x**3 + c*x**2. It requires the activation energy and the reaction energy of the chemical reaction. Example ------- Consider a reaction which has an activation energy of 25 kcal/mol and a reaction energy of -40 kcal/mol. The function must be called as: a,b,c = quarticrxn(25,-40) On the other hand the quartic_plot function allows to obtain a plot of the energy profile from the optimized a, b and c. If you want to save a plot image, you need to specify when the function is called. A png file will be saved. The name of the .png file must be specified when function is called. This is the default Else, the plot will be showed in the screen. This is the default. Example ------- If we want to save a file called reaction1.png we must call the function in that way: quartic_plot(a,b,c,'reaction1','save') If we only want to see the profile, we don not to specify anything, because the default is no_save. quartic_plot(a,b,c,'reaction1') ''' from sympy import * from quartic_rxn_opt import quarticrxn from quartic_rxn_opt import quartic_plot a, b, c = quarticrxn(25,-10) quartic_plot(a,b,c,'example','save')
30205406b140cd4504f698014acc58a3272e2f00
callmexss/Python_Crash_Course
/Chapter4/times_of_3.py
241
3.546875
4
# -*- coding: utf-8 -*- # @Author: callmexss # @Date: 2018-06-01 00:25:02 # @Last Modified by: callmexss # @Last Modified time: 2018-06-01 00:25:47 numbers = [n for n in range(3, 31, 3)] for number in numbers: print(number)
690c6c92d4831ef103d775da2b3c8809983b1393
Ferosima/Python_Lab
/5-Laba/3.py
12,355
3.8125
4
# 12. Вивести значення цілочисельного виразу, заданого у вигляді рядка S. Вираз визначається наступним чином: # <Вираз> :: = <цифра> | <Вираз> + <цифра> | <Вираз> - <цифра> # получился прикольный калькулятор, который может строить деревья from tkinter import * root = Tk() w, h = 800, 800 canv = Canvas(root, width=w, height=h, bg='white') list_symbol_one = ['*', '/'] list_symbol_two = ['+', '-', ] list_all_symbol = ['+', '-', '*', '/', ] def operation(a, b, c=int): b = int(b) c = int(c) if a == '+': return b + c elif a == '-': return b - c elif a == '*': return b * c elif a == '/': return b / c class TreeNode: def __init__(self): self.data = "" self.left = None self.right = None # ініціалізуються зв’язки вузла, # так як дерево бінарне, то # можливі тільки 2 дочірні вузла def initNode(self, left, right): self.left = left self.right = right # встановлюються деякі дані вузла def set_data(self, data): self.data = data def leftNode(self, n): if isinstance(self.left, TreeNode): print(n) return self.left.leftNode(n + 1) else: return self.data def Cal(self): if isinstance(self.left, TreeNode) and isinstance(self.right, TreeNode): print("Call r") self.right = self.right.Cal() print(self.right, "r") print("Call l") self.left = self.left.Cal() print(self.left, "l") return operation(self.data, self.left, self.right) elif isinstance(self.left, TreeNode): self.left = self.left.Cal() return operation(self.data, self.left, self.right) elif isinstance(self.right, TreeNode): self.right = self.right.Cal() print(self.right, "ri") return self.right elif self.left == None: self.left = 0 elif self.right == None: self.right == 0 else: print(operation(self.data, self.left, self.right)) return operation(self.data, self.left, self.right) # return operation(self.data, self.left, self.right) def call(self): if isinstance(self.left, TreeNode): if self.data == "": self.data = self.left.data self.left = self.left.call() # print(self.data, 'data') # print(self.left, 'left') # need stop if isinstance(self.right, TreeNode): # print(self.right.left) if self.data == "": self.data = self.right.data self.right = self.right.call() # print(self.data, 'data') # print(self.right, "right") if self.left == None: # if list_symbol_one.count(self.data)==1: # self.left=1 # else: self.left = 0 if self.right == None: # if list_symbol_one.count(self.data)==1: # self.right=1 # else: self.right = 0 if self.data == "": self.data = "+" # print(self.right, 'r.e') # print(self.left, 'l.e') # print(self.data, 'd.e') # print(operation(self.data, self.left,self.right)) # need stop return operation(self.data, self.left,self.right) def is_number(str): try: float(str) return True except ValueError: return False def str_to_TreeNode(a, x, y): b = TreeNode() start = 0 end = 0 check = 0 brackets1 = [] brackets2 = [] true = 0 ####delete ()########################################################################################################### for i in range(len(a)): if a[i] == '(': brackets1.append(i) if a[i] == ')': brackets2.append(i) for n in range(len(brackets1)): if n != len(brackets1) - 1: if brackets1[n + 1] < brackets2[n]: true += 1 if len(brackets1) == len(brackets2) and len(brackets1) == 1: true = 1 if true == len(brackets1) and a[0] == '(' and a[len(a) - 1] == ')': a = a[1:len(a) - 1] # print(a) #####check is it number?################################################################################################ if is_number(a): canv.create_text(x, y, font=("Purisa", 20), text=a) return a #####check operation + or -############################################################################################# for i in range(len(a)): # check +- if a[i] == '(': if check == 0: start = i + 1 check += 1 continue if check == 0: if list_symbol_two.count(a[i]) == 1: end = i b.data = a[i] # print(b.data, 'data') canv.create_text(x, y, font=("Purisa", 20), text=b.data) if i > 0 and a[i - 1] != ')': b.left = a[start:end] # print(b.left, 'left+-') canv.create_line(int(x), int(y), int(x - 25), int(y + 25), fill='black') canv.create_text(x - 25, y + 25, font=("Purisa", 20), text=b.left) # print(b.left,"left") # if i + 1 <= len(a) - 1 and a[i + 1] == '(': # b.right = srt_to_TreeNode(a[end:len(a) - 1], x + 50, y + 50) # else: if a[i + 1] != '(': n = 0 for n in range(i + 1, len(a)): if list_all_symbol.count(a[n]) == 1: n += 1 if n > 0: canv.create_line(int(x), int(y), int(x + 25), int(y + 25), fill='black') # print(a[end + 1:len(a)], 'right+-') b.right = str_to_TreeNode(a[end + 1:len(a)], x + 25, y + 25) canv.create_text(x, y, font=("Purisa", 20), text=a[i]) # canv.create_text(x + 25, y + 25, font=("Purisa", 20), text=a[end + 1:len(a)]) else: b.right = a[end + 1:len(a)] canv.create_line(int(x), int(y), int(x + 25), int(y + 25), fill='black') canv.create_text(x + 25, y + 25, font=("Purisa", 20), text=b.right) return b # print(b.right,"right") else: # print(a[end + 1:len(a)], 'right+-') b.right = str_to_TreeNode(a[end + 1:len(a)], x + 25, y + 25) canv.create_line(int(x), int(y), int(x + 25), int(y + 25), fill='black') return b if a[i] == ')': # новая ветка check -= 1 # print(a[start:end],"check") end = i if check == 0: if i < len(a) - 1 and list_all_symbol.count(a[i + 1]) == 1: # print(a[start:end], "left()") b.left = str_to_TreeNode(a[start:end], x - 50, y + 50) canv.create_line(int(x), int(y), int(x - 50), int(y + 50), fill='black') b.data = a[i + 1] canv.create_text(x, y, font=("Purisa", 20), text=b.data) # print(a[end + 2:len(a)], "right.etc") b.right = str_to_TreeNode(a[end + 2:len(a)], x + 50, y + 50) canv.create_line(int(x), int(y), int(x + 50), int(y + 50), fill='black') return b # else: # print(a[start:end], "right") # b.right = str_to_TreeNode(a[start:end], x, y) # print(a[start:end]) # print(b.right.right,"rr",b.right) # return b # if b.right == None and a[i] != ')': # b.right = a[start:len(a)] # canv.create_text(x, y, font=("Purisa", 20), text=b.right) # return b #############check operation * or /##################################################################################### start = 0 check = 0 for n in range(len(a)): if a[n] == '(': if check == 0: start = n + 1 check += 1 continue if a[n] == ')': # новая ветка check -= 1 # print(a[start:end], "check",n) end = n if check == 0: if list_symbol_one.count(a[n]) == 1: end = n # print(a[start:end]) for i in range(n + 1, len(a)): if a[i] == '(': if check == 0: pass # start = n + 1 check += 1 # print(check, "check+") # print(start, 'start') continue if a[i] == ')': # новая ветка check -= 1 # end = i # print(a[0:end], "check1", n) if check == 0: if list_symbol_two.count(a[i]) == 1 or list_symbol_one.count(a[i]) == 1: # end=i # print(a[start:i], "lF.w") # print(a[i + 1:len(a)], "rF.w") # print(a[i], 'dF.w') b.left = str_to_TreeNode(a[start:i], x - 50, y + 50) # canv.create_text(x - 25, y + 25, font=("Purisa", 20), text=a[start:i]) canv.create_line(int(x), int(y), int(x - 50), int(y + 50), fill='black') b.right = str_to_TreeNode(a[i + 1:len(a)], x + 50, y + 50) # canv.create_text(x + 25, y + 25, font=("Purisa", 20), text=a[i+1:len(a)]) canv.create_line(int(x), int(y), int(x + 50), int(y + 50), fill='black') b.data = a[i] canv.create_text(x, y, font=("Purisa", 20), text=b.data) return b # print(a[n + 1:len(a)], "rF") # print(a[n], 'dF') if a[n - 1] == ')': # print(a[start:n - 1], "lF") b.left = str_to_TreeNode(a[start:n - 1], x - 25, y + 25) # canv.create_text(x - 25, y + 25, font=("Purisa", 20), text=a[start:n-1]) else: # print(a[start:n], "lF", len(a[start - 1:n])) b.left = str_to_TreeNode(a[start:n], x - 25, y + 25) canv.create_text(x - 25, y + 25, font=("Purisa", 20), text=a[start:n]) canv.create_line(int(x), int(y), int(x - 25), int(y + 25), fill='black') # print(a[start:n], "lF") b.right = str_to_TreeNode(a[n + 1:len(a)], x + 25, y + 25) # canv.create_text(x + 25, y + 25, font=("Purisa", 20), text=a[n + 1:len(a)]) canv.create_line(int(x), int(y), int(x + 25), int(y + 25), fill='black') # print(a[n + 1:len(a)], "rF") b.data = a[n] canv.create_text(x, y, font=("Purisa", 20), text=b.data) return b return b #a = "(1+-1)*(1*1)" a=input("Вводите, пожайлуста, без лишних скобокб и не забывайте их закрывать,\nотрицательные числа берите в скобки(так должно работать лучше)\n") #a="1+2*(3-4)" c = str_to_TreeNode(a, 400, 300) if isinstance(c, TreeNode): print(c.call()) print("я там даже дерево построил), откройте tk") else: print(c) canv.pack() root.mainloop()
e6389ecd5757d8a0e31712b93044ba54038f8527
LiuY-ang/leetCode-Medium
/addTwoNumber.py
941
3.65625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p1,p2=l1,l2 ans=ListNode(-1) p,carry=ans,0 while p1 and p2: s=p1.val+p2.val+carry t=ListNode(s%10) carry=s/10 p.next=t p,p1,p2=p.next,p1.next,p2.next while p1: s=p1.val+carry t=ListNode(s%10) p.next=t carry=s/10 p,p1=p.next,p1.next while p2: s=p2.val+varry t=ListNode(s%10) p.next=t carry=s/10 p,p2=p.next,p2.next if carry==1: t=ListNode(1) p.next=t return ans.next
ebbc23f2fa8882c9aeed4180a09fd7e6b0a8fcef
mikwit/adventofcode
/mikwit/all_2019/day1/numberadder.py
544
3.8125
4
def file_summator(input_file="", current_number=0): in_file = open(input_file, "r") total = current_number for line in in_file: total += int(line) return(total) # input_file = open("input.txt", "r") # # print(input_file.read()) # # for line in input_file.read(): # # print (line) # current_number = 0 # for line in input_file: # # print (line) # # print(int(line)) # current_number += int(line) # # print(current_number) # return(current_number) print(file_summator("input.txt", 0))
c9b1f744ac5d3c0904e40d278ceddd9a399159e0
JozeeLin/learn-AI
/deep-learning-nn/nn/AddLayer.py
1,140
3.65625
4
from MulLayer import MulLayer class AddLayer(object): def forward(self, x,y): out = x+y return out def backward(self, dout): dx = dout * 1 dy = dout * 1 return (dx, dy) if __name__ == '__main__': apple = 100 apple_num = 2 orange = 150 orange_num = 3 tax = 1.1 mul_apple_layer = MulLayer() mul_orange_layer = MulLayer() add_sum_layer = AddLayer() mul_tax_layer = MulLayer() #forward apple_price = mul_apple_layer.forward(apple, apple_num) orange_price = mul_orange_layer.forward(orange, orange_num) sum_price = add_sum_layer.forward(apple_price, orange_price) price = mul_tax_layer.forward(sum_price, tax) #backward dprice = 1 dsum_price, dtax = mul_tax_layer.backward(dprice) dapple_price,dorange_price = add_sum_layer.backward(dsum_price) dorange,dorange_sum = mul_orange_layer.backward(dorange_price) dapple, dapple_sum = mul_apple_layer.backward(dapple_price) print dprice print dsum_price, dtax print dapple_price, dorange_price print dorange, dorange_sum print dapple, dapple_sum
23738de02206fa48b61549f11cfeefb8fbf4b713
M01eg/gb_python_basics
/homework2/task2.py
1,042
4.4375
4
''' Урок 2 Задание 2 Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). ''' def task2(): superlist = [] n = int(input("Введите количество элементов в вашем списке: ")) for i in range(n): superlist.append(input(f"Введите элемент {i+1}: ")) for i in range(0, n // 2 * 2, 2): superlist[i], superlist[i+1] = superlist[i+1], superlist[i] print("После обмена элементов мы получили следующий список:") print(superlist) if __name__ == "__main__": task2()
ce82e84ed062cf7f69e117e065d479496847fa08
ES2Spring2019-ComputinginEngineering/final-project-final-megabrett
/EnergyandPopulationData.py
1,740
3.5
4
# Getting Energy Usage/Person import matplotlib.pyplot as plt def createEnergyandCityLists(): cities = [] city_energy = [] pop = [] energy_per_person = [] file = open("Monthly-Electricity-Consumption-for-Major-US-Cities.csv") split_character = ',' for line in file: data_line = line.split(split_character) # split each line cities.append(data_line[0]) # add first element, name of city, in order city_energy.append(float(data_line[1])) # add second element, energy usage of city (in gigawatts), in order data_line[2] = data_line[2].strip("\n") # get rid of \n character on end of each element pop.append(float(data_line[2])) # add third element, population (millions of people), in order file.close() i = 0 # counter while i < len(city_energy): energy = city_energy[i] population = pop[i]*1000000 # gives exact population en_use_per_person = (energy/population)*1000 # gives energy use per person in megawatts energy_per_person.append(en_use_per_person) i += 1 return cities, city_energy, pop, energy_per_person #cities, city_energy, pop, energy_per_person = createEnergyandCityLists() def graphEnergyData(cities, city_energy, energy_per_person): x = 0,1,2,3,4,5,6,7,8,9,10,11,12,13 plt.figure(figsize=(15, 5)) plt.bar(x, energy_per_person, align='center', tick_label=cities) xlabel = plt.xlabel("Cities") xlabel.set_color("red") ylabel = plt.ylabel("Energy Use/Person (MegaWatts)") ylabel.set_color("red") title = plt.title("Energy Usage per Person in Major Cities") title.set_color("green") plt.show() #graphEnergyData(cities, city_energy, energy_per_person)
e6c77231dc9e30066fb48dceae1f625eca6d8077
conwayjj/AdventOfCode2020
/day2/day2_2.py
622
3.75
4
def validatePassword(password): words = password.split() lower, upper = words[0].split('-') lower = int(lower) upper = int(upper) character = words[1][0] pw = words[2] if (pw[lower-1] == character) ^ (pw[upper-1] == character): return True else: return False with open("""C:\\tmp\\adventCode\\2020\\day2\\input.txt""") as inFile: lines = inFile.readlines() validPasswords = 0 invalidPasswords = 0 for line in lines: if validatePassword(line): validPasswords += 1 else: invalidPasswords += 1 print("VALID: ", validPasswords) print("INVALID: ", invalidPasswords)
740f57265dfb7da255f81c2e133bb128664c021a
liseyko/CtCI
/leetcode/p0073 - Set Matrix Zeroes.py
2,253
3.5
4
class Solution: def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ if not matrix: return m, n = len(matrix), len(matrix[0]) rows, cols = set(), set() for j in range(m): for i in range(n): if matrix[j][i] == 0: rows.add(j) cols.add(i) for j in range(m): for i in range(n): if i in cols or j in rows: matrix[j][i] = 0 def setZeroes(self, matrix): if not matrix: return self.m, self.n = len(matrix), len(matrix[0]) def zerofy(x,y): for j in range(self.m): if matrix[j][x] == 0 and j != y: zerofy(x, j) matrix[j][x] = None for i in range(self.n): if matrix[y][i] == 0 and i != x: zerofy(i, y) matrix[y][i] = None for j in range(self.m): for i in range(self.n): if matrix[j][i] == 0: zerofy(i,j) for j in range(self.m): for i in range(self.n): if matrix[j][i] == None: matrix[j][i] = 0 def setZeroes(self, matrix): if not matrix: return self.n, self.m = len(matrix), len(matrix[0]) row1 = col1 = True for j in range(self.n): if matrix[j][0] == 0: col1 = False; break for i in range(self.m): if matrix[0][i] == 0: row1 = False; break for j in range(1, self.n): for i in range(1, self.m): if matrix[j][i] == 0: matrix[0][i] = 0 matrix[j][0] = 0 for j in range(1, self.n): if matrix[j][0] == 0: matrix[j] = [0] * self.m if not col1: matrix[0][0] = 0 for i in range(self.m): if matrix[0][i] == 0: for j in range(1, self.n): matrix[j][i] = 0 if not row1: matrix[0] = [0] * self.m
66e931c63e3981bc905e98763d22b20489038bcf
zzz686970/leetcode-2018
/476_findComplement.py
158
3.578125
4
def findComplement(num): result = "".join(["1" if char=='0' else "0" for char in str('{0:b}'.format(num))]) return int(result, 2) print(findComplement(5))
71dabf4442d9d2ec64b93e56318a25937bfeef8f
gloria-aprilia/Programming-Practice
/Python/Algorithm Practice/E6_ListTuple.py
120
3.578125
4
data = input("Please enter a set of number(, to separate): ") print(list(data.split(","))) print(tuple(data.split(",")))
9ed00b9b8e991c345f0c69635da3df7695141d2c
uohzxela/fundamentals
/sorting/sort_list.py
1,061
3.921875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head slow, fast, pre_slow = head, head, None while fast and fast.next: pre_slow = slow slow = slow.next fast = fast.next.next pre_slow.next = None return self.merge(self.sortList(head), self.sortList(slow)) def merge(self, left, right): curr = dummy = ListNode(0) while left and right: if left.val <= right.val: curr.next = left left = left.next else: curr.next = right right = right.next curr = curr.next if left: curr.next = left if right: curr.next = right return dummy.next
417619e07c467dcbe6ba12ce794441aeb86aafd1
pranaymate/pythonExercises-1
/easy/housePassword.py
962
4.0625
4
# The password will be considered strong enough # if its length is greater than or equal to 10 symbols, # it has at least one digit, # as well as containing one uppercase letter and one lowercase letter in it. # The password contains only ASCII latin letters or digits. def password_validator(data): if len(data) >= 10: digit = None lower = None upper = None for x in data: if x.isdigit(): digit = True elif x.islower(): lower = True elif x.isupper(): upper = True if digit and lower and upper is True: return True return False print(password_validator('A1213pokl')) # False print(password_validator('bAse730onE')) # True print(password_validator('asasasasasasasaas')) # False print(password_validator('QWERTYqwerty')) # False print(password_validator('123456123456')) # False print(password_validator('QwErTy911poqqqq')) # True
4120ab747229be6cf1b73fbd66acfc1eebee5a9d
gabrieltemtsen/My-First-Github-Project
/My first Github Program.py
2,035
4.15625
4
def gpa(): courses = int(input("How many courses have you offered so far:")) course_limit = 0 wgp = 0 total_credit = 0 for numbers in range(course_limit, courses): print ("Enter score for course ", numbers+1) score = int(input()) print("Enter Credit Unit for course: ", numbers+1) credit_unit = int(input()) if score >= 70 and score <= 100: grade = 5 wgp += credit_unit * grade total_credit += credit_unit elif score >= 60 and score <= 69: grade = 4 wgp += credit_unit * grade total_credit += credit_unit elif score >= 50 and score <= 59: grade = 3 wgp += credit_unit * grade total_credit += credit_unit elif score >= 45 and score <= 49: grade = 2 wgp += credit_unit * grade total_credit += credit_unit elif score >= 40 and score <= 44: grade = 1 wgp += credit_unit * grade total_credit += credit_unit elif score >= 0 and score <= 39: grade = 0 wgp += credit_unit * grade total_credit += credit_unit else: print("Sorry oo! start again") gpa = wgp / total_credit if gpa >= 4.5: print("Congratulations your Gpa is " + str(gpa) + " You are a first Class") if gpa >= 3.5 and gpa <= 4.44: print("Congratulations your Gpa is " + str(gpa) + " You are a second class upper student") if gpa >= 2.5 and gpa <= 3.49: print("Congratulations your Gpa is " + str(gpa) + " You are a second class lower student") if gpa >= 1.5 and gpa <= 2.49: print("Congratulations your Gpa is " + str(gpa) + " You are a Third class student") if gpa >= 0 and gpa <= 1.49: print("Sorry your Gpa is " + str(gpa) + " You are a last lower student") gpa() # dict = () # counts = dict # print(type(counts))
0dbf71b6b636441d19bf294a4cc28b9f45647228
Sandr0x00/algorithms
/hilbert_curve/__init__.py
928
3.53125
4
#!/usr/bin/env python3 class HilbertCurve: def __init__(self, n): self.n = n # convert (x,y) to d def xy2d (self, x, y): s = self.n // 2 d = 0 while s > 0: rx = (x & s) > 0 ry = (y & s) > 0 d += s * s * ((3 * rx) ^ ry) x, y = self.rot(self.n, x, y, rx, ry) s //= 2 return d # convert d to (x,y) def d2xy(self, d): x = y = 0 t = d s = 1 while s < self.n: rx = 1 & (t // 2) ry = 1 & (t ^ rx) x, y = self.rot(s, x, y, rx, ry) x += s * rx y += s * ry t //= 4 s *= 2 return y, x # rotate/flip a quadrant appropriately def rot(self, n, x, y, rx, ry): if ry: return x, y if rx: x = n - 1 - x y = n - 1 - y return y, x
32ff6068d538d9b5f124f31ba619a85a43fe8d9b
anurpa/bioinformatics_scripts
/adaptor_finder.py
1,528
3.796875
4
#import required modules from Bio import SeqIO import argparse #Define a function to count frequencies of substrings in a FASTQ file def find_adaptors(args): """ Get frequencies of substrings of length k across all sequences in a fastq file(f). Args: f: FASTQ file k: length of substring Returns: Substrings and counts, sorted by counts """ #Initiate a dictionary, to hold substrings as key and count as values kmers={} #Loop over each sequence in fastq file for record in SeqIO.parse(args.f, "fastq"): #Retrieve and save raw sequence line as variable seq seq=record.seq #Pull out substring of required length from sequence for i in range(len(seq) - args.k + 1): kmer = seq[i:i+args.k] #If substring already exists, increase count if kmer in kmers: kmers[kmer] += 1 #If substring is new, store new key else: kmers[kmer] = 1 #Print substrings and counts, sorted by values(counts) for s in sorted(kmers, key=kmers.get, reverse=True): print (s, kmers[s]) #Parse arguments from command line if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-k",action="store",dest="k",type=int, help="length of substring",required=True) parser.add_argument("-f",action="store",dest="f", help="fasta file",required=True) args = parser.parse_args() find_adaptors(args)
66e70a0f6d81628973c082f97258ac829c2e3baf
nmasamba/learningPython
/22_dict.py
776
4.5625
5
""" Author: Nyasha Pride Masamba Based on the lessons from Codecademy at https://www.codecademy.com/learn/python This Python program shows an example of using the dictionary (dict) data structure. It is useful to think of dictionaries as key:value pairs, so in that sense a dict record can be indexed by its key. They are immutable data types. """ my_dict = { "name": "Hinde Moni", "ID": 344, "Saying": "Hail Mary!" } print my_dict.keys() print my_dict.values() for key in my_dict: print key, my_dict[key]
0f6d8b9be2d07d8f03b5c1fa946a1debf97b003a
ezioitachi/Big-Data
/Coursera-Algorithms&Data/AlgorithmicToolbox/week2/fibonacci_last_digit.py
210
3.578125
4
# Uses python3 n = int(input()) def Fibo(n): F = [None]*(n+2) F[0] = 0 F[1] = 1 if n <=1: return F[n] else: for i in range(2,n+1): F[i] = (F[i-1] + F[i-2]) % 10 return F[n] print(Fibo(n))
7a982d495a0e21a0bbdb83b7c6586c36b875504f
yunzhuz/code-offer
/second/23.py
1,698
3.53125
4
class node(): def __init__(self,data): self.data = data self.next = None def xunzhao(head): if not head.next or not head.next.next: return None meetingnode = panduan(head) if meetingnode == None: return None pcount = meetingnode.next count = 1 while pcount != meetingnode: pcount = pcount.next count +=1 p1 = head p2 = meetingnode for i in range(count): p2 = p2.next while p1 != p2: p1 = p1.next p2 = p2.next return p1 def panduan(head): pslow = head.next pfast = head.next.next while pfast and pfast.next != None and pfast != pslow: pslow = pslow.next pfast = pfast.next.next if not pfast: return None return pfast ### 方法2 不用统计环中节点个数 class Solution: def EntryNodeOfLoop(self, head): if not head.next or not head.next.next: return None p1 = head p2 = self.panduan(head) if not p2: return None while p1 != p2: p1 = p1.next p2 = p2.next return p1 def panduan(self,head): pslow = head.next pfast = head.next.next while pfast and pfast.next != None and pfast != pslow: pslow = pslow.next pfast = pfast.next.next if not pfast or not pfast.next: return None return pfast if __name__ == '__main__': n1 = node(1) n2 = node(2) n3 = node(3) n4 = node(4) n5 = node(5) n6 = node(6) n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 n6.next = n3 print(xunzhao(n1).data)
22e06236be3cba4637cba74806c11581f1de5d8c
radhikaluvani/repo
/daily-programs/20200823/list.py
123
3.640625
4
a = [1,5,7,8,10,12,23,25,60,89] b = int(input("enter number: ")) c = [] for i in a: if i < b: c.append(i) print(c)
80cd0654162b9d29d3ed43ee3829ff31449b1bb5
timManas/PythonProgrammingRecipes
/project/src/ObjectOrientedConcepts/ChangingClassMembersExample/ChangingClassMembersExample.py
1,500
3.5625
4
# from project.src.ObjectOrientedConcepts.ChangingClassMembersExample.CSStudent import * # This works from project.src.ObjectOrientedConcepts.ChangingClassMembersExample import CSStudent # This doesent work ? def main(): student1 = CSStudent("Tim", 12345) student2 = CSStudent("John", 346) student3 = CSStudent("Romero", 233424234234234) #Print Student Stream print("Stream of Student1: ", student1.stream) print("Stream of Student2: ", student2.stream) print("Stream of Student3: ", student3.stream) # Changing the member of the Class by referring to the CLASS NAME directly CSStudent.stream = "Mathematics" #Print Student Stream print("\nStream of Student1: ", student1.stream) print("Stream of Student2: ", student2.stream) print("Stream of Student3: ", student3.stream) # Now we only want Student#3 to be back to BIOLOGY student3.stream = "BIOLOGY" #Print Student Stream print("\nStream of Student1: ", student1.stream) print("Stream of Student2: ", student2.stream) print("Stream of Student3: ", student3.stream) pass if __name__ == '__main__': main() ''' Theres going to be instances when we want to change the static members for ALLLLLLL the classes If we want to change the instance of all the object which REFER to that class - We must use the CLASS NAME instead of the object name But if we want to change individual objects - Then we must use the individual object name member '''
e0c6493f0d3602baa8e812108f88d786829a3324
brantheman60/Old-Python-Projects
/Pyzo/15-112/Week 4/Sorting Algorithms.py
2,632
4.3125
4
# https://www.cs.cmu.edu/~adamchik/15-121/lectures/Sorting%20Algorithms/sorting.html import random, time def bubbleSort(arr): # compares adjacent elements for i in reversed(range(0, len(arr))): for j in range(1,i+1): if arr[j-1] > arr[j]: temp = arr[j-1] arr[j-1] = arr[j] arr[j] = temp print("Bubble Sort: ", arr) def selectionSort(arr): # moves the minimum value to the start for i in range(len(arr)): min = i for j in range(i+1, len(arr)): if arr[j] < arr[min]: min = j temp = arr[i] arr[i] = arr[min] arr[min] = temp print("Selection Sort: ", arr) def insertionSort(arr): # inserts element in right place compared to previous elements for i in range(1,len(arr)): index = arr[i] j = i while j > 0 and arr[j-1] > index: arr[j] = arr[j-1] j -= 1 arr[j] = index print("Insertion Sort: ", arr) def merge(a, start1, start2, end): index1 = start1 index2 = start2 length = end - start1 aux = [None] * length for i in range(length): if ((index1 == start2) or ((index2 != end) and (a[index1] > a[index2]))): aux[i] = a[index2] index2 += 1 else: aux[i] = a[index1] index1 += 1 for i in range(start1, end): a[i] = aux[i - start1] def mergeSort(a): n = len(a) step = 1 while (step < n): # merge two adjacent groups of size 2, then of size 4, then 8, ... for start1 in range(0, n, 2*step): start2 = min(start1 + step, n) end = min(start1 + 2*step, n) merge(a, start1, start2, end) step *= 2 def createArr(length): return random.sample(range(1,100), length) def testSortingAlgorithms(): newArr = createArr(6) # assume none are the same print("Shuffled:\t\t", newArr, "\n") # Bubble Sort - 0(n^2) arr = newArr time0 = time.time() bubbleSort(arr) time1 = time.time() print((time1-time0)/1000, " s") # Selection Sort - 0(n^2) arr = newArr time0 = time.time() selectionSort(arr) time1 = time.time() print((time1-time0)/1000, " s") # Insertion Sort - 0(n^2) arr = newArr time0 = time.time() insertionSort(arr) time1 = time.time() print((time1-time0)/1000, " s") # Merge Sort - 0(n ln x) arr = newArr time0 = time.time() mergeSort(arr) time1 = time.time() print((time1-time0)/1000, " s") testSortingAlgorithms()
0599927cfb7aa1db9b996f4d09935e07eedc43b4
NJT145/my_github_repository_Python
/PyCharm_Projects/CS_372_01/Lecture_codes/code_week4/graph2.py
1,737
3.859375
4
class Node: def __init__(self, label): self.label=label self.neighbors=[] def __str__(self): temp_str=str(self.label) + ": " for node in self.neighbors: temp_str+=node.label + " " return temp_str def addNeighbor(self, node): self.neighbors.append(node) def deleteNeighbor(self,node): try: self.neighbors.remove(node) except ValueError: print "Node %s : %s is Invalid Neighbor" % (self.label, node.label) class Graph: def __init__(self): self.graph=dict() def addNode(self, label): if label in self.graph: print 'Node %s exists!!!' % label else: self.graph[label]=Node(label) def addNeighbor(self,node,neighbor): if node not in self.graph: self.addNode(node) if neighbor not in self.graph: self.addNode(neighbor) self.graph[node].addNeighbor(self.graph[neighbor]) def deleteNeighbor(self,node,neighbor): if node not in self.graph: print 'Node %s does not exist!!!' % node else: self.graph[node].deleteNeighbor(self.graph[neighbor]) def printGraph(self): for node in self.graph: print self.graph[node] graph1=Graph() graph1.printGraph() graph1.addNode('A') graph1.addNode('B') graph1.addNode('C') graph1.addNode('D') graph1.addNode('E') graph1.addNeighbor('A', 'C') graph1.addNeighbor('D', 'E') graph1.addNeighbor('B', 'C') graph1.addNeighbor('A', 'E') graph1.addNeighbor('C', 'D') graph1.printGraph() graph1.deleteNeighbor('F', 'D') graph1.printGraph()
438ddb8d0c98ed24f5ac2758a40a57e7023f1f5f
Wainhouse/DFESW3
/w3_exercises.py
2,467
4.21875
4
# 1) Write a Python function to find the Max of three numbers. # def max_of_two(x, y): # if x > y: # return x # return y # def max_of_three(x, y, z): # return max_of_two(x, max_of_two(y, z)) # print(max_of_three(-5, 4, 8)) # 2)Write a Python function to sum all the numbers in a list. # def sum_all(nums): # total = 0 # for i in nums: # total += i # return total # print(sum((4, 6, 399, 4, 3))) # 3) Write a Python function to multiply all the numbers in a list. # def multi_all(nums): # total = 1 # for i in nums: # total *= i # return total # print(multi_all((2, 3))) # 4) Write a Python program to reverse a string. # ample String : "1234abcd" # def reverse(string): # for i in string: # return string[::-1] # print(reverse("Luke")) # 5 Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number as an argument. # 6 Write a Python function to check whether a number falls in a given range. # def rang(num, x, y): # if num in range(x, y): # return("yes") # else: # return("no") # print(rang(200, 0, 100)) # 7 Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters. # Sample String : 'The quick Brow Fox' # Expected Output : # No. of Upper case characters : 3 # No. of Lower case Characters : 12 # def count_up(word): # countUp = 0 # for i in word: # if i.isupper(): # countUp += 1 # return countUp # def count_low(word): # countLow = 0 # for i in word: # if i.islower(): # countLow += 1 # return countLow # countUp = count_up("I am A BanANa") # countLow = count_low("I am A BanANa") # print("I am A BanANa") # print("No. of Upper case characters :", countUp) # print("No. of Upper case characters :", countUp) # 8) Write a Python function that takes a list and returns a new list with unique elements of the first list # def uni_lst(lst): # i = [] # for a in lst: # if a not in i: # i.append(a) # return i # print(uni_lst([45, 46, 34, 45, 23, 56, 34, 23, 45])) # 9) ite a Python function that takes a number as a parameter and check the number is prime or not. Go to the editor # Note : A prime number (or a prime) is a natural number greater than 1 and that has no positive divisors other than 1 and itself.
df373658afcfffc5036a9c06a3e85cdab1ae4fce
DidiMilikina/DataCamp
/Machine Learning Scientist with Python/22. Machine Learning with PySpark/02. Classification/07. Evaluate the Decision Tree.py
1,494
4.09375
4
''' Evaluate the Decision Tree You can assess the quality of your model by evaluating how well it performs on the testing data. Because the model was not trained on these data, this represents an objective assessment of the model. A confusion matrix gives a useful breakdown of predictions versus known values. It has four cells which represent the counts of: True Negatives (TN) — model predicts negative outcome & known outcome is negative True Positives (TP) — model predicts positive outcome & known outcome is positive False Negatives (FN) — model predicts negative outcome but known outcome is positive False Positives (FP) — model predicts positive outcome but known outcome is negative. Instructions 100 XP Create a confusion matrix by counting the combinations of label and prediction. Display the result. Count the number of True Negatives, True Positives, False Negatives and False Positives. Calculate the accuracy. ''' SOLUTION # Create a confusion matrix prediction.groupBy('label', 'prediction').count().show() # Calculate the elements of the confusion matrix TN = prediction.filter('prediction = 0 AND label = prediction').count() TP = prediction.filter('prediction = 1 AND label = prediction').count() FN = prediction.filter('prediction = 0 AND label != prediction').count() FP = prediction.filter('prediction = 1 AND label != prediction').count() # Accuracy measures the proportion of correct predictions accuracy = (TN + TP) / (TN + TP + FN + FP) print(accuracy)