blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
6a59184a4ae0cee597a190f323850bb706c09b11
BreeAnnaV/CSE
/BreeAnna Virrueta - Hangman.py
730
4.3125
4
import random import string """ A general guide for Hangman 1. Make a word bank - 10 items 2. Pick a random item from the list 3. Add a guess to the list of letters guessed Hide the word (use *) (letters_guessed = [...]) 4. Reveal letters already guessed 5. Create the win condition """ guesses_left = 10 word_bank = ["Environment", "Xylophone", "LeBron James", "Kobe", "Jordan", "Stephen Curry", "Avenue", "Galaxy", "Snazzy", "The answer is two"] word_picked = (random.choice(word_bank)) letters_guessed = [] random_word = len(word_picked) # print(word_picked) guess = '' correct = random.choice while guess != "correct": guess = () for letter in word_picked: if letter is letters_guessed: print()
392caa19570274c18bfbdffd11430f6a1180ef44
renard162/personal_library
/general/csvmanager.py
7,025
3.59375
4
# -*- coding: utf-8 -*- # %% """ Funções para manipular arquivos de texto contendo dados. """ import numpy as np import csv def csv_export(file_name, *lists, titles=None, separator='\t', decimal_digit='.', number_format='sci', precision=10): """ Função para salvar em arquivo de texto os dados de listas ou arrays. Args: file_name (string): Nome do arquivo que será criado ou sobrescrito. Ex.: 'arquivo.txt' *lists (múltiplas 1D-lists ou uma única list-lists): Listas ou arrays que formarão as colunas do arquivo de saída. Múltiplas listas ou arrays podem ser fornecidas desde que todas possuam o mesmo número de elementos. Esta forma de utilização facilita exportar dados simples. Caso seja fornecida uma lista de listas, essa deve ser fornecida única. A função não suporta múltiplas listas de listas. Esta forma de utilização facilita exportar dados em grandes quantidades, gerados em massa e organizados proceduralmente. titles (string-list, optional): Lista de strings que serão o título das colunas de dados. Opcional de ser fornecido mas, caso seja fornecido, deve conter o mesmo número de elementos que o número de listas fornecidas. separator (string, optional): Defaults to TAB ('\t'). Caractere que delimitará as colunas de dados e, caso seja fornecido, os títulos das colunas. Por padrão adota-se o TAB como separador, porém, se for necessária compatibilidade com algum editor de planilhas (Excel, por exemplo) em Pt-Br, NÃO utilize vírgula (',') como separador, pois estes softwares reconecem a vírgula como separador de casas decimais. decimal_digit (string, optional): Defaults to '.'. Caractere que separará os valores decimais de elementos numéricos. Caso não seja fornecido, adota-se o padrão internacional de separar os dígitos decimais por ponto, por motivo de compatibilidade com outros softwares. Caso deseja-se compatibilizar o aqruvo com qualquer editor de planilha (Excel, por exemplo) que esteja no padrão Pt-Br, utilizar ',' (vírgula) como separador decimal. Este caractere deve ser diferente do delimitador de colunas 'separator' para evitar conflitos. number_format (string, optional): Defaults to 'sci'. Formato dos dados numéricos de saída. Valores válidos são: - 'sci' -> Padrão científico (1,000E00). - 'dec' -> Padrão decimal (1,000). - Qualquer string diferente das anteriores farão os dados numéricos serem salvos como o padrão do python. precision (int, optional): Defaults to 10. Número de casas decimais utilizados em dados numéricos. Exemplo de uso 1 (múltiplas listas 1D fornecidas): Dadas as variáveis: I1 = [1.32, 2.65, 8.6, 0.7, 5.731] Vo = [12.0, 10.1, 14.68, 9.8, 7.99] Deseja-se salvar estes dados em arquivo CSV chamado "dados.csv" para utilizar em Excel Pt-Br com os títulos "Corrente de entrada" e "Tensão de saída", assim, define-se os títulos: titulos = ['Corrente de entrada', 'Tensão de saída'] Aplica-se estes valores na função: csv_export('dados.csv', I1, Vo, titles=titulos, decimal_digit=',') Exemplo de uso 2 (Lista de listas única fornecida): Dada a matriz de dados: M = [[0.25, 0.6, 0.15], [35, 42, 15]] Onde os dados da primeira lista representa "Rendimento" e da segunda lista representa "Temperatura", deseja-se salvar estes dados em arquivo "experimento.dat" para ser utilizado em Excel Pt-Br com as colunas devidamente nomeadas e separadas por ";". Então cria-se o vetor de títulos das colunas: titulos = ['Rendimento', 'Temperatura'] Então executa-se a função: csv_export('experimento.dat', M, titles=titulos, separator=';', decimal_digit=',') """ #Checagem do tipo de entrada: #n-listas: dimensions = 2 #lista de listas: dimensions = 3 dimensions = np.array(lists, dtype=object).ndim if dimensions == 3: lists = lists[0] #Checagem dos títulos (caso fornecidos) if (titles != None): if (np.sum([isinstance(x, str) for x in titles]) != len(titles)): raise Exception('Todos os títulos devem ser Strings!') if (len(titles) != len(lists)): raise Exception('O número de títulos é diferente do número de '\ 'listas fornecidas!') #Checagem de conflito entre separador decimal e delimitador de colunas. if (separator == decimal_digit): raise Exception('O caractere delimitador de colunas \'separator\' '\ 'deve ser diferente do caractere separador decimal '\ '\'decimal_digit\'!') #Como é esperado que o número de amostras seja muito, muito maior que o #número de listas, excutar a checagem da validade das listas antes de #processar seus elementos aumenta o desempenho do código. data_length = len(lists[0]) for data in lists: if (len(data) != data_length): raise Exception('Todos os vetores de dados devem ter o mesmo tamanho!') #Montagem da matriz de dados str_format = '{:.' + str(precision) if (number_format == 'sci'): str_format += 'e}' elif (number_format == 'dec'): str_format += 'f}' else: #Vetores numéricos tratados como vetores genéricos str_format = 'generic' data_matrix = [] for data in lists: try: #Vetor numérico if (str_format == 'generic'): raise Exception() data = np.array(data, dtype=float) temp_data = [str_format.format(x).replace('.', decimal_digit) \ for x in data] except: #Vetor genérico temp_data = [str(x) for x in data] finally: #Finalmente mesmo.... ufa data_matrix.append(temp_data) data_matrix = np.array(data_matrix).T.tolist() #Escrita no arquivo #Depois de tanto malabarismo para ajustar os dados e fazer os dumb checks, #já estava na hora de finalmente fazer o que a função deve fazer... with open(file_name, 'w', newline='') as file: writer = csv.writer(file, delimiter=separator) if (titles != None): writer.writerow(titles) for line in data_matrix: writer.writerow(line)
a7fa12618849376c1bbc3655b9ee4e1d0061477c
gugunm/test-kumparan
/model-v2.py
5,249
3.796875
4
""" Kumparan's Model Interface This is an interface file to implement your model. You must implement `train` method and `predict` method. `train` is a method to train your model. You can read training data, preprocess and perform the training inside this method. `predict` is a method to run the prediction using your trained model. This method depends on the task that you are solving, please read the instruction that sent by the Kumparan team for what is the input and the output of the method. In this interface, we implement `save` method to helps you save your trained model. You may not edit this directly. You can add more initialization parameter and define new methods to the Model class. Usage: Install `kumparanian` first: pip install kumparanian Run python model.py It will run the training and save your trained model to file `model.pickle`. """ # library of kumparan from kumparanian import ds # sastrawi library, using for stopword removal from Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory # library to create tf-idf from sklearn.feature_extraction.text import TfidfTransformer # library to create words count vectorize from sklearn.feature_extraction.text import CountVectorizer # library to split data from sklearn.model_selection import train_test_split # library to remove punctuation in every content from nltk.tokenize import RegexpTokenizer # accuracy metrics to evaluate prediction from sklearn.metrics import accuracy_score # library to learn model using Support Vector Machine from sklearn.svm import SVC # library to read data import pandas as pd class Model: def __init__(self): """ You can add more parameter here to initialize your model """ # initialize the variable for count_vectorizer function self.count_vect = CountVectorizer() # initialize the variable for tf-idf function self.tfidf_transformer = TfidfTransformer() # initialize SVM classifier method self.svm_clf = SVC(kernel = 'linear', C = 1) def train(self): """ NOTE: Implement your training procedure in this method. """ # read data.csv using pandas and drop nan data = pd.read_csv("data.csv").dropna() # get article_content and transform to list contents = data["article_content"].values.tolist() # get article_topic and transform to list topics = data["article_topic"].values.tolist() # import library to tokenize and remove punctuation tokenizer = RegexpTokenizer(r'\w+') # stopword removal for bahasa indonesia stopword = StopWordRemoverFactory().create_stop_word_remover() # list to save clean contents clean_contents = list() # looping the contents, and preprocess for each content for content in contents: # case folding the sentence to be lowcase lowcase_word = content.lower() # remove stopword from the content stop_word = stopword.remove(lowcase_word) # tokenize the content sentence_token = tokenizer.tokenize(stop_word) # initialize a list for clean token clean_tokens = list() for token in sentence_token: # append token to the list after lower it clean_tokens.append(token) # transform a token to be sentence sentence = " ".join(clean_tokens) + '' # append clean sentence clean_contents.append(sentence) # count vectorizer X_train_counts = self.count_vect.fit_transform(clean_contents) # create tfidf from count vectorizer X_train_tfidf = self.tfidf_transformer.fit_transform(X_train_counts) # split data to train and test set > test 10%, train 90% X_train, X_test, y_train, y_test = train_test_split(X_train_tfidf, topics, test_size=0.1) # train a model self.svm_clf.fit(X_train, y_train) # prediction for x_test prediction = self.svm_clf.predict(X_test) # model accuracy for x_test accuracy = accuracy_score(y_test, prediction) # print accuracy print(accuracy) def predict(self, input): """ NOTE: Implement your predict procedure in this method. """ # put the input (string) into a list input_test = list(input) # count vectorize of input_test vocabulary new_counts = self.count_vect.transform(input_test) # create tf-idf for input test new_tfidf = self.tfidf_transformer.transform(new_counts) # get a prediction label label = self.svm_clf.predict(new_tfidf)[0] return label def save(self): """ Save trained model to model.pickle file. """ ds.model.save(self, "model.pickle") if __name__ == '__main__': # NOTE: Edit this if you add more initialization parameter model = Model() # Train your model model.train() # try to predict article_topic = model.predict("article_content") print(article_topic) # Save your trained model to model.pickle model.save()
6f3f133dbbc8fc6519c54cc234da5b367ee9e80d
stark276/Backwards-Poetry
/poetry.py
1,535
4.21875
4
import random poem = """ I have half my father's face & not a measure of his flair for the dramatic. Never once have I prayed & had another man's wife wail in return. """ list_of_lines = poem.split("\n") # Your code should implement the lines_printed_backwards() function. # This function takes in a list of strings containing the lines of your # poem as arguments and will print the poem lines out in reverse with the line numbers reversed. def lines_printed_backwards(list_of_lines): for lines in list_of_lines: list_of_lines.reverse() print(list_of_lines) def lines_printed_random(list_of_lines): """Your code should implement the lines_printed_random() function which will randomly select lines from a list of strings and print them out in random order. Repeats are okay and the number of lines printed should be equal to the original number of lines in the poem (line numbers don't need to be printed). Hint: try using a loop and randint()""" for lines in list_of_lines: print(random.choice(list_of_lines)) def my_costum_function(list_of_lines): """"Your code should implement a function of your choice that rearranges the poem in a unique way, be creative! Make sure that you carefully comment your custom function so it's clear what it does.""" # IT's going to delete the last line for lines in list_of_lines: list_of_lines.pop() print(list_of_lines) lines_printed_backwards(list_of_lines) lines_printed_random(list_of_lines) my_costum_function(list_of_lines)
79e2e4cb5ee662ca24a0a2e9154b5f5c5837cc60
akhan7/fss16groupG
/code/5/maxwalksat.py
4,532
3.765625
4
from __future__ import print_function import copy import random def r(a=0, b=1): return random.randint(a, b) class Osyczka: """ Utility class to solve the Osyczka2 equation """ def min_max(self, tries): """ Args: tries: number of tries / iterations Returns: A tuple of the minimum and absolute maximum of Osyczka2 function """ i = 0 min = float('inf') max = float('-inf') while i < tries: x = self.rand_list() if self.constraints(x): oval = self.osyczka(x) if oval < min: min = oval if oval > max: max = oval i += 1 return min, max def get_threshold(self, g_min, g_max, tries): """ Args: g_min: Min Value (found from min_max()) g_max: Max Value (found from min_max()) tries: Number of iterations Returns: Normalized threshold value averaged over "tries" number of iterations """ i = 0 aggregate_diff = 0 while i < tries: min, max = self.min_max(1000) if min > g_min and max < g_max: aggregate_diff += self.get_normalized(min, g_min, g_max) i += 1 return aggregate_diff / float(tries) def get_normalized(self, x, g_min, g_max): """ Args: x: Value to be normalized g_min: Min value g_max: Max value Returns: Normalized value of x """ return ((x) - g_min) / float(g_max - g_min) def osyczka(self, x): """ Args: x: Independent variable Returns: value of Osyczka function at x """ return self.__f1(x) + self.__f2(x) def constraints(self, x): """ Args: x: List of 6 elements representing Returns: True if the contraints pass, False otherwise. """ return self.__g1(x) >= 0 and self.__g2(x) >= 0 and self.__g3(x) >= 0 and self.__g4(x) >= 0 \ and self.__g5(x) >= 0 and self.__g6(x) >= 0 def rand_list(self): """ Returns: A random list of 6 integers """ return [r(0, 10), r(0, 10), r(1, 5), r(0, 6), r(1, 5), r(0, 10)] def __f1(self, x): return -(25 * pow(x[0] - 2, 2) + pow(x[1] - 2, 2) \ + pow(x[2] - 1, 2) * pow(x[3] - 4, 2) + pow(x[4] - 1, 2)) def __f2(self, x): sum = 0 for i in xrange(len(x)): sum = sum + pow(x[i], 2) return sum def __g1(self, x): return x[0] + x[1] - 2 def __g2(self, x): return 6 - x[0] - x[1] def __g3(self, x): return 2 - x[1] + x[0] def __g4(self, x): return 2 - x[0] + 3 * x[1] def __g5(self, x): return 4 - pow(x[2] - 3, 2) - x[3] def __g6(self, x): return pow(x[4] - 3, 3) + x[5] - 4 class MaxWalkSat: @staticmethod def solve(max_tries): o = Osyczka() # Get min and max over thousand tries g_min, g_max = o.min_max(1000) print("The global min,max for normalization : ", g_min, g_max) # Get threshold over 10 tries (Internally uses min_max(1000)) # threshold = o.get_threshold(g_min, g_max, 10) threshold = 0.06; print("Stopping condition (threshold) : ", threshold) solution = o.rand_list() while not o.constraints(solution): solution = o.rand_list() for i in xrange(max_tries): # print(solution) if o.constraints(solution) and o.get_normalized(o.osyczka(solution), g_min, g_max) < threshold: return ("SUCCESS", solution, o.osyczka(solution),i) c = r(0, 5) if 0.5 < random.random(): solution[c] = o.rand_list()[c] else: # Throw away solution prev_solution = copy.deepcopy(solution) solution = o.rand_list() while not o.constraints(solution) and o.get_normalized(o.osyczka(solution), g_min, g_max) < o.get_normalized( o.osyczka(prev_solution), g_min, g_max): solution = o.rand_list() return ("FAILURE", solution, o.osyczka(solution),i) if __name__ == '__main__': print(MaxWalkSat.solve(1000))
da6af0c09f54f044d89eaa17ab549f219deb006b
akhan7/fss16groupG
/code/6/decision.py
325
3.515625
4
class Decision: """ Class indicating Decision of a problem """ def __init__(self, name, low, high): """ @param name: Name of the decision @param low: minimum value @param high: maximum value """ self.name = name self.low = low self.high = high
7069fe6daf6fe7091471a9e4220569d58e9fcbe3
GWANGHYUNYU/Python_Tutorial
/quiz01.py
632
3.671875
4
# Quiz) 변수를 이용하여 다음 문장을 출력하시오. # # 변수명 : station # # 변수값 : "사당", "신도림", "인천공항" 순서대로 입력 # # 출력 문장 : xx 행 열차가 들어오고 있습니다. # station = ["사당", "신도림", "인천공항"] # for i in station: # print(i, "행 열차가 들어오고 있습니다.") station = "사당" print("{} 행 열차가 들어오고 있습니다.".format(station)) station = "신도림" print("{} 행 열차가 들어오고 있습니다.".format(station)) station = "인천공항" print("{} 행 열차가 들어오고 있습니다.".format(station))
2ffa4f8025d643ad0b58f3a2f0bb30e0eec22a65
yilia13516877583/-git
/thread_lock.py
402
3.53125
4
""" 线程锁演示 """ from threading import Thread,Lock lock = Lock() # 锁对象 a = b = 0 def value(): while True: lock.acquire() if a != b: print("a = %f,b = %f"%(a,b)) lock.release() t = Thread(target=value) t.start() while True: with lock: # 上锁 a += 0.1 b += 0.1 # with语句块结束自动解锁 t.join()
36eae5a4a0f55d15e6105e24fa7d4d64a1009b2e
YatreeLadani/CompetitiveProgramming
/LeetCode/4_Valid_Anagram.py
254
3.671875
4
def validanagram(s,t): if (1 <= len(s) and 1 <= len(t)) or (len(s) <= 5 * (10**4) and len(t) <= 5 * (10**4)): if sorted(s)==sorted(t): print("True") else: print("Flase") validanagram("rat", "art")
f356e0847e22fda7ce2621790bc4be4939f8037b
hasanahmed-eco/space-man
/**SPACEMAN FINAL**.py
2,077
4.03125
4
import random # change the guess array NameError # To DO: # 1) Ensure user doesn't enter a value twice letterCount = 0 word_list = [ "apple", "banana", "education", "house", "fridge", "game", "aaaaaaaab" ] print("--------------------") print("----SPACEMAN 2.0----") print("--------------------") def setUpGame(): lives = 6 word = word_list[random.randint(0, len(word_list)) - 1] previouslyGuessedLetters = [] guess = [] for i in range(0, len(word)): guess.append("_") return lives, word, guess, previouslyGuessedLetters # CHANGE GUESS GUESS ARRAY TO A DIFFERENT NAME def Game(): lives, word, guess, previouslyGuessedLetters = setUpGame() run = True while (run==True and letterCount != len(word)): printArray(guess) playerGuess = getUserInput() isLetterInWord = checkLetter(word, playerGuess) if(playerGuess in previouslyGuessedLetters): print("You have already guessed this letter") else: if(isLetterInWord): guess = updateGuess(word, playerGuess, guess) else: lives = lives - 1 if(lives == 0): run = False else: print("\nYou guessd the letter wrong, you have {} lives remaining".format(lives)) previouslyGuessedLetters.append(playerGuess) if(letterCount == len(word)): print("Well done, you have guessed the word correctly!") else: print("\nYou have ran out of lives, the word was {}".format(word)) def printArray(guess): for letter in guess: print(letter, end=" ") print('\n') def getUserInput(): playerGuess = input("Please enter a letter: ") return playerGuess def checkLetter(word, letter): if letter in word: return True else: return False def updateGuess(word, userGuess, guess): count = 0 for letter in word: if letter == userGuess: guess[count] = letter global letterCount letterCount = letterCount + 1 count = count + 1 return guess Game()
ad87297b334864c573301f0aab7e1cbba65d5d33
usf-cs-spring-2019-anita-rathi/110-project-constellation-jychan4
/projectconstellationV5.py
2,092
3.796875
4
#Yew Journ Chan #May 30, 2019 #Version 5 import turtle #Starting with Point Alnitak turtle.hideturtle() #this command hides arrow symbols identified as "turtle" turtle.dot(10) #indicating the point starting at Alnitak turtle.write("Alnitak") #label point "Alnitak" #Point Betelgeuse turtle.left(110) #pivoting towards direction of point Betelgeuse turtle.forward(320) #distance between point Alnitak and point Betelgeuse turtle.dot(10) #indicating point Betelgeuse turtle.write("Betelgeuse") #label point "Betelgeuse" turtle.penup() #lift pen to prevent drawing when retracing steps turtle.backward(320) #retracing steps back to point "Alnitak" #Point Saiph turtle.pendown() #pen down to begin drawing again turtle.left(135) #pivoting left towards direction of point Saiph turtle.forward(250) #distance between point Alnitak and point Saiph turtle.dot(10) #indicating point Saiph turtle.write("Saiph") #label point "Saiph" #Point Alnilam turtle.penup() #lift pen to prevent drawing when retracing steps turtle.backward(250) #retracing steps back to point Alnitak turtle.pendown() #pen down to start drawing again turtle.left(140) #pivoting left to point Alnilam turtle.forward(70) #distance between point Alnitak and point Alnilam turtle.dot(10) #indicating point Anilam turtle.write("Alnilam") #label point "Alnilam" #Point Mintaka turtle.forward(70) #distance between point Alnilam and point Mintaka turtle.dot(10) #indicating point Mintaka turtle.write("Mintaka") #lavel point "Mintaka" #Point Meissa turtle.left(50) #pivoting left to point Meissa turtle.forward(250) #distance between point Mintaka and point Meissa turtle.dot(10) #indicating point Meissa turtle.write("Meissa") #label point "Meissa" #Point Rigel turtle.penup() #lift pen to prevent drawing when retracing steps turtle.backward(250) #retracing steps back to point Mintaka turtle.pendown() #pen down to start drawing again turtle.right(150) #pivoting right to point Rigel turtle.forward(240) #distance between point Mintaka and point Rigel turtle.dot(10) #indicating point Rigel turtle.write("Rigel") #label point "Rigel"
4afcb0749886f9c8807b970405d13d3a4993721c
tkf/compapp
/src/compapp/descriptors/links.py
3,978
3.5
4
from ..core import private, Descriptor def countprefix(string, prefix): w = len(prefix) n = len(string) i = 1 while i < n and string[i * w: (i+1) * w] == prefix: i += 1 return i class Link(Descriptor): """ "Link" parameter. It's like symbolic-link in the file system. Examples -------- >>> from compapp.core import Parametric >>> class MyParametric(Parametric): ... x = 1 ... broken = Link('..') ... ... class nest(Parametric): ... x = 2 ... l0 = Link('') ... l1 = Link('x') ... l2 = Link('..x') ... l3 = Link('.nest.x') ... broken = Link('..broken') ... ... class nest(Parametric): ... x = 3 ... l0 = Link('') ... l1 = Link('x') ... l2 = Link('..x') ... l3 = Link('.nest.x') ... broken = Link('..broken') ... >>> par = MyParametric() >>> par is par.nest.l0 is par.nest.nest.l0 True >>> par.nest.l1 1 >>> par.nest.l2 1 >>> par.nest.l3 3 >>> par.nest.nest.l1 1 >>> par.nest.nest.l2 2 >>> par.nest.nest.l3 Traceback (most recent call last): ... AttributeError: 'nest' object has no attribute 'l3' >>> hasattr(par, 'broken') False >>> hasattr(par.nest, 'broken') False >>> hasattr(par.nest.nest, 'broken') False .. todo:: Should `path` use more explicit notation as in the JSON pointer? That is to say, use ``'#'`` instead of ``''`` (an empty string) to indicate the root. Then, for example, ``'x'`` would be written as ``'#.x'``. """ def __init__(self, path, adapter=None, **kwds): super(Link, self).__init__(**kwds) self.path = path self.adapter = adapter def get(self, obj): if self.path.startswith('.'): i = countprefix(self.path, '.') start = obj for _ in range(i - 1): start = private(start).owner if start is None: return self.default restpath = self.path[i:] else: restpath = self.path start = private(obj).getroot() value = start for part in restpath.split('.') if restpath else []: try: value = getattr(value, part) except AttributeError: return self.default if self.adapter: value = self.adapter(value) return value class Root(Link): """ An alias of ``Link('')``. """ def __init__(self, **kwds): super(Root, self).__init__('', **kwds) class Delegate(Link): """ Delegate parameter to its owner. ``x = Delegate()`` is equivalent to ``x = Link('..x')``. Examples -------- >>> from compapp.core import Parametric >>> class Parent(Parametric): ... ... class nest1(Parametric): ... sampling_period = Delegate() ... ... class nest2(Parametric): ... sampling_period = Delegate() ... ... sampling_period = 10.0 ... >>> par = Parent() >>> par.sampling_period 10.0 >>> par.nest1.sampling_period 10.0 >>> par.nest2.sampling_period 10.0 >>> par.sampling_period = 20.0 >>> par.nest1.sampling_period 20.0 """ def __init__(self, **kwds): super(Delegate, self).__init__(None, **kwds) def get(self, obj): # FIXME: This is a bit hacky implementation (communicating by # mutating shared namespace). Need refactoring. self.path = '..' + self.myname(obj) return super(Delegate, self).get(obj) class MyName(Descriptor): def get(self, obj): return private(obj).myname class OwnerName(Descriptor): def get(self, obj): return private(private(obj).owner).myname
e42694efe84f29d3cb96dda98e8793d7613256c0
david-singh/Log-Analysis
/reportingtool.py
3,203
3.609375
4
# ! /usr/bin/env python3 import psycopg2 # What are the most popular three articles of all time? query_1_title = ("What are the most popular three articles of all time?") query_1 = """select articles.title, count(*) as views from articles inner join log on log.path like concat('%',articles.slug,'%') where log.status like '%200%' group by articles.title, log.path order by views desc limit 3""" # Who are the most popular article authors of all time? query_2_title = ("Who are the most popular article authors of all time?") query_2 = """select authors.name, count(*) as views from articles inner join authors on articles.author = authors.id inner join log on log.path like concat('%', articles.slug, '%') where log.status like '%200%' group by authors.name order by views desc""" # On which days did more than 1% of requests lead to errors? query_3_title = ("On which days did more than 1% of requests lead to errors?") query_3 = """select * from error_log_view where \"Percent Error\" > 1""" def option(): """ Provide the options to select from """ print("Welcome") print("Enter your option *_* \n") print("1 : What are the most popular three articles of all time?") print("2 : Who are the most popular article authors of all time?") print("3 : On which days did more than 1% of requests lead to errors?\n") while True: opt = int(input("Enter : ")) if opt < 1 or opt > 3: print("Please Choose between the three options") continue else: break return opt def connection(): """Connect to the PostgreSQL database. Returns a database connection""" try: db = psycopg2.connect("dbname=news") c = db.cursor() return db, c except: print("Sorry, Unable to connect to Database") def query_results(query): """Return query results for given query """ db, c = connection() c.execute(query) return c.fetchall() db.close() def print_query_results(query_result): """Prints query results for given query """ print ('\n'+query_result[1]) for index, results in enumerate(query_result[0]): print ('> ' + str(results[0]) + ' --- ' + str(results[1]) + ' views') def print_error_results(query_result): """Prints query results for error query """ print ('\n'+query_result[1]) for results in query_result[0]: print ('> ' + str(results[0]) + ' --- ' + str(results[1]) + "% errors") if __name__ == '__main__': opt = option() if opt == 1: # stores the result article_result = query_results(query_1), query_1_title # prints the output print_query_results(article_result) elif opt == 2: # stores the result author_result = query_results(query_2), query_2_title # prints the output print_query_results(author_result) else: # stores the result error_result = query_results(query_3), query_3_title # prints the output print_error_results(error_result)
4c5923e491d8527c4a255746510c568175334701
SamuelNarciso/Analizador_Sintactico
/AnalizadorSintactico/TreeString.py
1,172
3.609375
4
import Tree import alphabet # int v=10 # int v =10 # int v = 10 class Node: def __init__(self, value, alphabet): self.value = value self.alphabet = alphabet class TreeString: def CreateTree(self): alphabets = [ Node(31, [';']), Node(40, alphabet.Alphabet().GenerateLetters()), Node(26, [' ']), Node(29, ['g']), Node(30, ['n']), Node(28, ['i']), Node(24, ['r']), Node(25, ['t']), Node(23, ['S']) ] tree = Tree.Tree() for x in alphabets: tree.root = tree.insert(tree.root, x.value, x.alphabet) return tree def TreeAssign(self): alphabets = [ Node(30, [';']), Node(31, ['"', "'"]), Node(25, alphabet.Alphabet().LetterWithSimbols()), Node(26, ['"', "'"]), Node(23, ['=']), Node(24, [' ']), Node(1, alphabet.Alphabet().GenerateLetters()) ] tree = Tree.Tree() for x in alphabets: tree.root = tree.insert(tree.root, x.value, x.alphabet) return tree
de78a9a1d734acc46b5403c9960f9ea372cfa242
udaypatel83/FirstRepositoryforPython
/Loops1.py
401
3.640625
4
# 1 # 123 # 12345 # 1234567 #123456789 # minline = 1 maxline = 5 i =1 j =5 numprint = 1 str1 = str(numprint) a = 1 b = 2 while minline <= maxline: while j>=i: print (' '*j, end="") print( str1) while a <= b: numprint = numprint +1 str1 = str1 + str(numprint) a=a+1 j= j-1 a=1 minline+=1 print('')
637466a2c1e4300befe7497c5b1b63e530a565a4
edagotti689/PYTHON-13-RANDOM-PREDEFINE-MODULE
/1_ramdom.py
404
4
4
''' 1. random module is predeined module in python used to create a random values. 2. It is used to select a random number or element from a group of elements 3. random module mainly used in games and cryptography ''' import random # random() is used to return a random float number b/w 0 to 1 (0<x<1) l=random.random() print(l) for i in range(10): print(random.random())
472c1086db3decabcded78da1b77b6a67cf6d83b
stereoabuse/euler
/problems/prob_023.py
1,270
3.71875
4
################################################################################ # Project Euler Problem 023 # # https://projecteuler.net/problem=023 # # # # Author: Chris B. # # Date: November 05, 2020 # ################################################################################ def prob_023(n = 28124): ''' Return sum of all positive integers that can NOT be written as the sum of two abundant number https://en.wikipedia.org/wiki/Abundant_number ''' abundant_list, non_sum = [], [] int_list_sum = sum(range(1,n)) double_abundants = set() for i in range(1,n): i_divisor_sum = sum(j for j in range(1, int(i/2) + 1) if i % j == 0) if i_divisor_sum > i: abundant_list.append(i) for x in abundant_list: for y in abundant_list: if y + x < n: double_abundants.add(x + y) return int_list_sum - sum(double_abundants) prob_023()
1f49c039dc9e5d187221cbdeb75992063e20e3b7
zwamdurkel/2wf90-assignment-2
/method/displayField.py
588
3.75
4
# Input: INTEGER mod, POLY modPoly, POLY a # Output: STRING answer, POLY answer-poly # Functionality: Output a representative of the field element of F that represents a, # this means the unique polynomial f of degree less than the degree of q(x) that is congruent to a. # Output f as pretty print string and as POLY. from method.displayPoly import displayPoly from method.longDivPoly import longDivPoly def displayField(mod, modPoly, a): x = longDivPoly(mod, a, modPoly)[3] return displayPoly(mod, x)[0], x #FINNEAN
a13982d0e87fa36afa55de7d25ab68a4eab07847
zwamdurkel/2wf90-assignment-2
/method/divisionField.py
761
3.515625
4
# Input: INTEGER mod, POLY modPoly, POLY a, POLY b # Output: STRING answer, POLY answer-poly # Functionality: Compute the element f = a / b in F. # Output f as pretty print string and as POLY. from method.addPoly import addPoly from method.displayField import displayField from method.longDivPoly import longDivPoly from method.displayPoly import displayPoly def divisionField(mod, modPoly, a, b): x = displayField(mod, modPoly, a)[1] y = displayField(mod, modPoly, b)[1] if y == [0]: return 'ERROR', [] q, r = longDivPoly(mod, x, y)[2:4] while r != [0]: x = addPoly(mod, x, modPoly)[1] q, r = longDivPoly(mod, x, y)[2:4] return displayPoly(mod, q)[0], q
16f4516dc01599206efe6d145d6cdb5eff29f874
CodeNeverStops/PythonChallenge
/02_ocr.py
207
3.59375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- def solution(content): chars = [char for char in content if char.isalpha()] print "".join(chars) content = file('02_ocr.txt').read() solution(content)
14cfc68263a404e951421ddf9fa6780d8ae78de2
niharnandan/RA-Spring2020
/2020_1 Spring/OptimalStrategy Simulations/PYTHON - optimal strategy/Optimal Strategy/2. Data Simulation/data simulation distribution.py
9,342
3.875
4
# import packages import math import random import numpy as np import csv ############################### Explanation ############################### # This is a very similar code to 'data simulation.py'. But instead of simulating 40*25 sequences, # we simulate 100 samples, each with 25*4 sequences. We will calculate the distribution of MLE # according to this simulation. # IMPORTANT NOTE: four parameters that would affect the simulation results: # lambda(k), alpha1, alpha2, stop_cost. # If you want to change lambda(k), change in this code. To change the other three, change # 'value functions.py' to generate a different 'value functions.csv' first. # NOTE 2: what we need to run the code: 'value functions.csv', 'Bayes Results.csv' (experiment data) # NOTE 3: write into csv file called 'simulation results 2.csv' ############################### helper function ############################### # capture the randomness of decision making. prob of choosing stop, 1, 2, given lambda(k), V_stop, V_1, V_2 # input: lambda(k), V_stop, V_1, V_2 # output: prob of choosing stop, investigate 1, and investigate 2 def randomness(k,v_stop,v_red,v_blue): try: p_stop = 1/(1+math.exp(k*(v_red-v_stop))+math.exp(k*(v_blue-v_stop))) except OverflowError: p_stop = 0 try: p_red = 1/(1+math.exp(k*(v_stop-v_red))+math.exp(k*(v_blue-v_red))) except OverflowError: p_red = 0 try: p_blue = 1/(1+math.exp(k*(v_stop-v_blue))+math.exp(k*(v_red-v_blue))) except OverflowError: p_blue = 0 return (p_stop,p_red,p_blue) ############################### set parameters ############################### k = 0.04 # parameter (lambda) in randomness p_grid = np.linspace(0,1,1001,endpoint=True) # p grid trial = 60 # total number of available trials cost = [5,10,20,40,80] # cost per investigation prior = [0.1,0.3,0.5,0.7,0.9] # prior probability of 1 guilty count = 0 # keep track of the number of trial (no greater than 60) true_state = [] # guilty state for each cost, prior # extract the true state ('guilty_suspect_chosen') from experiment data for c in cost: # for each cost level for p in prior: # for each prior level with open('Bayes Results.csv','r') as csvfile: # read the experiment file filereader = csv.reader(csvfile, delimiter=',') for row in filereader: # identify the trial from part2, with cost=c and prior=p if row[1] == 'part2' and row[2] == str(c) and row[3] == str(p): true_state.append(row[4]) # read from csv file stored as 'value functions.csv' the following parameters: # accuracy1 (prob of finding 1 guilty conditional on 1 guilty), accuracy2, alpha_1, alpha_2 with open('value functions.csv','r') as csvfile: filereader = csv.reader(csvfile, delimiter=',') accuracy1 = float(next(filereader)[1]) accuracy2 = float(next(filereader)[1]) alpha_1 = float(next(filereader)[1]) alpha_2 = float(next(filereader)[1]) # create a list of column names, same format as the experiment data csv file column_name = ['trial_no','block_name','setup_cost','red_prior_prob', 'guilty_suspect_chosen','timing_valid','timing_error'] for i in range(1,63): column_name.append('_'.join(['choice',str(i)])) ############################### simulation and write into csv file ############################### # write simulation results into one single file with open('simulation results 2.csv','w') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|',quoting=csv.QUOTE_MINIMAL) filewriter.writerow(column_name) # below is the simulation of decision sequences for M in range(100): for c in cost: # the following lines read V_stop, V_1, V_2 of the corresponding cost from 'value functions.csv' with open('value functions.csv','r') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for line, content in enumerate(filereader): if content == [''.join(['cost=',str(c)])]: line_num = line # identify the line of cost = c break V_stop = next(filereader) V_stop = [float(i) for i in V_stop] # change str type to float V_1 = next(filereader) V_1 = [float(i) for i in V_1] V_2 = next(filereader) V_2 = [float(i) for i in V_2] for p in prior: idx = cost.index(c)*5 + prior.index(p) # index for truly guilty state of (c,p) guilty = true_state[idx] # true state p0 = p # instore value of p into p0, so that we can reset after break from one trial # for each level of c(cost) and p(prior), we append the simulation result into the # created csv file, which contains 40 simulations for each (c,p) combination, and # each simulation consists 60 available investigation opportunities for i in range(4): # four simulations investigation = ['','',c,p,guilty,'',''] # for each trial, keep track of the choices made count = 0 # keep track of the number of investigation (60 maximum) while (count <= trial): # when we have not reached total available investigation number (60) count += 1 # keep track of number of times we have investigated p_index = np.argmax(-(abs(p_grid - p))) # find the position of p in p_grid # find the value of stop, 1, 2 for that p, and the prob of stop, 1, 2 based on randomness choice = randomness(k,V_stop[p_index],V_1[p_index],V_2[p_index]) random_action = random.random() # generate a random number # case 1: accuse if random_action <= choice[0]: if p>=0.5: # red is more likely to be guilty investigation.append('accuse_red') investigation.append('advance_to_next_trial') else: # blue is more likely to be guilty investigation.append('accuse_blue') investigation.append('advance_to_next_trial') p = p0 break # case 2: investigate red elif random_action <= 1-choice[2]: investigation.append('investigate_red') # red is guilty and evidence is shown, then accuse red if random.random()<=accuracy1 and guilty == 'red': investigation.append('evidence_shown') investigation.append('accuse_red') investigation.append('advance_to_next_trial') p = p0 break else: # no evidence posterior = p*(1-accuracy1)/(1 - p*accuracy1) if (p >= 0.5 and posterior > p) or (p < 0.5 and posterior < p): p = alpha_1*posterior + (1-alpha_1)*p else: p = alpha_2*posterior + (1-alpha_2)*p p = min(max(p,0),1) # updated p in (0,1) # case 3: investigate blue else: investigation.append('investigate_blue') # blue is guilty and evidence is shown, then accuse blue if random.random()<=accuracy2 and guilty == 'blue': investigation.append('evidence_shown') investigation.append('accuse_blue') investigation.append('advance_to_next_trial') p = p0 break else: # no evidence posterior = p/(1 - (1-p)*accuracy2) if (p >= 0.5 and posterior > p) or (p < 0.5 and posterior < p): p = alpha_1*posterior + (1-alpha_1)*p else: p = alpha_2*posterior + (1-alpha_2)*p p = min(max(p,0),1) # updated p in (0,1) # if we run out of investigation opportunities, but don't make a decision yet if investigation[-1] != 'advance_to_next_trial': if p>=0.5: # red likely to be guilty investigation.append('accuse_red') else: # blue likely to be guilty investigation.append('accuse_blue') investigation.append('advance_to_next_trial') p = p0 # write the sequence of investigation choice of one trial into the csv with open('simulation results 2.csv','a') as csvfile: filewriter = csv.writer(csvfile) filewriter.writerow(investigation) csvfile.close()
055972f2b5cb0fd63f8b0e67f1bcee03950917c2
bobotan/Python-100-Days
/Day01-15/Day08/demo1.py
220
3.546875
4
class Stu (object): def __init__(self,name,age): self.name=name self.age=age def sit(self): print(self.name) if __name__=="__main__": stu=Stu(name='123',age=5) stu.sit()
b8f6614b03593fa4d5eb94d5d983b172f7cbb0f1
bobotan/Python-100-Days
/Day01-15/Day07/demo.py
517
3.8125
4
# str1='a1b2c3d4e5' # print(str1[1]) # print(str1[2:5]) # print(str1[2:]) # print(str1.isdigit()) # print(str1.isalpha()) # print(str1.isalnum()) # print(str1[-3:-1]) # print(str1[::-1]) # 列表 # list1=[1,3,5,7,100] # print(list1) # list2=['fuck']*5 # print(list2) # print(list2[2]) # list2.append('you') # print(list2) fruits = ['grape', 'apple', 'strawberry', 'waxberry'] fruits += ['pitaya', 'pear', 'mango'] for fruit in fruits: print(fruit.title(),end=' ') print() fruits3=fruits[:] print(fruits3)
ea11406cfd4cccb20fa8f1d46bc581816dde3088
huyngopt1994/network-tool
/bit_Handler/bitreader.py
1,853
3.640625
4
""" Simple bitreader class and some utility functions. Inspired by http://multimedia.cx/eggs/python-bit-classes """ import sys class BitReadError(ValueError): pass class BitReader(object): """Read bits from bytestring buffer into unsigned integers.""" def __init__(self, buffer): self.buffer = buffer # Set the pos of bit self.bit_pos = 7 # get the first bytestring to interger value self.byte = ord(self.buffer[0]) self.index = 1 def get_bits(self, num_bits): """Read num_bits from the buffer.""" num = 0 # create a mask to filter per bit for per position # firstly get the highest bit in byte mask = 1 << self.bit_pos if self.byte is None: return None while num_bits: num_bits -=1 num <<= 1 if self.byte & mask: num |= 1 mask >>= 1 self.bit_pos -= 1 print (self.bit_pos) if self.bit_pos < 0: if self.byte is None: raise BitReadError("Beyond buffer doundary") self.bit_pos = 7 mask =1 << self.bit_pos if self.index < len(self.buffer): self.byte = ord(self.buffer[self.index]) else: self.byte = None self.index += 1 print('this is where we need to plus index') print self.index return num if __name__ == '__main__': buffer = sys.argv[1] num_bits = sys.argv[2] bit_object = BitReader(buffer) print('the first') num1 = bit_object.get_bits(int(num_bits)) print('the second') num2 = bit_object.get_bits(int(num_bits)) print('the third') num3 = bit_object.get_bits(int(num_bits))
846ac682c888800252b6562b70f5d88d60151a37
koendevolder/project-euler
/3/3.py
636
3.578125
4
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? ''' n = 600851475143 i = 2 while n != i: while n % i == 0: n = n / i i = i + 1 print n ''' def prime_number (var): for i in range(2, var): if (var % i == 0): return False break return True --- initial solution n = 600851475143 i = 2 while n != i: if (n % i == 0): n = n / i i = 2 i = i + 1 print n --- internet solution n = 600851475143 i = 2 while i * i < n: while n % i == 0: n = n / i i = i + 1 print n '''
816cfdedf274dbff93b9e23f361b5f690c6852c4
suprateek-sc19/Caesar-Cipher-in-Python-
/cipher.py
2,045
4
4
import time # encrypt and decrypt a message using Caesar Cipher key = 'abcdefghijklmnopqrstuvwxyz' # Encryption Function def encrypt(n, plaintext): """Encrypt the string and return the ciphertext""" #Start timer start = time.time() result = '' # Convert all lettes to lowercase #Substitute every letter for l in plaintext.lower(): try: i = (key.index(l) + n) % 26 result += key[i] except ValueError: result += l #Stop timer end = time.time() #Calculate run time run = end - start print("Encryption took {:.5f} seconds".format(run)) return result.lower() # Decryption function def decrypt(n, ciphertext): """Decrypt the string and return the plaintext""" start2 = time.time() result = '' for l in ciphertext: try: i = (key.index(l) - n) % 26 result += key[i] except ValueError: result += l end2 = time.time() run2 = end2 - start2 print("Decryption took {:.5f} seconds".format(run2)) return result # Taking user input digits=[] text = input("Please enter the message you want to encrypt \n") dob = input("Please enter your DOB in the format MM/DD/YYYY \n") # Adding digits of DOB to use the sum as offset for encryption digits.append(dob.split("/")) offset = 0 for num in digits: for i in num: i = int(i) while(i!=0): offset += i % 10 i = int(i/10) # Printing both encrypted and decrypted messages encrypted = encrypt(offset, text) print('Encrypted:', encrypted) decrypted = decrypt(offset, encrypted) print('Decrypted:', decrypted) # Testing Code # with open("tests.txt", "r", encoding="utf8") as f: # data = f.read() # messages = data.split("---") # for i,j in zip(messages, range(3,11)): # encrypted = encrypt(j, i) # decrypted = decrypt(j, encrypted) # print(encrypted) # print(decrypted)
9b1f3c8d96a19e3da776c3413d4f2239187efa54
NguyenAnhDuc/pytemp
/src/libs/singleton/__init__.py
1,309
3.75
4
#!/usr/bin/python # -*- coding: utf8 -*- """ Author: Ly Tuan Anh github nick: ongxabeou mail: lytuananh2003@gmail.com Date created: 2017/04/28 """ class Singleton(object): """Singleton decorator.""" def __init__(self, cls): self.__dict__['cls'] = cls instances = {} def __call__(self): if self.cls not in self.instances: self.instances[self.cls] = self.cls() return self.instances[self.cls] def __getattr__(self, attr): return getattr(self.__dict__['cls'], attr) def __setattr__(self, attr, value): return setattr(self.__dict__['cls'], attr, value) # ------------------Test------------------------ if __name__ == '__main__': @Singleton class bar(object): def __init__(self): self.val = None @Singleton class poo(object): def __init__(self): self.val = None def activated(self, acc_id): self.val = acc_id x = bar() x.val = 'sausage' print(x, x.val) y = bar() y.val = 'eggs' print(y, y.val) z = bar() z.val = 'spam' print(z, z.val) print(x is y is z) x = poo() x.val = 'sausage' print(x, x.val) y = poo() y.val = 'eggs' print(y, y.val) x = poo() x.activated(123) print(x.val)
9d5b9a3d265ee3741b9f03a236003e6132a7010e
grey-area/avida-clone
/organism.py
9,206
3.515625
4
import random copy_mutation_rate = 0.0025 birth_insert_mutation_rate = 0.0025 birth_delete_mutation_rate = 0.0025 number_of_instructions = 26 class organism(): def randomColour(self): self.colour = (random.random(),random.random(),random.random()) # Determine which register to interact with def register(self): register = 0 # If the next instruction is a no-op, use it to set the active register and then skip over that no-op if self.genome[(self.heads[0]+1)%len(self.genome)] < 3: register = self.genome[(self.heads[0]+1)%len(self.genome)] self.heads[0] = (self.heads[0]+1)%len(self.genome) return register # Instructions. ?A? indicates that A is the default setting, but that this can be changed by following the instruction with no-ops #0,1,2 No-ops def nop(self): pass #3 Execute the instruction after only if ?AX? doesn't equal its complement def if_n_eq(self): position = (self.heads[0]+1)%len(self.genome) while self.genome[position]<3: position = (position+1)%len(self.genome) register = self.register() if self.registers[register] != self.registers[(register+1)%3]: position = (position-1)%len(self.genome) self.heads[0] = position #4 Execute the next non-nop instruction only if ?AX? is less than its complement def if_less(self): position = (self.heads[0]+1)%len(self.genome) while self.genome[position]<3: position = (position+1)%len(self.genome) register = self.register() if self.registers[register] < self.registers[(register+1)%3]: position = (position-1)%len(self.genome) self.heads[0] = position #5 Remove a number from the current stack and place it in ?AX? def pop(self): if len(self.stack) > 0: self.registers[self.register()] = self.stack.pop() #6 Copy the value of ?AX? onto the top of the current stack def push(self): if len(self.stack) < self.stackLimit: self.stack.append(self.registers[self.register()]) #7 Toggle the active stack def swap_stk(self): temp = self.otherStack self.otherStack = self.stack self.stack = temp #8 Swap the contents of ?AX? with its complement def swap(self): register = self.register() temp = self.registers[register] self.registers[register] = self.registers[(register+1)%3] self.registers[(register+1)%3] = temp #9 Shift all the bits in ?AX? one to the right def shift_r(self): self.registers[self.register()] >>= 1 #10 Shift all the bits in ?AX? one to the left def shift_l(self): self.registers[self.register()] <<= 1 #11 Increment ?AX? def inc(self): self.registers[self.register()] += 1 #12 Decrement ?AX? def dec(self): self.registers[self.register()] -= 1 #13 Calculate the sum of AX and BX; put the result in ?AX? def add(self): self.registers[self.register()] = self.registers[0] + self.registers[1] #14 Calculate AX-BX; put the result in ?AX? def sub(self): self.registers[self.register()] = self.registers[0] - self.registers[1] #15 Bitwise NAND on AX and BX, put result in ?AX? def nand(self): self.registers[self.register()] = ~(self.registers[0] & self.registers[1]) #16 Output the value ?AX? and replace it with a new input def IO(self): register = self.register() self.output = self.registers[register] self.registers[register] = self.input #17 Allocate memory for an offspring def h_alloc(self): self.genome += [26] * (self.maxSize - len(self.genome)) #18 Divide off an offspring located between the read-head and write-head. def h_divide(self): if self.heads[1] <= self.heads[2]: self.offspring = self.genome[self.heads[1]:self.heads[2]] self.genome = self.genome[:self.heads[1]] else: self.offspring = self.genome[self.heads[1]:] self.genome = self.genome[:self.heads[1]] self.registers = [0,0,0] self.heads = [len(self.genome)-1,0,0,0] self.stack = [] self.otherStack = [] self.complementCopied = [] #19 Copy an instruction from the read-head to the write-head and advance both. def h_copy(self): toCopy = self.genome[self.heads[1]] if toCopy < 3: self.complementCopied.append((toCopy-1)%3) else: self.complementCopied = [] # Wrong copy mutation if random.random() < copy_mutation_rate: toCopy = random.randint(0,number_of_instructions) self.genome[self.heads[2]] = toCopy # Duplicate copy mutation if random.random() < copy_mutation_rate: self.heads[2] = (self.heads[2]+1) % len(self.genome) self.genome[self.heads[2]] = toCopy self.heads[1] = (self.heads[1]+1) % len(self.genome) self.heads[2] = (self.heads[2]+1) % len(self.genome) #20 Find a complement template of the one following and place the flow head after it. def h_search(self): complement = [] position = (self.heads[0]+1)%len(self.genome) self.heads[3] = position while self.genome[position]<3: complement.append((self.genome[position]+1)%3) position = (position+1)%len(self.genome) # Search for the complement. If we find it, place the flow head after the end of it, otherwise place the flow head immediately after the IP position = (self.heads[0]+1)%len(self.genome) while position != self.heads[0]: test = self.genome[position:position+len(complement)] end = position+len(complement) if len(test) < len(complement): end = len(complement)-len(test) test += self.genome[:len(complement)-len(test)] if test==complement: # we found the complement label self.heads[3] = end%len(self.genome) break position = (position+1)%len(self.genome) #21 Move the ?IP? to the position of the flow-head. (A=IP, B=read, C=write) def mov_head(self): register = self.register() self.heads[register] = self.heads[3] if register==0: self.heads[0] = (self.heads[0]-1)%len(self.genome) # Because it's about to be incremented #22 Move the ?IP? by a fixed amount found in CX def jmp_head(self): register = self.register() self.heads[register] = (self.heads[register] + self.registers[2]) % len(self.genome) #23 Write the position of the ?IP? into CX (A=IP, B=read, C=write) def get_head(self): self.registers[2] = self.heads[self.register()] #24 The CPU remembers the last contiguous series of no-ops copied by h_copy. Execute the next instruction only if this instruction is followed by the complement of what was last copied def if_label(self): followingLabel = [] position = (self.heads[0]+1)%len(self.genome) while self.genome[position]<3: followingLabel.append(self.genome[position]) position = (position+1)%len(self.genome) # If the labels match, put the position back a step (remember, the IP will be incremented immediately after this) # The result is that the next instruction will be skipped if the labels don't match if followingLabel == self.complementCopied[len(self.complementCopied)-len(followingLabel):]: position = (position-1)%len(self.genome) self.heads[0] = position #25 Move the flow-head to the memory position specified by ?CX? def set_flow(self): self.heads[3] = self.registers[(self.register()+2)%3]%len(self.genome) def setGenome(self, genome): self.genome = genome self.oldGenome = self.genome[:] def __init__(self): self.maxSize = 100 self.genome = [] # The program self.registers = [0,0,0] # The registers self.stack = [] # The stacks self.otherStack = [] self.stackLimit = 20 self.heads = [0,0,0,0] # instruction, read, write, flow heads self.input = 0 self.output = 0 self.complementCopied = [] self.offspring = None self.colour = (0.0, 0.0, 0.0) self.age = 0 self.instructions = [self.nop,self.nop,self.nop,self.if_n_eq,self.if_less,self.pop,self.push,self.swap_stk,self.swap,self.shift_r,self.shift_l,self.inc,self.dec,self.add,self.sub,self.nand,self.IO,self.h_alloc,self.h_divide,self.h_copy,self.h_search,self.mov_head,self.jmp_head,self.get_head,self.if_label,self.set_flow,self.nop] def execute(self, input): self.input = input self.offspring = None if len(self.genome) > 0: self.instructions[self.genome[self.heads[0]]]() # Execute one instruction if len(self.genome) > 0: self.heads[0] = (self.heads[0] + 1) % len(self.genome) # Increment the instruction head self.age += 1 return self.offspring
7ac095090e1bd5c5301b0dd06af883ee02b4a9b5
marcinszymanski1978/training_Python_Programator
/test3.py
236
3.734375
4
x=9 print("X =",x) if x<=9: print("X nie jest większe od",x) else: print("X jest większe od",x) y = "Marcin Szymański" print(y,len(y)) if len(y)>x: print("Napis jest dłuższy od",x) else: print("Napis nie jest dłuższy od",x)
202a2c3c9310b7064966c5d7fe953fcd3a9d7c39
marcinszymanski1978/training_Python_Programator
/while1.py
225
3.84375
4
x=1 for x in range(5): print(x) dzien_tygodnia=['poniedzialek','wtorek','sroda','czwartek','piatek','sobota','niedziela'] for x in range(len(dzien_tygodnia)): print("Dzień tygodnia nr",x+1, "to",dzien_tygodnia[x])
955d4bebf2c1c01ac20c697a2bba0809a4b51b46
patilpyash/practical
/largest_updated.py
252
4.125
4
print("Program To Find Largest No Amont 2 Nos:") print("*"*75) a=int(input("Enter The First No:")) b=int(input("Enter The Second No:")) if a>b: print("The Largest No Is",a) else: print("The Largest No Is",b) input("Enter To Continue")
bdf9ee7ba513a401ed3d6b263cb6ab14f684734e
ObbieOnOblivion/Toyota-Supra-tuning
/toyota_supra_v3.py
16,680
3.734375
4
import random import time # import tkinter import my_function_3 class ToyotaSupraInternals: """ anything thing that cant be tuned and the features of the car Attributes: turbo(str): The name of the turbo turbo_type(str): The type of the turbo transmission(str): this shows the general type of the transmission not the exact make or model gear1_ratio(float): this is the first gear ratio, or the trans ratio gear2_ratio(float): this is the second gear ratio. gear3_ratio(float): this is the third gear ratio. gear4_ratio(float): this is the forth gear ratio. gear5_ratio(float): this is the fifth gear ratio. gear6_ratio(float): this is the sixth gear ratio. dif_type(str): this shows if the differential is either opened or closed not the percentage locked or opened dif_ratio(float): this is the ratio for the differential engine_type(str): this is the engine type, in the first case it would be an inline 6 wheel_diameter(int): this shows the diameter of the rear tyres weight(int): the weight of the car with the modifications gutted_weight(int): this is the weight that you will lose if you gut the A/C and the interior """ """these are other variable just to keep in mind these are not important to the program """ DragCoefficient = .320 CurbWeight = 3434 """ drag Coefficient at 90 miles per hour""" DC90 = 66 def __init__(self): self.turbo = 'PT8847' self.turbo_type = 'ball bearing' self.transmission = 'helical gear drive' self.gear1_ratio = 3.55 self.gear2_ratio = None self.gear3_ratio = None self.gear4_ratio = None self.gear5_ratio = None self.gear6_ratio = None self.dif_type = 'lsd' self.dif_ratio = 3.909 self.engine_type = 'induction performance 2jz' self.wheel_diameter = 20 self.weight = 3599 self.gutted_weight = 400 def set_gear_ratio(self, gear, ratio): if gear == 1: self.gear1_ratio = ratio if gear == 2: self.gear2_ratio = ratio if gear == 3: self.gear3_ratio = ratio if gear == 4: self.gear4_ratio = ratio if gear == 5: self.gear5_ratio = ratio if gear == 6: self.gear6_ratio = ratio def gut_car(self): """this method removes weight from the car""" if self.weight == 3599: self.weight -= self.gutted_weight return True else: return False def apply_interior(self): """this method puts back the weight that was gutted back on""" if bool(self.gut_car) and self.weight == 3199: self.weight += self.gutted_weight Scotty = ToyotaSupraInternals() Scotty.set_gear_ratio(1, 3.55) Scotty.set_gear_ratio(2, 2.09) Scotty.set_gear_ratio(3, 1.49) Scotty.set_gear_ratio(4, 1.00) Scotty.set_gear_ratio(5, .69) Scotty.set_gear_ratio(6, .58) class ToyotaSupra(ToyotaSupraInternals): """This class will be more concerning with the cars tune not as much the hardware of the car Attributes: spring_pressure(int): This is the minimum amount of boost you could to level with your spring boost_level(int): This is the psi your turbo charger is running duty_cycle(int): This hows at what percent work is the injectors doing for what its rated for fuel_pressure(int): This is the pressure of the fuel injectors timing_degrees(int): This is the amount of timing that is iin the car max_boost(int): This is the most amount of boost you could give this engine before a bearing spins or rod knock two_step_RPM(int): This is the RPM the two-step is set at tyre_type(str): this is the the type of tyre used on the rear wheels fuel_type(str): This shows the grade and type of fuel used tsd1(dict): This is a dictionary is for a range of two-step RPMs """ def click(self): """opens the spring pressure window """ import tkinter as tk mane = tk.Tk() mane.geometry('300x300-170-50') mane.title('spring pressure') text1 = tk.Text(mane, relief='sunken') text1.delete(0.0, 6.6) text1.insert(0.0, self.spring_pressure) mane.mainloop() @staticmethod def what_we_do(): """this shows a general idea of what goes on in the use_screen method""" import tkinter as tk mainwindow = tk.Tk() mainwindow.geometry('700x300-50-100') label1 = tk.Label(mainwindow, text='tyres') label2 = tk.Label(mainwindow, text='boost preasure') label3 = tk.Label(mainwindow, text='duty cycle') label4 = tk.Label(mainwindow, text='launch control') label5 = tk.Label(mainwindow, text='boost by gear') label6 = tk.Label(mainwindow, text='car details') label1.config(relief='groove') label2.config(relief='groove') label3.config(relief='groove') label4.config(relief='groove') label5.config(relief='groove') label6.config(relief='groove') label1.grid(column=0, row=0, sticky='nesw') label2.grid(column=1, row=0, sticky='nesw') label3.grid(column=2, row=0, sticky='nesw') label4.grid(column=3, row=0, sticky='nesw') label5.grid(column=4, row=0, sticky='nesw') label6.grid(column=5, row=0, sticky='nesw') mainwindow.columnconfigure(0, weight=4) mainwindow.columnconfigure(1, weight=4) mainwindow.columnconfigure(2, weight=4) mainwindow.columnconfigure(3, weight=4) mainwindow.columnconfigure(4, weight=4) mainwindow.columnconfigure(5, weight=4) mainwindow.rowconfigure(0, weight=4) mainwindow.mainloop() @staticmethod def use_screen(): """this is the application itself """ def click_20(): my_function_3.click_20() # visit my_function_3.py for documentation def click_19(): my_function_3.click_19() # visit my_function_3.py for documentation def click18(): my_function_3.click_18() # visit my_function_3.py for documentation def click17(): my_function_3.click_17() # visit my_function_3.py for documentation def click16(): my_function_3.click_16() # visit my_function_3.py for documentation def click15(): my_function_3.click_15() # visit my_function_3.py for documentation def click14(): my_function_3.click_14() # visit my_function_3.py for documentation def click13(): my_function_3.click_13() # visit my_function_3.py for documentation def click12(): my_function_3.click_12() # visit my_function_3.py for documentation def click11(): my_function_3.click_11() # visit my_function_3.py for documentation def click10(): my_function_3.click_10() # visit my_function_3.py for documentation def click9(): my_function_3.click_9() # visit my_function_3.py for documentation def click8(): my_function_3.click_8() # visit my_function_3.py for documentation def click7(): my_function_3.click_7() # visit my_function_3.py for documentation def click6(): my_function_3.click_6() # visit my_function_3.py for documentation def click5(): my_function_3.click_5() # visit my_function_3.py for documentation def click4(): my_function_3.click_4() # visit my_function_3.py for documentation def click3(): my_function_3.click_3() # visit my_function_3.py for documentation def click2(): my_function_3.click_2() # visit my_function_3.py for documentation def click1(): my_function_3.click_1() # visit my_function_3.py for documentation def click(): my_function_3.click() # visit my_function_3.py for documentation def kill_switch(): mainwindow.destroy() import tkinter as tk mainwindow = tk.Tk() mainwindow.title("Toyota Supra Tune") mainwindow.geometry('700x300-50-100') mainwindow.configure(background='plum') label1 = tk.Label(mainwindow, text='tyres') label2 = tk.Label(mainwindow, text='boost pressure') label3 = tk.Label(mainwindow, text='other') label4 = tk.Label(mainwindow, text='launch control') label5 = tk.Label(mainwindow, text='gear info') label6 = tk.Label(mainwindow, text='car details') label1.config(relief='groove', bg='purple') label2.config(relief='groove', bg='purple') label3.config(relief='groove', bg='purple') label4.config(relief='groove', bg='purple') label5.config(relief='groove', bg='purple') label6.config(relief='groove', bg='purple') label1.grid(column=0, row=0, sticky='nesw') label2.grid(column=1, row=0, sticky='nesw') label3.grid(column=2, row=0, sticky='nesw') label4.grid(column=3, row=0, sticky='nesw') label5.grid(column=4, row=0, sticky='nesw') label6.grid(column=5, row=0, sticky='nesw') button1 = tk.Button(mainwindow, text="tyre pressures", fg='purple', command=click2) button2 = tk.Button(mainwindow, text="tyre type", fg='purple', command=click1) button3 = tk.Button(mainwindow, text="spring pressure", fg='red', command=click) button4 = tk.Button(mainwindow, text="boost pressure", fg='red', command=click4) button5 = tk.Button(mainwindow, text="max boost psi", fg='red', command=click3) button6 = tk.Button(mainwindow, text="duty cycle", fg='yellow', comman=click6) button7 = tk.Button(mainwindow, text="two-step RPM", fg='orange', command=click7) button8 = tk.Button(mainwindow, text="gear1", fg='turquoise', command=click9) button9 = tk.Button(mainwindow, text="gear2", fg='turquoise', command=click10) button10 = tk.Button(mainwindow, text="gear3", fg='turquoise', command=click11) button11 = tk.Button(mainwindow, text="gear4", fg='turquoise', command=click12) button12 = tk.Button(mainwindow, text="gear5", fg='turquoise', command=click13) button13 = tk.Button(mainwindow, text="gear6", fg='turquoise', command=click14) button14 = tk.Button(mainwindow, text="fuel information", fg='green', command=click8) button15 = tk.Button(mainwindow, text="differential", fg='green', command=click15) button16 = tk.Button(mainwindow, text="Engine", fg='green', command=click16) button17 = tk.Button(mainwindow, text='car image', fg='green', command=click5) button18 = tk.Button(mainwindow, text="kill", fg='blue', command=kill_switch) button19 = tk.Button(mainwindow, text='simulator', fg='magenta', command=click18) button20 = tk.Button(mainwindow, text='Dyno numbers', fg='crimson', command=click17) button21 = tk.Button(mainwindow, text='Other Details', fg="lavender", command=click_19) button22 = tk.Button(mainwindow, text="weight", fg="yellow", command=click_20) button1.grid(column=0, row=1, sticky='news') button2.grid(column=0, row=2, sticky='news') button4.grid(column=1, row=1, sticky='news') button3.grid(column=1, row=2, sticky='news') button5.grid(column=1, row=3, sticky='news') button6.grid(column=2, row=1, sticky='news') button7.grid(column=3, row=1, sticky='news') button8.grid(column=4, row=1, sticky='news') button9.grid(column=4, row=2, sticky='news') button10.grid(column=4, row=3, sticky='news') button11.grid(column=4, row=4, sticky='news') button12.grid(column=4, row=5, sticky='news') button13.grid(column=4, row=6, sticky='news') button14.grid(column=5, row=1, sticky='news') button15.grid(column=5, row=2, sticky='news') button16.grid(column=5, row=3, sticky='news') button17.grid(column=5, row=4, sticky='news') button18.grid(column=2, row=6, sticky='news') button19.grid(column=1, row=6, sticky='news') button20.grid(column=5, row=5, sticky='news') button21.grid(column=0, row=6, sticky='news') button22.grid(column=2, row=2, sticky='news') mainwindow.columnconfigure(0, weight=4) mainwindow.columnconfigure(1, weight=4) mainwindow.columnconfigure(2, weight=4) mainwindow.columnconfigure(3, weight=4) mainwindow.columnconfigure(4, weight=4) mainwindow.columnconfigure(5, weight=4) mainwindow.rowconfigure(0, weight=4) mainwindow.rowconfigure(1, weight=4) mainwindow.rowconfigure(2, weight=4) mainwindow.rowconfigure(3, weight=4) mainwindow.rowconfigure(4, weight=4) mainwindow.rowconfigure(5, weight=4) mainwindow.rowconfigure(6, weight=4) mainwindow.mainloop() tyre_pressure = 17 def __init__(self): super(ToyotaSupra, self).__init__() self.spring_pressure = 5 self.boost_level = int(self.spring_pressure) self.duty_cycle = 103 self.fuel_pressure = 90 self.timing_degrees = 10 self.max_boost = 55 self.two_step_RPM = 3900 self.tyre_type = "Drag Radials" self.fuel_type = "89 Octane" self.tsd1 = {} def set_max_boost(self, max_boost_pressure): """this sets the max boost pressure""" if self.spring_pressure <= max_boost_pressure <= 60: self.max_boost = max_boost_pressure def advance_timing(self): """this advances the timing to create more power """ self.timing_degrees = 14 def retard_timing(self): """this retards the timing to create less power or less harmful emissions""" self.timing_degrees = 8 def inc_boost(self, boost): """this increases the boost pressures""" if int(self.spring_pressure) <= self.boost_level <= int(self.max_boost): self.boost_level += boost else: self.boost_level = int(self.spring_pressure) + 1 def change_fuel_type(self, fuel): """change the fuel type and the grade of the fuel""" fuel = str(fuel) fuel = fuel.strip(' ') fuel_list = ['93 Octane', 'c16', 'ignite red', '118 Octane', '89 Octane'] while fuel in fuel_list: for i in range(0, 5): if fuel in fuel_list[i]: self.fuel_type = fuel break break def tsd_set1(self): """this sets the dictionary tsd1 indexes to dictionaries""" for i in range(4200, 4501, 100): dict1 = dict() dict1["1"] = 1.32 # above 25 dict1["2"] = 1.17 # 22 - 25 dict1["3"] = 1.11 # 19 - 22 dict1["4"] = 1.05 # 17-19 dict1["5"] = 1.00 # 17 dict1["6"] = .98 # 15-17 dict1["7"] = 1.04 # 12-15 dict1["8"] = 1.14 # bellow 12 self.tsd1[i] = dict1 for i in range(4000, 4200, 100): dict2 = dict() dict2["1"] = 1.27 # above 25 dict2["2"] = 1.15 # 22 - 25 dict2["3"] = 1.10 # 19 - 22 dict2["4"] = 1.04 # 17-19 dict2["5"] = 1.03 # 17 dict2["6"] = 1.01 # 15-17 dict2["7"] = 1.07 # 12-15 dict2["8"] = 1.24 # bellow 12 self.tsd1[i] = dict2 for i in range(3700, 4000, 100): dict3 = dict() dict3["1"] = 1.17 # above 25 dict3["2"] = 1.09 # 22 - 25 dict3["3"] = 1.02 # 19 - 22 dict3["4"] = 1.009 # 17-19 dict3["5"] = 1.07 # 17 dict3["6"] = 1.11 # 15-17 dict3["7"] = 1.21 # 12-15 dict3["8"] = 1.34 # bellow 12 self.tsd1[i] = dict3 for i in range(3500, 3700, 100): dict4 = dict() dict4["1"] = 1.21 # above 25 dict4["2"] = 1.17 # 22 - 25 dict4["3"] = 1.11 # 19 - 22 dict4["4"] = 1.09 # 17-19 dict4["5"] = 1.03 # 17 dict4["6"] = 1.11 # 15-17 dict4["7"] = 1.27 # 12-15 dict4["8"] = 1.44 # bellow 12 self.tsd1[i] = dict4 OBBIE = ToyotaSupra() if __name__ == '__main__': print(ToyotaSupraInternals.__name__)
e6b2537be9801817e078d19cbdf34a047c1c777a
VendiolaRobin/vendiolarobin.github.io
/vendiola.py
134
4.375
4
x = int(input("Enter a number: ")) print(2*x) if (x % 3) == x: print("{x} is Even") else: print("your number is odd")
b87dedfda07df77c95d7a2ed20c1babfaaa1d763
xmartinbr/Python-Exemples
/Ej2-ProgFuncional.py
774
3.546875
4
#Función de nivel superior def saludo(idioma): def saludo_es(): print("Hola") def saludo_en(): print("Hello") idioma_func={"es":saludo_es, "en":saludo_en } #Devuelve el nombre de la función a utilizar en fucnión del valor #del parámetro [idioma] pasado return idioma_func[idioma] #saludar hace referencia al nombre de la función [saludo_es] saludar = saludo("es") #Al nombre de la función [saludo_es] se le añaden los parentesisis () y #por lo tanto saludar() = saludo_es() saludar() #saludar hace referencia al nombre de la función [saludo_en] saludar = saludo("en") #Al nombre de la función [saludo_es] se le añaden los parentesisis () y #por lo tanto saludar() = saludo_en() saludar()
b77a89b15e672b9508c4437e8b674284dd3326d4
MinhTamPhan/LearnPythonTheHardWay
/Exercise/Day5.3/point2d.py
703
3.671875
4
class Point2d(object): """store 1 point two dim """ def __init__(self, x, y): self.x = x self.y = y """return point do or don't equal Another point""" def Equals(self, pointOther): if self.x == pointOther.x and self.y == pointOther.y: return True else: return False """return Decsition Up Dow Left Right from point to another point""" def Decisions(self, pointOther): if self.x == pointOther.x and self.y < pointOther.y: return "D" elif self.x == pointOther.x and self.y > pointOther.y: return "U" elif self.x > pointOther.x and self.y == pointOther.y: return "L" elif self.x < pointOther.x and self.y == pointOther.y: return "R" else: return "I don't know"
9302fbf822224f10935dc423d35b283bf41b2609
MinhTamPhan/LearnPythonTheHardWay
/Exercise/Day5.3/ex42.py
1,371
4.34375
4
## Animal is-a object (yes, sort of confusing) look at the extra credit class Animal(object): pass ## Dog is-a object class Dog(Animal): def __init__(self, name): ## set attribul name = name self.name = name ## Cat is-a object class Cat(object): def __init__(self, name): ## set name of Cat self.name = name ## Person is-a object class Person(object): def __init__(self, name): ## set name of person self.name = name ## Person has-a pet of some kind self.pet = None ## Employee is-a object class Employee(Person): def __init__(self, name, salary): ## ?? hm what is this strage magic super(Employee, self).__init__(name) ## set salary = salary self.salary = salary ## Fish is-a object class Fish(object): pass ## Salmon is-a object class Salmon(Fish): pass ## Hailibut is-a object class Hailibut(Fish): pass ## rover is-a Dog rover = Dog("Rover") ## satan is-a Cat satan = Cat("Satan") ## mary is-a Person mary = Person("Mary") ## mary has-a pet is satan mary.pet = satan ## frank is-a Employee has-salary is 120000 frank = Employee("Frank", 120000) ## frank has-a pet is rover and it is a Dog frank.pet = rover ## flipper is-a fish() flipper = Fish() ## crouse is-a Salmon crouse = Salmon() ## harry is-a halibut harry = Hailibut() print "Name: ", frank.name , "Pet: ", print frank.pet.name ,"salary: ", frank.salary
b939c070c0cbdfa664cea3750a0a6805af4c6a10
Yatin-Singla/InterviewPrep
/Leetcode/RouteBetweenNodes.py
1,013
4.15625
4
# Question: Given a directed graph, design an algorithm to find out whether there is a route between two nodes. # Explanation """ I would like to use BFS instead of DFS as DFS might pigeonhole our search through neighbor's neighbor whereas the target might the next neighbor Additionally I'm not using Bi-directional search because I'm not sure if there is a path from target to root, Worst case scenario efficiency would be the same """ # Solution: from queue import LifoQueue as Queue def BFS(start, finish) -> bool: if not start or not finish: return False Q = Queue() # marked is a flag to indicate that the node has already been enqueued start.marked = True Q.enqueue(start) # process all nodes while not Q.isEmpty(): node = Q.dequeue() if node == target: return True for Neighbor in node.neighbors: if not Neighbor.marked: Neighbor.marked = True Q.enqueue(Neighbor) return True
eba983fe4115fa01d9406bce360a1675b394c1cd
Yatin-Singla/InterviewPrep
/Leetcode/ListDepths.py
1,351
4.0625
4
# Question: Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth # (eg if you have a tree with depth D, you'll have D linkedlists) # Solution from treeNode import Node from queue import LifoQueue as Queue # helper function def Process(node, level, result): if level > len(result) - 1: result.append([node]) else: result[level].append(node) return # BFS implementation def ListDepths(root: Node): if not root: return Q = Queue() level, result = 0, [] Q.enqueue((root, level)) while not Q.isEmpty(): node, level = Q.dequeue() Process(node, level, result) if node.left: Q.enqueue((node.left, level + 1)) if node.right: Q.enqueue((node.right, level + 1)) return result # DFS helper """ Assumption: value of level would be atmost 1 > len(result) passing in reference """ def DFSHelper(root, level, result): if not root: return if level > len(result) - 1: result.append([root]) else: result[level].append(root) DFSHelper(root.left, level + 1, result) DFSHelper(root.right, level + 1, result) return # DFS def DFSlistDepth(root: Node): level, result = 0, [] DFSHelper(root, level, result) return result
e92e09888bff7072f27d3d24313f3d53e37fc7dc
Yatin-Singla/InterviewPrep
/Leetcode/Primes.py
609
4.1875
4
''' Write a program that takes an integer argument and returns all the rpimes between 1 and that integer. For example, if hte input is 18, you should return <2,3,5,7,11,13,17>. ''' from math import sqrt # Method name Sieve of Eratosthenes def ComputePrimes(N: int) -> [int]: # N inclusive ProbablePrimes = [True] * (N+1) answer = [] for no in range(2,N+1): if ProbablePrimes[no] == True: answer.append(no) for i in range(no*2, N+1, no): ProbablePrimes[i] = False return answer if __name__ == "__main__": print(ComputePrimes(100))
b9a12d0975be4ef79abf88df0b083da68113e76b
Yatin-Singla/InterviewPrep
/Leetcode/ContainsDuplicate.py
730
4.125
4
# Given an array of integers, find if the array contains any duplicates. # Your function should return true if any value appears at least twice in the array, # and it should return false if every element is distinct. # * Example 1: # Input: [1,2,3,1] # Output: true # * Example 2: # Input: [1,2,3,4] # Output: false # * Example 3: # Input: [1,1,1,3,3,4,3,2,4,2] # Output: true def isDuplicates(nums): if not nums: return False if len(nums) == 1: return False unique = set() for item in nums: if item not in unique: unique.add(item) else: return True return False def containsDuplicate(nums): return True if len(set(nums)) < len(nums) else False
9fa036a40a99cf929410c823c38fec3d9b51b47a
Yatin-Singla/InterviewPrep
/Leetcode/BuyAndSellTwice.py
913
3.734375
4
''' Write a program that computes the maximum profit that can be made by buying and selling a share at most twice. The second buy must be made on another date after the first sale. ''' #returns profit and end index def BuyAndSell(prices, StartIndex) -> (int, int): if StartIndex < len(prices): return (0,-1) Profit, minPriceSoFar, IndexSell = 0, prices[StartIndex], 0 for index in range(StartIndex, len(princes)): ProfitToday = prices[index] - minPriceSoFar if ProfitToday > Profit: Profit = ProfitToday IndexSell = index minPriceSoFar = min(prices[index], minPriceSoFar) return Profit, IndexSell def BuyAndSellTwice(prices): profit, SecondBuy = BuyAndSell(prices, 0) SecondProfit, _ = BuyAndSell(prices, SecondBuy+1) return profit+SecondProfit if __name__ == "__main__": print(BuyAndSellTwice([12,11,13,9,12,8,14,13,15]))
b459e8a597c655f68401d3c8c73a68decfba186e
Yatin-Singla/InterviewPrep
/Leetcode/StringCompression.py
1,090
4.4375
4
''' Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabccccaa would become a2b1c5a3. If the compressed string would not become smaller than the original string, you method should return the original string. Assume the string has only uppercase and lowercase letters. ''' def StringCompression(charString): counter = 1 result = [] for index in range(1,len(charString)): if charString[index] == charString[index-1]: counter += 1 else: # doubtful if ''.join would work on int type list result.extend([charString[index-1],str(counter)]) counter = 1 result.extend([charString[-1], str(counter)]) return ''.join(result) if len(result) < len(charString) else charString # more efficient solution would be where we first estimate the length the length of the compressed string # rather than forming the string and figuring out which one to return. if __name__ == "__main__": print(StringCompression("aabccccaaa"))
b2fab79f5aae295192628dd012fbe3717db2625a
Yatin-Singla/InterviewPrep
/Leetcode/Merge Sorted Array.py
744
3.6875
4
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ index = 0 begPtr1 = begPtr2 = 0 tempNums1 = nums1[:m] while begPtr1 < m and begPtr2 < n: if tempNums1[begPtr1] < nums2[begPtr2]: nums1[index] = tempNums1[begPtr1] begPtr1 += 1 else: nums1[index] = nums2[begPtr2] begPtr2 += 1 index += 1 if begPtr1 != m: nums1[index:] = tempNums1[begPtr1:m] else: nums1[index:] = nums2[begPtr2:n] return nums1
195d8ee7cab08c68134a01a34c50f22b55e4b620
lzbgithubcode/Python-Study
/Base/Python使用小结.py
1,287
3.765625
4
#采集一个人的身高、体重、性别、年龄 计算输出体脂率是否正常 #计算BMI def computeBMI(weight,height): result = weight/height*height return result #计算体质率 def computebodyfatrate(bmi,age,sex): result = 1.2*bmi + 0.23*age -5.4-10.8*sex return result #判断是否正常 def judgeNormal(rate,sex): if sex == 0: #女 if rate >=0.25 and rate <= 0.28: print("这位女士您的体脂率正常") elif rate > 0.28: print('这位女士您的体脂率偏高') else: print('这位女士您的体脂率偏低') else: #男 if rate >=0.15 and rate <= 0.18: print("这位男士您的体脂率正常") elif rate > 0.18: print('这位男士您的体脂率偏高') else: print('这位男士您的体脂率偏低') while True: height = float(input("请输入您的身高是(cm):\n")) height = height/100 weight = float(input('请输入您的体重是(kg):\n')) age = int(input('请输入您的年龄\n')) sex = int(input('请输入您的性别(男输入1 女输入0):\n')) bmi = computeBMI(weight,height) rate = computebodyfatrate(bmi,age,sex) judgeNormal(rate,sex) break
2e9773b65e90e66a07c5bce018a468ac31a7b3f0
lzbgithubcode/Python-Study
/Base/元祖操作.py
783
3.84375
4
'1.元祖定义:有序不可变集合''' # 1.1 元祖的定义 # l = (1,) # print(type(l)) # tup = 1,2,3,4,'zb' # print(tup) # 1.2 列表转化从元祖 # nums = [1,2,3,4,5,6] # result = tuple(nums) # print(result,type(result)) '''2.元祖的操作,不可变,没有增删改''' # 2.1 查询某个元素或者多个元素 # items = (1,2,34,4,5,5,6,7,8,9) # print(items) # print(items[2],items[:2:],items[::-1]) # 2.2 获取元祖值 # print(items.count(5)) # 元素的个数 # print(items.index(2)) # 元素对应的索引 # print(len(items),max(items),min(items)) # 2.3 判定 in not in # print(1 in items) # 2.4 拼接(乘法 家法)和拆包 # # item2 = ('a','b','c') # print(items + item2) # print(item2 * 2) # # a,b = (10,20) # a,b = (b,a) # print(a,b)
97b89fcea4f35c9d899854eb87aa1999b1f095f2
JessicaGarson/MachineLearningFridays
/regularExpressions/regex_stepthrough.py
123
3.78125
4
f = open('regex_examples.txt','r') for line in f.readlines(): enter = input('') if enter == '': print(line)
d2bb5b64aa6bc8751844a356a3501f8c7af0fe55
WojciechSobierajski/FuelCounter
/FunctionsForFuelCounter.py
2,915
3.8125
4
import tkinter as tk from datetime import datetime def displaying_calculated(distance_driven, total_cost, cost_100km, fuel_consumption): dist=f"You've driven: {distance_driven} km" print(dist) trip_cost = f'It cost you: {total_cost} zł' print(trip_cost) cost_of_100km = f'100 km cost you: {cost_100km} zł' print(cost_of_100km) liters_per_100km= f'Fuel consumption is: {fuel_consumption} l/100 km' print(liters_per_100km) def displaying_validation_tk(fuel_consumption): if fuel_consumption > 10: score_tk = 'Too fast!' if fuel_consumption < 10 and fuel_consumption > 5: score_tk = 'consumption is good!' if fuel_consumption < 5: score_tk = 'Wow, very low !' return score_tk def displaying_validation_of_style(fuel_consumption): if fuel_consumption > 10: score = 'Too fast!' if fuel_consumption < 10 and fuel_consumption > 5: score = 'Fuel consumption is good!' if fuel_consumption < 5: score = 'Wow, very low !' print(score) def displaying_Tkinter(car_distance, distance_driven, total_cost, fuel_consumption, score_tk): def closing(): root.destroy() root = tk.Tk() canvas = tk.Canvas(root, height=300, width=400, bg="dark red") canvas.pack() frame = tk.Frame(root, height=100, width=100, bg="brown") frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1) label = tk.Label(frame, text=(f"You've driven: {distance_driven} km")) label.place(relx=0.1, rely=0.1) label = tk.Label(frame, text=(f'It cost you: {total_cost} zl')) label.place(relx=0.1, rely=0.2) label = tk.Label(frame, text=(f'Fuel consumption is: {fuel_consumption} l/100km')) label.place(relx=0.1, rely=0.3) label = tk.Label(frame, text=(f'Therefore {score_tk}')) label.place(relx=0.1, rely=0.4) label = tk.Label(frame, text=(f'Overal car distance: {car_distance} km')) label.place(relx=0.1, rely=0.5) button = tk.Button(root, text='Click to continue', command=closing) button.pack() root.mainloop() def filling_excel(sheet, wb, name, current_distance, current_price, distance_driven, total_cost, current_liters, fuel_consumption, cost_100km): cell = sheet.cell(sheet.max_row + 1, 1) cell.value = (datetime.date(datetime.now())) cell = sheet.cell(sheet.max_row, 2) cell.value = current_distance cell = sheet.cell(sheet.max_row, 3) cell.value = current_price cell = sheet.cell(sheet.max_row, 4) cell.value = current_liters cell = sheet.cell(sheet.max_row, 5) cell.value = distance_driven cell = sheet.cell(sheet.max_row, 6) cell.value = total_cost cell = sheet.cell(sheet.max_row, 7) cell.value = fuel_consumption cell = sheet.cell(sheet.max_row, 8) cell.value = cost_100km wb.save(f'{name}.xlsx')
cf0bb66cb20ad4d58c749bfc362ae8577f843f62
Indronil-Prince/Artificial-Intelligence-Project
/Utility.py
494
3.609375
4
import copy def numOfValue(board, value): return board.count(value) def InvertedBoard(board): invertedboard = [] for i in board: if i == "1": invertedboard.append("2") elif i == "2": invertedboard.append("1") else: invertedboard.append("X") return invertedboard def generateInvertedBoardList(pos_list): ''' ''' result = [] for i in pos_list: result.append(InvertedBoard(i)) return result
1668f71546bb5de1df2f4ba55a41d4dd76f54853
heidekrueger/f00b4r-Challenge
/Level 3.1 - b0mb-b4by/solution.py
2,568
3.875
4
def solution(m,f): """ Solution to the bomb-baby puzzle. Here, we are given some dynamical update rules, a pair (m,f) could be succeeded either by (m+f,f) or (m,m+f). Given two numbers (m,f), we are tasked with finding the shortest path (in generations) to generate (m,f) from (1,1), or to determine that the outcome is impossible. The 'real challenge' is finding an efficient implementation, in particular, avoiding deep recursion stacks and 'skipping' recursion loops that can be determined a-priori to be unnecessary. Args: m, f (str): string represenations of integers. Returns: (str): number of generations to generate (m,f) from initial state (1,1) or 'impossible' Constraints: m and f should be string represenations of integers below 10^50. Implementation: We backpropagate through the generation graph until we hit an edge case for which we can make a definitive decision. """ m = int(m) f = int(f) # number of accumulated generations n = 0 ## A tail-recursive implementation with constant memory usage ## is easily possible, but unfortunately Python cannot handle/optimize ## tail recursion, and is still limited by maximum recursion depth. ## We'll thus implement tail-recursion implicitly via a loop: while True: # The entire generation poset is symmetric, # so we can reduce the problem to m >= f # without affecting the output in any way if m < f: m, f = f, m ## Base cases: # Base case 1: Negative or zero inputs? --> impossible if m<1 or f<1: return "impossible" # Base case 2: (m, 1) # It takes (m-1) generations to generate the tuple (m, 1), i.e. # when always choosing the transition (m,1) -> (m+1, 1) if f==1: return str(n + m-1) ## Recursive case: go down the tree # (m,f) could have been generated from (m-f, f) or (m, f-m) # (or their symmetries) but we know that m >= f # so f-m will be <1 and we can ignore that branch. # As long as m will remain greater than f after the update, # we already know that would end up in the recursive case again # in the next step, so we can directly take multiple steps at # once in order to avoid unnecessary iterations: steps = m // f n += steps m -= steps * f
0d3ba1b8a0884c431f64a996c0b9a5696e5c93fc
foulp/AdventOfCode2019
/src/Day22.py
2,648
3.53125
4
class Shuffle: def __init__(self, size_of_deck): self.deck_size = size_of_deck @staticmethod def cut(n): # f(x) = ax + b % deck_size, with a=1 and b=-n return 1, -n @staticmethod def deal_with_increment(n): # f(x) = ax + b % deck_size, with a=n and b=0 return n, 0 @staticmethod def deal_into_new_stack(): # f(x) = ax + b % deck_size, with a=-1 and b=deck_size-1 return -1, -1 def full_shuffle(self, commands): # With f(x) = a'x + b' % deck_size, and g(x) = ax + b % deck_size # f(g(x)) = a'ax + (a'b + b') % deck_size full_a, full_b = 1, 0 for technique in commands: if technique.startswith('deal with increment'): aa, bb = self.deal_with_increment(int(technique.split()[-1])) elif technique.startswith('cut'): aa, bb = self.cut(int(technique.split()[-1])) elif technique.startswith('deal into new stack'): aa, bb = self.deal_into_new_stack() else: raise ValueError(f"Did not understand command: {technique}") full_b = (bb + aa * full_b) % self.deck_size full_a = (full_a * aa) % self.deck_size return full_a, full_b if __name__ == '__main__': with open('../inputs/Day22_input.txt', 'r') as f: commands_list = f.read().split('\n') deck_size = 10007 start_pos = 2019 shuffle = Shuffle(deck_size) a, b = shuffle.full_shuffle(commands_list) answer = (a * start_pos + b) % deck_size print(f"The result of first star is {answer}") # Solve a*x+b = end_pos [deck_size] # => a*x = (end_pos-b) [deck_size] # => x = (end_pos-b) * inv_mod(a, deck_size) [deck_size] if GCD(a, deck_size) == 1 # NB : inv_mod(a, m) is x in range(0, m) such that a*x = 1 [m], exists iff GCD(a, m) = 1 # NB : inv_mod(a, deck_size) = pow(a, deck_size-2, deck_size) valid iff deck_size is prime assert start_pos == (answer - b) * pow(a, deck_size-2, deck_size) % deck_size n_turns = 101741582076661 deck_size = 119315717514047 end_pos = 2020 shuffle = Shuffle(deck_size) a, b = shuffle.full_shuffle(commands_list) # f^-1(x) = inv_mod(a, deck_size) * (x-b) % deck_size # f^n(x) = a**n * x + b * (1 + a + a**2 + a**3 + ... + a**(n-1)) % deck_size a_final = pow(a, n_turns, deck_size) b_final = b * (pow(a, n_turns, deck_size) - 1) * pow(a-1, deck_size-2, deck_size) % deck_size answer = (end_pos - b_final) * pow(a_final, deck_size-2, deck_size) % deck_size print(f"The result of second star is {answer}")
74d654a737cd20199860c4a8703663780683cea4
quanzt/LearnPythons
/src/guessTheNumber.py
659
4.25
4
import random secretNumber = random.randint(1, 20) print('I am thinking of a number between 1 and 20.') #Ask the player to guess 6 times. for guessesTaken in range(1, 7): print('Take a guess.') guess = int(input()) if guess < secretNumber: print('Your guess is too low') elif guess > secretNumber: print('Your guess is too high') else: break if guess == secretNumber: print(f'Good job. You are correct. The secret number is {str(secretNumber)}') else: print('Sorry, your guess is wrong. The secret number is {}'.format(secretNumber)) # # for i in range(20): # x = random.randint(1, 3) # print(x)
b3e1e98d777d82610e8215a3a44ae6803f3fe502
fucct/Algorithm-python
/leetcode/leetcode83.py
594
3.5
4
from leetcode.leetcode21 import ListNode class Solution83: def deleteDuplicates(self, head: ListNode) -> ListNode: result = [] while head: if not result: result.append(head.val) head = head.next continue if not head.val == result[-1]: result.append(head.val) head = head.next if not result: return resultNode = ListNode(result.pop()) while result: resultNode = ListNode(result.pop(), resultNode) return resultNode
ea076830b85f656b4467da07eac0376eb5f9c1e3
fucct/Algorithm-python
/leetcode/leetcode9.py
335
3.734375
4
import functools class Solution9: def isPalindrome(self, x: int) -> bool: string = str(x) split_list = [char for char in string] reversed_list = split_list[:] reversed_list.reverse() return functools.reduce(lambda x, y: x and y, map(lambda p, q: p == q, split_list, reversed_list), True)
4e013101f7527171160a6b6d6e17a635557e288e
fucct/Algorithm-python
/leetcode/leetcode2.py
1,285
3.59375
4
from leetcode.leetcode21 import ListNode class Solution2: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = [] adder = 0 while l1 and l2: num = l1.val + l2.val + adder if num >= 10: result.append(num-10) adder = 1 else: result.append(num) adder = 0 l1 = l1.next l2 = l2.next while l1: num = l1.val + adder if num >= 10: result.append(num - 10) adder = 1 else: result.append(num) adder = 0 l1 = l1.next while l2: num = l2.val + adder if num >= 10: result.append(num - 10) adder = 1 else: result.append(num) adder = 0 l2 = l2.next if adder == 1: result.append(adder) if not result: resultNode = ListNode() return resultNode num = result.pop() resultNode = ListNode(num) while result: num = result.pop() resultNode = ListNode(num, resultNode) return resultNode
2377bc9128134917060ce847fba3a7e6a292039c
hungrytech/Practice-code
/DFS and BFS/DFS practice1.py
533
3.578125
4
def dfs(graph, start_node) : visited, need_visit= list(), list() need_visit.append(start_node) while need_visit : node = need_visit.pop() if node not in visited : visited.append(node) need_visit.extend((graph[node])) return visited data=dict() data['A'] = ['B','C'] data['B'] = ['A','D'] data['C'] = ['A','G','H','I'] data['D'] = ['E','F'] data['E'] = ['D'] data['F'] = ['D'] data['G'] = ['C'] data['H'] = ['C'] data['I'] = ['C','J'] data['J'] = ['I'] print(dfs(data, 'A'))
a2d8ccafa4d89411f84960155771597179447ea9
hungrytech/Practice-code
/Sort/firt print low grade.py
490
3.625
4
# 이것이 코딩테스트다 정렬 알고리즘 학습 # 문제를 읽고 직접 짜본 코드이다. # 알고리즘을 구상하다 모르겠으면 해답을보고 다시 구상해본다. # 문제: 성적이 낮은 순서로 학생 출력하기 n = int(input()) data=[] for i in range(n) : data_input = input().split() data.append((data_input[0],int(data_input[1]))) result= sorted(data, key=lambda student: student[1]) for student in result : print(student[0], end=' ')
915bb8a872505cf0c476815b0045a36842f8687a
hungrytech/Practice-code
/python/UniversityProject2.py
479
3.84375
4
def slice (String) : # ACG로 시작하고 TAT로 종결되는 슬라이싱 함수 start_ACG=String.find('ACG') #ACG가 시작하는 index start_TAT=String.find('TAT') #TAT가 시작하는 index slice_String = String[start_ACG:start_TAT+3] #ACG시작하는 index 부터 TAT가 끝나는 index까지 slicing return slice_String sequence="TACTAAAACGGCCCTTGGGAACCTATAAAGGCAATATGCAGTAG" #---------출력--------- print(slice(sequence)) #slicing한 결과값 출력
2d9a7d0568cdf890ebf8b3fbbce6de67a8dc3dcb
hungrytech/Practice-code
/BaekJoon/BaekJoon1427myThink.py
169
3.578125
4
n = int(input()) n=str(n) data=list() for i in n : data.append(int(i)) data = sorted(data, reverse=True) result="" for i in data : result+=str(i) print(result)
b2e1cce90b9e3b64a5d21e00460b69136fcf3267
cjakuc/cs-module-project-recursive-sorting
/src/sorting/sorting.py
3,250
4.0625
4
# TO-DO: complete the helper function below to merge 2 sorted arrays def merge(arrA, arrB): elements = len(arrA) + len(arrB) merged_arr = [0] * elements # Your code here if len(arrA) == 0: return list_right elif len(arrB) == 0: return list_left x = 0 y = 0 merged_idx = 0 while merged_idx < elements: if arrA[x] <= arrB[y]: merged_arr.append(arrA[x]) x += 1 else: merged_arr.append(arrB[y]) y += 1 # If we are at the end of one of the lists we can take a shortcut if y == len(arrB): # Reached the end of right # Append the remainder of left and break merged_arr += arrA[x:] break elif x == len(arrA): # Reached the end of left # Append the remainder of right and break merged_arr += arrB[y:] break return merged_arr # TO-DO: implement the Merge Sort function below recursively def merge_sort(arr): # Your code here # if len(arr) > 1: # return arr # else: # middle = len(arr)//2 # left = arr[:middle] # right = arr[middle:] # return merge(mere_sort(left), merge_sort(right)) # return arr if len(arr) > 1: middle = len(arr)//2 left = arr[:middle] right = arr[middle:] merge_sort(left) merge_sort(right) # arr = merge(left, right) x = 0 y = 0 merged_idx = 0 while x < len(left) and y < len(right): if left[x] < right[y]: arr[merged_idx] = left[x] x += 1 else: arr[merged_idx] = right[y] y += 1 merged_idx += 1 while x < len(left): arr[merged_idx] = left[x] x += 1 merged_idx += 1 while y < len(right): arr[merged_idx] = right[y] y += 1 merged_idx += 1 return arr # STRETCH: implement the recursive logic for merge sort in a way that doesn't # utilize any extra memory # In other words, your implementation should not allocate any additional lists # or data structures; it can only re-use the memory it was given as input # def merge_in_place(arr, start, mid, end): # # Your code here # def merge_sort_in_place(arr, l, r): # if len(arr) > 1: # middle = len(arr)//2 # left = arr[:middle] # right = arr[middle:] # merge_sort(left) # merge_sort(right) # # arr = merge(left, right) # x = 0 # y = 0 # merged_idx = 0 # while x < len(left) and y < len(right): # if left[x] < right[y]: # arr[merged_idx] = left[x] # x += 1 # else: # arr[merged_idx] = right[y] # y += 1 # merged_idx += 1 # while x < len(left): # arr[merged_idx] = left[x] # x += 1 # merged_idx += 1 # while y < len(right): # arr[merged_idx] = right[y] # y += 1 # merged_idx += 1 # return arr
9689376936022dc428cb1f59960ee7d920e1d031
Great-special/sales-analysis_2
/Data-Insight/sales_analysis.py
7,985
4.1875
4
import pandas as pd import matplotlib.pyplot as plt ####### Loading Data/File ####### d_f = pd.read_csv('10000 sales records.csv') #print(d_f.head(10)) ## Getting the headers headers = d_f.columns # print(headers) # print(d_f.describe()) ####### Working with the loaded Data ####### ## Q1: Which columns(Country) has the highest(most) sales """ To get the highest sales you need to multiply the quantity with the price per unit """ country_HighestSales = d_f.groupby('Country').max()[['Units Sold']] #print(country_HighestSales) country_HighestSales.to_excel('Countries with their sales.xlsx') ## Getting the country with highest Cost Price totalCP = d_f['Total Cost'].max() countryTCP = d_f.loc[d_f['Total Cost'] == totalCP] #print(countryTCP) ## Q2: Which columns(Month) has the highest sales """ To get the Month with the highest sales you need to get the months and sum up each month """ ## Adding the month column and Getting the highest sales """Converting the column to datetime format and adding Month column""" d_f['Ship Date'] = pd.to_datetime(d_f['Ship Date']) d_f['Order Date'] = pd.to_datetime(d_f['Order Date']) d_f['Month'] = d_f['Order Date'].dt.strftime('%m') d_f['Year'] = d_f['Order Date'].dt.strftime('%Y') #print(d_f.head(10)) #print(d_f.iloc[0]) #print(d_f.iloc[2]) "The (groupby()) method/function is used to sort by a column" month_HighestSales = d_f.groupby('Month').sum()[['Units Sold', 'Total Cost', 'Total Revenue', 'Total Profit']] #print(month_HighestSales) #month_HighestSales.to_csv('Months and their sales.csv') ## Q3: What is the most effective sales channel """ Find the channel with highest number of sales To get the most effective sales channel you have to groupby the sales channel column """ no_of_time_online = len(d_f[d_f['Sales Channel'] == 'Online']) no_of_time_offline = len(d_f[d_f['Sales Channel'] == 'Offline']) #print(f'Len of online = {no_of_time_online} \n len of offline = {no_of_time_offline}') sale_cha = d_f.groupby('Sales Channel').sum()[['Units Sold', 'Total Cost', 'Total Revenue', 'Total Profit']] sale_cha['Total Count'] = [no_of_time_offline, no_of_time_online] #print(sale_cha) #sale_cha.to_csv('Most effective sales channel.csv') ## Q4: Which product is the most sold """ Find the product with highest number of sales To get the most sold product, you have to groupby the product column """ item_sale = d_f.groupby('Item Type').sum()[['Units Sold', 'Total Cost', 'Total Revenue', 'Total Profit']] product_most = item_sale.loc[item_sale['Units Sold'] == item_sale['Units Sold'].max()] #print(product_most) #item_sale.to_excel('Items and Sales.xlsx') ## Q5: Which country and region buys the most sold product """ Find and get the most sold product To get the country and region, you have to locate and stort by the coutry, region column Created a new dataframe and made a group from it """ """ To get product name, we need to filter by units sold, then get the index of the row and item(product)""" max_unit = item_sale.loc[item_sale['Units Sold'] == item_sale.iloc[9][0]] #print(max_unit) country_item_sale = d_f[d_f['Item Type'] == 'Personal Care'][['Region', 'Country', 'Units Sold', 'Total Cost', 'Total Revenue', 'Total Profit']] #print(country_item_sale) p_care = country_item_sale.groupby(['Country', 'Region']).sum()[['Units Sold', 'Total Cost', 'Total Revenue', 'Total Profit']] # print(p_care) p_care_limit = p_care.loc[p_care ['Units Sold'] >= 30000] # print(p_care_limit) #p_care.to_excel('Countries & regions that buys the most sold product.xlsx') ## Q6: Which country has the highest cost price country_TCP = country_item_sale.groupby('Country').sum()[['Total Cost']] #print(country_TCP) #country_TCP.to_excel('Country and cost price.xlsx') ## Q7 & 8: Which columns(Country)/ (product) has the highest profit 32454798.26 HighestProfit_country = d_f.groupby('Country').sum()[['Total Profit']] limit_ = HighestProfit_country['Total Profit'].max() - 10000000 top_countryProfit = HighestProfit_country.loc[HighestProfit_country['Total Profit'] >= limit_ ] #HighestProfit_country.to_excel('country, product and profit.xlsx') HighestProfit_item = d_f.groupby('Item Type').sum()[['Total Profit']] #print(HighestProfit_item) #HighestProfit_item.to_excel('Product and profit.xlsx') ## Q9: Which columns(Month) has the highest sales year_sale = d_f.groupby(['Year']).sum()[['Units Sold', 'Total Profit']] #print(year_sale) #year_sale.to_excel('yearly sales.xlsx') ## Q10: Which Products were sold together ordered_together = d_f[d_f['Order ID'].duplicated(keep=False)] print(ordered_together) ### Visualization Of Data ### plt.style.use('seaborn') ## V1: Which columns(Country) has the highest(most) sales # countries = [country for country, df in d_f.groupby('Country')] # plt.bar(countries, country_HighestSales['Units Sold']) # plt.xticks(countries, rotation='vertical', size=8) # plt.xlabel('Countries') # plt.ylabel('Unit Sold') # plt.show() # ## V2: Which columns(Month) has the highest sales # months = range(1,13) # plt.bar(months, month_HighestSales['Units Sold']) # plt.xticks(months) # plt.xlabel('Month') # plt.ylabel('Unit Sold') # plt.show() ## V3: What is the most effective sales channel " In bar; (X-axis, Y-axis)" # chan = ['Offline', 'Online'] # plt.bar(chan, sale_cha['Units Sold']) # plt.xticks(chan) # plt.xlabel('Sales Channel') # plt.ylabel('Unit Sold') # plt.show() ## V4: Which product is the most sold # items = [item for item, df in d_f.groupby('Item Type')] # plt.bar(items, item_sale['Units Sold']) # plt.xticks(items, rotation='vertical', size=8) # plt.title('Most Sold Product') # plt.xlabel('Items') # plt.ylabel('Units Sold') # plt.grid(True, color='black') # plt.show() ## V5: Which country and region buys the most sold product # countryItemSale = [con for con, df in p_care_limit.groupby('Country')] # plt.bar(countryItemSale, p_care_limit['Units Sold']) # plt.xticks(countryItemSale, rotation='vertical', size=8) # plt.title('Some Countries that buys the most sold product') # plt.xlabel('Country') # plt.ylabel('Units Brought') # plt.grid(True, color='black') # plt.show() ## V6: Which country has the highest cost price # countryItemSale = [con for con, df in office_sup_TCP.groupby('Country')] # plt.bar(countryItemSale, office_sup_TCP['Total Cost Price']) # plt.xticks(countryItemSale, rotation='vertical', size=8) # plt.xlabel('Country') # plt.ylabel('Total Cost Price', rotation='vertical') # plt.show() ## V7: Which country has the highest profit # count_pro = [con for con, df in top_countryProfit.groupby('Country')] # plt.bar(count_pro, top_countryProfit['Total Profit']) # plt.xticks(count_pro, rotation='vertical', size=8) # plt.title('Country And Profit') # plt.xlabel('Country') # plt.ylabel('Total Profit', rotation='vertical') # plt.grid(True, color='Black') # plt.show() ## V8: Which item has the highest profit # _profit = [pro for pro, df in HighestProfit_item.groupby('Item Type')] # plt.bar(_profit, HighestProfit_item['Total Profit']) # plt.xticks(_profit, rotation='vertical', size=8) # plt.title('Products and profit') # plt.xlabel('Product') # plt.ylabel('Profit', rotation='vertical') # plt.grid(True, color='black') # plt.show() ## V9: Which columns(Month) has the highest sales # year_ = [year for year, df in d_f.groupby('Year')] # fig, ax1 = plt.subplots() # ax1.bar(year_, year_sale['Units Sold'], label='Units Sold') # ax2 = ax1.twinx() # ax2.plot(year_, year_sale['Total Profit'],label='Profit', color='red') #plt.xticks(HighestProfit_item['Unit Cost'], rotation='vertical', size=8) # ax1.set_title('Year, Sales And Profit') # ax1.tick_params(axis='y', rotation='auto', labelcolor='blue') # ax1.set_ylabel('Units Sold', color='blue') # ax2.tick_params(axis='y', rotation='auto', labelcolor='red') # ax2.set_ylabel('Profit', color='red') # ax1.set_xlabel('Year') # plt.grid(False) # plt.show() ## V10: Which Products were sold together
2cc359c82b856fe75eed2906e36f9fa18f6de8cc
BarbaraRafal/SDA_exercises
/testowanie_tdd/home_work/home_work_jadwiga.py
1,875
3.734375
4
from datetime import datetime from typing import Tuple class Book: ALLOWED_GENRES: Tuple = ( "Fantasy", "Science Fiction", "Thriller", "Historical", "Romance", "Horror", ) def __init__(self, title: str, author: str, book_genre: str) -> None: self.title = self.validate_title(title) self.author = author self.book_genre = self.validate_genre(book_genre) def validate_title(self, title: str) -> str: if not isinstance(title, str) or title == "": raise ValueError("Title is incorrect!") return title def validate_genre(self, genre: str) -> str: if genre not in self.ALLOWED_GENRES: raise ValueError(f"Genre:{genre} is incorrect") return genre def __repr__(self) -> str: return self.title class Author: def __init__(self, name: str, year_of_birth: int) -> None: self._name = name self._year_of_birth = year_of_birth self._book_list = [] def add_book(self, title: str, book_genre: str) -> None: self._book_list.append(self._create_book(title, book_genre)) def _create_book(self, title: str, book_genre: str) -> Book: return Book(title, self._name, book_genre) @property def age(self): author_age = datetime.now().year - self._year_of_birth return author_age @property def name(self): return self._name @property def book_list(self): return self._book_list # def get_content_from_google(self): # """This method is used to help understanding mocks""" # content = requests.get("https://www.google.com") # # print(content.text) # return content.status_code author1 = Author("Jan Kowalski", 1985) author1.add_book("Tytuł", "Fantasy") # author1.get_content_from_google()
587d31d1aa464c529e14659857ff52d4629e5700
BarbaraRafal/SDA_exercises
/testowanie_tdd/tdd_day1/account.py
479
3.5
4
class Account: def __init__(self, balance_amount: float, user_status: str) -> None: self.balance_amount = balance_amount self.user_status = user_status def transfer(self, amount_of_money: float) -> float: try: self.balance_amount += amount_of_money except TypeError: print(f"{amount_of_money} is not a float!") return self.balance_amount def balance(self) -> float: return self.balance_amount
0a5d7f42c11be6f4fb2f9ede8340876192080d8d
Dana-Georgescu/python_challenges
/diagonal_difference.py
631
4.25
4
#!/bin/python3 ''' Challenge from https://www.hackerrank.com/challenges/diagonal-difference/problem?h_r=internal-search''' # # Complete the 'diagonalDifference' function below. # # The function is expected to return an INTEGER. # The function accepts 2D_INTEGER_ARRAY arr as parameter. # def diagonalDifference(): arr = [] diagonal1 = diagonal2 = 0 n = int(input().strip()) for s in range(n): arr.append(list(map(int, input().rstrip().split()))) for i in range(n): diagonal1 += arr[i][i] diagonal2 += arr[i][-(i+1)] return abs(diagonal1 - diagonal2) print(diagonalDifference())
9ae095de08c2cf599b1d731858f3cb0ab5e5be11
pedro-espinosa/matching_pennies
/stimuli.py
1,285
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Module containing functions for generating visual stimuli """ import os #%% Welcome, instructions and first choice welcome_text = """ Welcome! In this experiment you will play a game of 'Matching Pennies' against a computer. Each player has a coin. Every round, the players decide which side of their coin to show. If both coins have the same side up, you get a point. If the coins have different sides up the computer gets a point. Press space bar to continue. """ instructions_text = """ Instructions: Press 'H' to choose Heads Press 'T' to choose Tails Press 'Q' at any time to quit Now, press the space bar to start. """ choice_text = """ Heads or Tails? (Q to quit) """ #%% Score text score_text = "{} - {}\n spacebar to continue" #%% filepaths for outcome images f_hh = os.path.join('images', 'hh.jpg') f_tt = os.path.join('images', 'tt.jpg') f_ht = os.path.join('images', 'ht.jpg') f_th = os.path.join('images', 'th.jpg') #%% Final score screen #This stimulus is in main.py under '#%% Final score screen' (for simplicity) #%% Summary printout for experimenter to see in the console when trial is over #This text runs in resultsPrintout() function in the class Data found in the strategy_functions module.
0d38d3e0de7b6950364dff49b4592cd629e26408
lukejpie/Machine-Learning-Final-Project
/project-lpietra1/run_logistic_regression.py
4,516
3.6875
4
""" Run Logistic Regression: Author: Luke Pietrantonio Created: 5/7/19 Description: Transforming the linear regression problem into a logistic problem by having "high" and low days, as opposed to linear regression """ import math as m import matplotlib.pyplot as plt import numpy as np from utils import * from dataset import Dataset from sklearn import utils from sklearn.linear_model import LogisticRegression from sklearn.metrics import mean_squared_error def create_regressions(num_regr): """ Description: Creates all of instances of the regressions that we need Params: Number of regressions Returns: List of instantiated regressions """ regrs = [] for i in range(num_regr): regrs.append(LogisticRegression(solver='lbfgs',max_iter=500)) return regrs def train_regressions(regrs,X_train,y_train): """ Description: Trains all of the regressions with each of the corresponding datasets Params: regrs-List of instantiated regressions, X_train-List of X_train datasets, y_train-List of y_train datasets Returns: Fitted regressions """ i = 0 for regr in regrs: regr.fit(X_train[i],y_train[i]) i += 1 #print('reg done') return regrs def predict(regrs,X_test): """ Description: Performs predictions for each regression on its appropriate test dataset Params: regrs-List of trained regressions, X_test-List of X_test datasets Returns: y_preds-List of list of predictions of y values from X_test """ y_preds = [] i = 0 for regr in regrs: y_preds.append(regr.predict(X_test[i])) i += 1 #print('pred done') return y_preds def score(regrs,X_test,y_test): """ Description: Returns the Scores of each regression Params: X_test, y_test Returns: List of scores """ scores = [] i=0 for regr in regrs: scores.append(regr.score(X_test[i],y_test[i])) i+=1 return scores def linToLog(y): """ Description: Reclassifies linear output as high or low Params: y-All of the y values from the dataset Returns: Classified y values """ mid = y.median() y[y<=mid] = 0 y[y> mid] = 1 return y def featureimportances(X_train,regrs): """ Description: Averages all of the feature importances across all of the models Params: regrs-List of all of the models Returns: List of averaged feature importances """ numFeatures = X_train[0].shape[1] fi = np.zeros(numFeatures) for i in range(len(regrs)): fiT = regrs[i].coef_.flatten() fiT = X_train[i].std(0)*fiT fi = np.add(fi,fiT) fi = fi/len(regrs) return fi def plotFI(featureimportances): objects = ('season','mnth','hr','holiday','weekday','workingday','weathersit','temp','atemp','hum','windspeed') y_pos = np.arange(len(objects)) plt.bar(y_pos, featureimportances, align='center', alpha=0.5) plt.xticks(y_pos, objects) plt.ylabel('Importance') plt.title('Feature Importance Over All Models') plt.show() def main(): divisions = 500 ds = Dataset() ds.load("Bike-Sharing-Dataset/hour.csv") size = ds.get_size() X = [] y =[] percentages = [] #Full X and y from dataset all_X = ds.get_x() all_y = ds.get_y() print(all_y.median()) #Transforms linear classifications into classifications all_y = linToLog(all_y) #Shuffle data and split into divisons for i in range(1,divisions+1): percentage = (1/divisions * i) percentages.append(percentage) all_X,all_y = utils.shuffle(all_X,all_y) X.append(all_X[:int(size*percentage)]) y.append(all_y[:int(size*percentage)]) #Splits training and testing data X_train, X_test, y_train, y_test = split(X,y) #Create List of Regressions regrs = create_regressions(divisions) #Train all regressions regrs = train_regressions(regrs,X_train,y_train) #Perform Predictions #y_pred = predict(regrs,X_test) # Calculate Scores from the Models scores = score(regrs,X_test,y_test) print('Scores:') print(scores) print('mean') print(y_test[0].mean(axis=0)) # print(regrs[0].coef_) plt.scatter(percentages,scores) plt.ylabel('Score') plt.xlabel('Percentage of Original Dataset') plt.title('Percentage of Original Dataset vs Score') plt.show() fi = featureimportances(X_train,regrs) plotFI(fi) if __name__ == '__main__': main()
fec59c99e4a986c3d9a09abb51e8485cc2dc739f
NIHanifah/phyton-prak9
/nomor4.py
399
3.90625
4
#mengacak huruf pada kata #menggunakan shuffle import random import collections #membuat susunan huruf yang berbeda def shuffleString(x, n): kata = list(x) listKata = [] k = 0 while k < n: random.shuffle(kata) hasil = ''.join(kata) if hasil not in listKata: listKata.append(hasil) k += 1 print(listKata) shuffleString('aku', 3)
b25933e9e0414b96f98c600606aebcfc1e7e8d73
chaemoong/SmartDelivery
/utils/module.py
1,682
3.546875
4
""" 위 모듈은 개발자 뭉개구름이 제작하였으며 무단으로 사용할 경우 라이선스 위반에 해당됩니다. """ import json class Module(): def __init__(self): self.module = 'JSON 모듈입니다!' def save(self, filename, data): print(f'[JSON MODULE] [작업시도] {filename} 파일을 저장중입니다...') with open(filename, encoding='utf-8', mode='w') as f: json.dump(data, f, sort_keys=True, separators=(',',' : '), ensure_ascii=False) print(f'[JSON MODULE] [Success] {filename} 파일을 성공적으로 저장하였습니다!') return data def open(self, filename): print(f'[JSON MODULE] [작업시도] {filename} 파일을 여는중입니다...') with open(filename, encoding='utf-8', mode='r') as f: data = json.load(f) print(f'[JSON MODULE] [Success] {filename} 파일을 성공적으로 열었습니다!') return data def is_vaild(self, filename): print(f'[JSON MODULE] [작업시도] {filename} 파일이 있는지 확인하는중입니다...') try: self.open(filename) print(f'[JSON MODULE] [Success] {filename} 파일이 정상적으로 감지되었습니다!') return True except FileNotFoundError: print(f'[JSON MODULE] [Failed] {filename} 파일이 정상적으로 감지하지 못했습니다...') return False except json.decoder.JSONDecodeError: print(f'[JSON MODULE] [Failed] {filename} 파일이 정상적으로 감지하지 못했습니다...') return False
537eb97c8fa707e1aee1881d95b2bf497123fd67
jeffsilverm/big_O_notation
/time_linear_searches.py
2,520
4.25
4
#! /usr/bin/env python # # This program times various search algorithms # N, where N is the size of a list of strings to be sorted. The key to the corpus # is the position of the value to be searched for in the list. # N is passed as an argument on the command line. import linear_search import random import sys corpus = [] value_sought_idx = -1 def random_string( length ): """This function returns a random ASCII string of length length""" s = '' for i in range(length ): # Generate a random printable ASCII character. This assumes that space is a # printable character, if you don't like that, then use ! ) s = s + ( chr( random.randint(ord(' '), ord('~') ) ) ) return str( s ) def create_corpus(N): """This function returns a corpus to search in. It generates a sorted list of values which are random strings. It then sorts the list. Once the corpus is created, it gets saved as a global variable so that it will persist""" global corpus global value_sought_idx for i in range(N): corpus.append( random_string(6)) # corpus.sort() # linear search does not need the corpus to be sorted value_sought_idx = random.randint(0,N-1) return def call_linear_search(value_sought): """Call the iterative version of the binary search""" # We need to do make a subroutine call in the scope of time_searches so we can # pass the global variable corpus. corpus is out of scope of the actual # binary search routine, so we have to pass it (it gets passed by reference, # which is fast) linear_search.linear_search(corpus, value_sought) N = int(sys.argv[1]) create_corpus(N) if __name__ == '__main__': import timeit number = 100 # number of iterations tq = '"""' # Need to insert a triple quote into a string value_sought = corpus[value_sought_idx] # This is a little pythonic trickery. The input to the timeit.timeit method is # a snippet of code, which gets executed number of times. In order to # parameterize the code, use string substitution, the % operator, to modify the # string. Note that this code has to import itself in order to get the # subroutines in scope. linear_call_str = "time_linear_searches.call_linear_search( " + \ tq + value_sought + tq + ")" linear_time = timeit.timeit(linear_call_str, \ setup="import time_linear_searches", number=number) print "linear search: %.2e" % linear_time
abbb02f14ecbea14004de28fc5d5daddf65bb63e
jeffsilverm/big_O_notation
/iterative_binary_search.py
1,292
4.1875
4
#! /usr/bin/env python # # This program is an implementation of an iterative binary search # # Algorithm from http://rosettacode.org/wiki/Binary_search#Python def iterative_binary_search(corpus, value_sought) : """Search for value_sought in corpus corpus""" # Note that because Python is a loosely typed language, we generally don't # care about the datatype of the corpus low = 0 high = len(corpus)-1 while low <= high: mid = (low+high)//2 if corpus[mid] > value_sought: high = mid-1 elif corpus[mid] < value_sought: low = mid+1 else: return mid # Return the index where the value was found. return -1 # indicate value not found if "__main__" == __name__ : import time_searches # We need this to create the corpus and value_sought value_sought = time_searches.corpus[time_searches.value_sought_idx] print "The value sought is %s" % value_sought print "The size of the corpus is %d" % len ( time_searches.corpus ) answer_idx = iterative_binary_search(time_searches.corpus, value_sought) print "The answer is at %d and is %s" % ( answer_idx, time_searches.corpus[answer_idx] ) print "The correct answer is %d" % time_searches.value_sought_idx
2b0a86e5ff0a45d03c215f3a164b2e9882613c55
alklasil/SScript
/SScriptCompiler/src/common.py
215
3.671875
4
def flattenList(l): l_flattened = [] for item in l: if type(item) is list: l_flattened.extend(flattenList(item)) else: l_flattened.append(item) return l_flattened
8f623a197814365cb7aa43bd2bce8f6dace96e4a
DerrickKnighton/Min-Sum-Partition
/minsumpartition.py
3,589
3.671875
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 17:09:14 2019 @author: Derrick Found this problem online for interview prep and it didnt seem too bad so i gave it a try didnt take super long """ class Min_Sum_Partition(): import numpy as np def create_Random_Array(self,range_Of_Ints,size_Of_Arr): #creates random array #range_Of_Ints is [0,num you chose) arr = np.random.randint(range_Of_Ints, size=size_Of_Arr) return arr def Partition(self,arr): #split array into 2 sub arrays such that the summation of he 2 is minimized #Algo idea find max in the input array add it to ont of the arrays such that #the difference of the summation of the arrays is smaller than if you added it to the other #if the difference of them is the same add to array 2 it doesnt really mater what one you add it to #continue until arr is size 0 sub_arr_one = np.ndarray([0]) sub_arr_two = np.ndarray([0]) #this algo works with only posiive numbers to init max to negative max = np.argmax(arr) num_to_add = -1000 sum1 = 0 sum2 = 0 while arr[max] != 0: print(arr) print(arr[max]) ##################################################### #if statements take max in arr add to one sub_arr delete the max element in #arr and change the bool so next max is added to other sub arr #let it be known it is completely unesscessary to add these vals to arrays #this could be accomplished more efficiently by just summing the values #immediately and that would take up less space i just wanted to #do it his way to show the arrays so you can see where the values ended up sum1_Try = sum1 + int(arr[max]) sum2_Try = sum2 + int(arr[max]) if abs(sum1_Try - sum2) < abs(sum2_Try - sum1): num_to_add = arr[max] sub_arr_one = np.append(sub_arr_one,[num_to_add]) sum1 += arr[max] arr[max] = 0 elif abs(sum1_Try - sum2) > abs(sum2_Try - sum1): num_to_add = arr[max] sub_arr_two = np.append(sub_arr_two,[num_to_add]) sum2 += arr[max] arr[max] = 0 elif abs(sum1_Try - sum2) == abs(sum2_Try - sum1): num_to_add = arr[max] sub_arr_two = np.append(sub_arr_two,[num_to_add]) sum2 += arr[max] arr[max] = 0 max = np.argmax(arr) ##################################################### return sub_arr_one, sub_arr_two def Min_Sum(self,sub_arr_one, sub_arr_two): ########################################################## #sum sub arrs and take difference sum1 = np.sum(sub_arr_one) sum2 = np.sum(sub_arr_two) print(sum1,sum2) final_Answer = np.abs(sum1 - sum2) ########################################################## return(final_Answer) if __name__ == "__main__": run = Min_Sum_Partition() arr = run.create_Random_Array(1000,100) arr2 = [1,1,3,4,7] sub_arr_one, sub_arr_two = run.Partition(arr) print(run.Min_Sum(sub_arr_one,sub_arr_two))
ecc686dc19b4bdf92585421e6bb161e8e6b59dd8
chrisxwan/codeboola-game
/scaffold.py
4,382
3.609375
4
import random class Player(object): max_hp = 100 current_hp = 100 # Check if the player is still alive # by ensuring that his current hp is greater than 0 def is_alive(self): # Fill this in! # Return True or False depending on whether the Player's # attack was successful def successful_attack(self): # Fill this in! # Heal the Player, if his health is not full already def rest(self): # Fill this in! # The player has been damaged! Decrease the Player's # current health by the appropriate amount def damage(self, dmg): # Fill this in! def print_current_health(self): print("You currently have " + str(self.current_hp) + " health.") def info(self): print("You are " + self.name + " the " + self.player + "!") print("You attack with " + str(self.accuracy * 100) + "% accuracy.") print("Your successful attacks deal " + str(self.attack) + " damage.") print("Every time you heal yourself, you heal " + str(self.heal) + " health") def kill(self): self.max_hp = 0 class Archer(Player): # input the appropriate attributes for the Archer def __init__(self, name): # Fill this in! class Swordsman(Player): # input the appropriate attributes for the Swordsman def __init__(self, name): # Fill this in! class Healer(Player): # input the appropriate attributes for the Healer def __init__(self, name): # Fill this in! class GiantSpider(): # input the appropriate attributes for the Spider def __init__(self): # Fill this in! # Check if the spider is still alive # by ensuring that its current hp is greater than 0 def is_alive(self): # Fill this in! # The player has been damaged! Decrease the Spider's # current health by the appropriate amount def damage(self, dmg): # Fill this in! # Return True or False depending on whether the Plaeyer's # attack was successful def successful_attack(self): # Fill this in! def print_current_health(self): print("The enemy currently has " + str(self.hp) + " health.\n") def fight(player, enemy): while(player.is_alive() and enemy.is_alive()): player.print_current_health() enemy.print_current_health() move = input("What is your move? ") print("") while(move != "a" and move != "h"): print("Press a to attack, press h to heal\n") move = input("What is your move? ") print("") if(move == "a"): # Fill in this code! # What happens if the user wanted to attck? elif(move == "h"): # Fill in this code! # What happens if the user wanted to heal? if(enemy.successful_attack()): # Fill in this code! # What happens if the spider made a successful attack? else: # Fill in this code! # What happens if the spider missed its attack? return player.is_alive name= input("Hello! What's your name? ") while(name == ""): name = input("We will need your name to proceed! What is your name? ") player_class = input("Hi " + name + "! What class of character would you want to be? ") player = None while(player_class != "a" and player_class != "s" and player_class != "h"): print("") print("Press a to be an archer, press s to be a swordsman, press h to be a healer") player_class = input("What class of character would you want to be? ") # Based on what the user has chosen, how should you # initialize his/her character? if(player_class == "a"): # Fill this in! elif(player_class == "s"): # Fill this in! elif(player_class == "h"): # Fill this in! print("") player.info() num_steps = 0 print("\nYou are in a tunnel, and you must get out! It will take 10 steps to get out, but as you walk along you may encounter some spiders that you will need to fight. \nIf at any point in the game you are unsure what the commands are, just hit enter and you'll receive some instructions. Good luck!\n") while(player.is_alive and num_steps < 10): step = input("What do you want to do? ") print("") if(step == "s"): # Fill in this code! What happens if a player takes a step? # Hint: In this step, the user either encounters a spider OR # the player does not encounter anything # What is the chance that the player encounters a spider? num_steps += 1 print("You have made a total of " + str(num_steps) + " steps!\n") elif(step == "q"): player.kill() print("Better luck next time!") break else: print("Press s to take a step, press q to quit") if(player.is_alive()): print("You won!")
d8b293f25173bbee6ddaa45118640f2ed7cdb1d0
VitorHSF/Programacao-Linear-E-Aplicacoes
/Exercicios- Matrizes III/EX03/ex03.py
853
3.703125
4
def getLinha(matriz, n): return [i for i in matriz[n]] def getColuna(matriz, n): return [i[n] for i in matriz] matriza = [[3, 4], [2, 3]] matrizalin = len(matriza) matrizacol = len(matriza[0]) matrizb = [[-1], [-1]] matrizblin = len(matrizb) matrizbcol = len(matrizb[0]) matRes = [] print() print('Matriz A') print('=-'* 5) for j in matriza: print(j) print('=-'* 5) print() print('Matriz B') print('=-'* 5) for j in matrizb: print(j) print('=-'* 5) print() for i in range(matrizalin): matRes.append([]) for j in range(matrizbcol): listMult = [x*y for x, y in zip(getLinha(matriza, i), getColuna(matrizb, j))] matRes[i].append(sum(listMult)) print('Multiplicação de duas matrizes:') print('=-'* 5) for j in matRes: print(j) print('=-'* 5) print()
09d18759aa23f1c7625ac83b5a93d4d15fd281e4
VitorHSF/Programacao-Linear-E-Aplicacoes
/Exercicios - Matrizes/EX04/ex04.py
865
3.59375
4
from time import sleep matriz = [[1, -1, 0], [2, 3, 4], [0, 1, -2]] matrizresult = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] matrizt= list(map(list, zip(*matriz))) print('=-=' * 20) print('Dada a Matriz A, obtenha a matriz B tal que B = A + At') print('\nMatriz A:') for j in matriz: print('{}'.format(j)) print() print('Matriz A Transposta:') for j in matrizt: print(j) for linha in range(0, 3): for coluna in range(0, 3): matrizresult[linha][coluna] = matriz[linha][coluna] + matrizt[linha][coluna] print() print('calculando.') sleep(2.0) print('calculando..') sleep(1.5) print('calculando...') sleep(1.0) print('\nMatriz B = A + A Transposta:') for linha in range(0, 3): for coluna in range(0, 3): print('[{:^5}]'.format(matrizresult[linha][coluna]), end='') print() print('=-=' * 20)
0fcbee7b0ba2d158317b40e5f47ff3242584fbef
wmackowiak/Zadania
/Zajecia07/fitmeter.py
369
3.59375
4
import bmi # podaj wagę i wrost weight = float(input("Podaj wagę w kg: ")) height = float(input("Podaj wzrost w m: ")) # wyślij wagę i wzrost do funkcji obliczjącej result_bmi = bmi.calculate_bmi(weight, height) state = bmi.get_state(result_bmi) print(state) filename = state.lower() + '.txt' with open(filename) as fopen: tip = fopen.read() print(tip)
e5416db47f43573132d34b69c15921ce623552e9
wmackowiak/Zadania
/Zajecia03/zad04.py
645
4.03125
4
#Stwórz skrypt, który przyjmuje 3 opinie użytkownika o książce. Oblicz średnią opinię o książce. # W zależności od wyniku dodaj komunikaty. Jeśli uzytkownik ocenił książkę na ponad 7 - bardzo dobry, ocena 5-7 przeciętna, 4 i mniej - nie warta uwagi. ocena1 = int(input("Jaka jest Twoja ocena ksążki?")) ocena2 = int(input("Jaka jest Twoja ocena ksążki?")) ocena3 = int(input("Jaka jest Twoja ocena ksążki?")) srednia = round(float((ocena1 + ocena2 + ocena3) / 3),0) print(srednia) if srednia > 7: print("bardzo dobry") elif srednia >=5 and srednia <=7: print("przeciętna") else: print("nie warta uwagi")
eb2c90826b55ccf8d43e3dba932787c72e33db74
wmackowiak/Zadania
/Zajecia04/dom06.py
357
3.953125
4
# 6▹ Utwórz listę zawierającą wartości poniższego słownika, bez duplikatów. # days = {'Jan': 31, 'Feb': 28, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sept': 30} for key in days.keys(): lista1 = list(set(days.keys())) for value in days.values(): lista2 = list(set(days.values())) print(lista1) print(lista2)
69bd4880aac5e7c71c7fe580c11a8e2bc48361cd
wmackowiak/Zadania
/Dodatkowe/zad27.py
202
3.796875
4
# Proszę za pomocą pętli while napisać ciąg składający się z 5 wielokrotności liczby 6. # # 6 # 12 # 18 # 24 # 30 x = 6 for i in range(5): while x <= 30: print(x) x = x + 6
cfe325d65dd4a17391dad5839290b4a2ea569127
wmackowiak/Zadania
/Zajecia06/zad05.py
1,053
3.84375
4
# Rozpoznawanie kart. Utwórz plik zawierający numery kart kredytowych. Sprawdź dla każdej kart jej typ. # Podziel kart do plików wg typów np. visa.txt, mastercard.txt, americanexpress.txt. def is_card_number(number): return number.isdecimal() and len(number) in (13, 15, 16) def starts_with_correct_digits(number): if 51 <= int(number[0:2]) <= 55: return True elif 2221 <= int(number[0:4]) <= 2720: return True else: return False with open('karty.txt', 'r', encoding='utf-8') as fopen: cards = fopen.read() cards = cards.split() for nr_card in cards: nr_card = input("Podaj nr karty: ") if is_card_number(nr_card): if len(nr_card) in [13,16] and nr_card[0] == '4': print("To jest Visa") elif len(nr_card) == 16 and starts_with_correct_digits(nr_card): print("To jest Mastercard") elif len(nr_card) == 15 and (nr_card[0:2] in ['34','37']): print("To jest American Express") else: print("Nie znam typu karty") else: print("To nie jest nr karty")
584d559437a74a7a34b4093d87ad6def1816c33a
wmackowiak/Zadania
/Zajecia03/dom4.py
373
3.546875
4
# Zapytaj użytkownika o numer od 1 do 100, jeśli użytkownik zgadnie liczbę ukrytą przez programistę wyświetl # komunikat “gratulacje!”, w przeciwnym razie wyświetl “pudło!”. liczba_uzytkownika = input("Podaj liczbę z przedziału od 1 do 100: ") moja_liczba = '45' if liczba_uzytkownika == moja_liczba: print("Gratulacje!") else: print("Pudło!")
e9f780995200a10c7fe117f01a283f5f95325f73
wmackowiak/Zadania
/Zajecia04/dom2.py
387
3.8125
4
# Utwórz dowolną tablicę n x n zawierającą dowolny znak, a następnie wyświetl jej elementy w formie tabeli n x n. # Elementy powinny być oddzielone spacją # wejście: # n = 3 # # tab = [['-', '-', '-'] # ['-', '-', '-'], # ['-', '-', '-']] # wyjście: # - - - # - - - # - - - # tablica = [[0] * cols] * rows tablica = [['-'] * 3] * 3 for x in tablica: print(x)
7d3d64976ba2bc6670ccbc2bb65dbecf20513e40
wmackowiak/Zadania
/Dodatkowe/zad11.py
240
3.71875
4
# Zwykle odliczanie wsteczne kojarzy nam się ze startem rakiety. Proszę o wygenerowanie liczb od 10 do zera i na końcu # będzie komunikat: „ Rakieta startuje!!!”. i=10 while i>=0: print(i) i=i-1 print("Rakieta startuje!!!")
71fb6862027166ebec778612f6acc48f47d51914
MatePaulinovic/thesis
/thesis/utils/array_util.py
1,202
3.515625
4
from typing import List import numpy as np def save_np_ndarray(string_format: str, string_args: List[str], destination_dir: str, array: np.ndarray ) -> None: """Saves numpy arrays with the specified format name to the output dir. Args: string_format (str): filename format the file should have string_args (List[str]): list of parameters to be inserted to the format destination_dir (str): directory where the file should be saved array (np.ndarray): the array that should be saved """ np.save((destination_dir + string_format).format(*string_args), array) def cut_np_2D_ndarray(array: np.ndarray, start_offset: int, end_offset: int ) -> np.ndarray: #TODO: add documentation return array[:, max(0, start_offset) : min(end_offset, array.shape[1])] def cut_np_1D_ndarray(array: np.ndarray, start_offset: int, end_offset: int ) -> np.ndarray: #TODO: add documentation return array[max(0, start_offset) : min(end_offset, len(array))]
70c18e3e9d4773c08f755826779661164264932c
atulmishr/Dtypes-work
/datatypes.py
608
3.953125
4
#python strings Atul="Welcome into the world of Bollywood" print(Atul) print(Atul*2) print(Atul[1:10]) print(Atul[9:]) print(Atul + "Atul Mishra with Sanjay Kapoor") #python Lists Heros = ['Aamir','Salman','Ranveer','Shahid','Akshay'] print(Heros) print(Heros[1:2]) print(Heros[2:]) Heroiens= ['Dyna','Katreena','Karishma','kareena','kirti'] print(Heros + Heroiens) #list operations Heros.append('Rajkumar Rao') print(Heros) Heroiens.insert(3,'Aalia') print(Heroiens) Heros.extend('Sonu sood') print(Heros) #deleting players=['Ronaldo,Messi','Dhoni','jadeja','Raina'] print(players) del players([1:3]) print(players)
a72b702f794d518d17e9fb30f29425b6253ffae0
MingjunGuo/bdt_5002
/assign1/A1_mguoaf_20527755_Q2_code.py
9,220
3.625
4
# -*-coding:utf-8-*- import csv import time def loadDataDict(filename): """ load data from file :param filename: filename :return: Dataset is a dict{(transcation):count,...} """ filename = filename # load data from given file,type is list with open(filename) as f: DataSet = csv.reader(f) # transform the datatype to dict DataDict = {} for transaction in DataSet: if frozenset(transaction) in DataDict.keys(): DataDict[frozenset(transaction)] += 1 else: DataDict[frozenset(transaction)] = 1 return DataDict # define a tree,and save every node class treeNode: """ define a class, every node will have some attributes: name:the name of node count: the number of node occurance ParentNode : the ParentNode ChildrenNode: the ChildrenNode, the type is dict NodeLink: the similar node in different transaction, The default is None and some function: inc: plus the numOccurance disp: print the tree """ def __init__(self, name, numOccur, ParentNode): self.name = name self.count = numOccur self.ParentNode = ParentNode self.ChildrenNode = {} self.NodeLink = None def inc(self, numOccur): self.count += numOccur def updateHeader(originalNode, targetNode): """ connecting the similar treeNode together :param originalNode: the treeNode :param targetNode: the treeNode that should be connected :return: """ while(originalNode.NodeLink != None): originalNode = originalNode.NodeLink originalNode.NodeLink = targetNode def updateTree(items, intree, headerTable, count): """ Update Tree with every transaction, updating process can be split into three steps: (1) if the items[0] has already been the childrenNode of intree, then update the numOccur of Items[0] (2) else: construct the new treeNode,and update the headerTable (3) loop step(1) and step(2) until there is no item in items :param items: one transaction after filtering by minSup :param intree: the items[0]'s parentNode :param headerTable: headerTable:{item:[count, header of NodeLink],...} :param count: the count of this transaction :return: """ # Step1: if items[0] in intree.ChildrenNode: intree.ChildrenNode[items[0]].inc(count) # Step2: else: intree.ChildrenNode[items[0]] = treeNode(items[0], count, intree) if headerTable[items[0]][1] == None: headerTable[items[0]][1] = intree.ChildrenNode[items[0]] else: updateHeader(headerTable[items[0]][1], intree.ChildrenNode[items[0]]) # Step3: if len(items) > 1: updateTree(items[1:], intree.ChildrenNode[items[0]], headerTable, count) def createTree(DataDict, minSup=300): """ creating FP-Tree can be split into three steps: (1) Traverse the DataSet, count the number of occurrences of each item, create a header-table (2) Remove items in the headerTable that do not meet the minSup (3) Traverse the DataSet again, create the FP-tree :param DataSet: dict{(transaction):count,...} :param minSup: minimum support :return:rootTree, headerTable """ # Step 1: headerTable = {} for transaction in DataDict: for item in transaction: headerTable[item] = headerTable.get(item, 0) + DataDict[transaction] # del item whose value is Nan: key_set = set(headerTable.keys()) for key in key_set: if key is '': del(headerTable[key]) # Step 2: key_set = set(headerTable.keys()) for key in key_set: if headerTable[key] < minSup: del(headerTable[key]) # if the headerTable is None, then return None, None freqItemSet = set(headerTable.keys()) if len(freqItemSet) == 0: return None, None # plus one value for the item to save the NodeLink for key in headerTable: headerTable[key] = [headerTable[key], None] # Instantiate the root node rootTree = treeNode('Null Set', 1, None) # Step 3: for transaction, count in DataDict.items(): localID = {} for item in transaction: if item in freqItemSet: localID[item] = headerTable[item][0] if len(localID) > 0: orderedItems = [v[0] for v in sorted(localID.items(), key=lambda p: p[1], reverse=True)] updateTree(orderedItems, rootTree, headerTable, count) return rootTree, headerTable def ascendTree(leafNode, prefixPath): """ Treat every transaction as a line, connecting from leafnode to rootnode :param leafNode: leafnode :param prefixPath: path ending with leafnode :return: """ if leafNode.ParentNode != None: prefixPath.append(leafNode.name) ascendTree(leafNode.ParentNode, prefixPath) def findPrefixPath(baseitem, treeNode): """ find conditional pattern base(collection of paths ending with baseitem being looked up) for every frequent item :param baseitem: frequent item :param treeNode: the header of NodeLink in headerTable :return: condPats:conditional pattern base """ condPats = {} while treeNode != None: prefixPath = [] ascendTree(treeNode, prefixPath) if len(prefixPath) > 1: condPats[frozenset(prefixPath[1:])] = treeNode.count treeNode = treeNode.NodeLink return condPats def mineTree(inTree, headerTable, minSup, prefix, freqItemList): """ after constructing the FP-Tree and conditional FP-tree, loop for look for frequent ItemSets :param inTree: the dataset created by createTree :param headerTable: the FP-Tree :param minSup: the minimum support :param prefix: used to save current prefix, should be pass set([]) at first :param freqItemList: used to save frequent itemsets, should be pass list[] at first :return: """ items = [v[0] for v in sorted(headerTable.items(), key=lambda p:p[1][0])] for baseitem in items: newFreqSet = prefix.copy() newFreqSet.append(baseitem) freqItemList.append(newFreqSet) condPats = findPrefixPath(baseitem, headerTable[baseitem][1]) myCondTree, myHeadTable = createTree(condPats, minSup) if myHeadTable != None: mineTree(myCondTree, myHeadTable, minSup, newFreqSet, freqItemList) def from_Itemset(freqItems, rootTree, headerTable, minSup): """ Based on the result of frequent Itemset, print out those FP-conditional trees whose height is larger than 1 :param freqItems: the result of finding frequent Itemset :return: the FP-conditional trees , put in one list """ # Step1: find all the items that the FP-conditional trees whose height is larger than 1 FP_items = [] for items in freqItems: if len(items) > 1: FP_items.append(items[0]) # Step2: Remove duplicates FP_items = list(set(FP_items)) # Step3: find the conditional-tree of every item lst_all = [] for baseitem in FP_items: condPats = findPrefixPath(baseitem, headerTable[baseitem][1]) myCondTree, myHeadTable = createTree(condPats, minSup) lst = from_node(myCondTree) lst_all.append(lst) return lst_all def from_node(node): """ from every node whose conditional tree is higher than 1, print the conditional tree into list :param node: :return: """ lst = [] combination = node.name + ' ' + str(node.count) lst.append(combination) if node.ChildrenNode: lst_children = [] Item_set = set(node.ChildrenNode.keys()) for Item in Item_set: node_new = node.ChildrenNode[Item] lst_new = from_node(node_new) lst_children.append(lst_new) lst.append(lst_children) if len(lst) == 1: lst = lst[0] return lst def fpTree(DataDict, minSup=300): """ package all the function into the main function :param DataDict: the input file :param minSup: the minimum support :return: freqItems\FP-conditional trees """ rootTree, headerTable = createTree(DataDict, minSup) freqItems = [] prefix = [] mineTree(rootTree, headerTable, minSup=300, prefix=prefix, freqItemList=freqItems) lst_all = from_Itemset(freqItems, rootTree, headerTable, minSup=300) # print_fp_all = print_fp(rootTree, headerTable, minSup=300) return freqItems, lst_all def data_write_csv(filename, datas): with open(filename, 'w', newline='') as f: writer = csv.writer(f) for data in datas: writer.writerow([data]) print('save file successfully') if __name__ == '__main__': start = time.clock() DataDict = loadDataDict('groceries.csv') freqItems, lst_all = fpTree(DataDict) data_write_csv('submission_2.1.csv', freqItems) data_write_csv('submission_2.2.csv', lst_all) elapsed_1 = time.clock() - start print("Running time is:", elapsed_1) print(freqItems) print(len(freqItems)) print(len(lst_all)) print(lst_all)
3bee7286fcbfd406dea12509209bb2ac292541eb
jhoneal/Python-class
/pythag.py
99
3.546875
4
from math import sqrt def calc(a,b): c = sqrt(a^2 + b^2) print('{:.3f}'.format(c)) calc(4,9)
0fd4177666e9d395da20b8dfbfae9a300e53f873
jhoneal/Python-class
/pin.py
589
4.25
4
"""Basic Loops 1. PIN Number Create an integer named [pin] and set it to a 4-digit number. Welcome the user to your application and ask them to enter their pin. If they get it wrong, print out "INCORRECT PIN. PLEASE TRY AGAIN" Keep asking them to enter their pin until they get it right. Finally, print "PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.""" pin = 9999 num = int(input("Welcome to this application. Please enter your pin: ")) while num != pin: num = int(input("INCORRECT PIN. PLEASE TRY AGAIN: ")) print("PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.")
d64d13bb882c7b211d77803e00f968eb8ea3f81d
jhoneal/Python-class
/add.py
187
3.71875
4
import random def a1(): a = random.randint(0,9) b = random.randint(0,9) print("What is {} + {}?".format(a,b)) answer = int(input("Enter number:")) print(answer==a+b) a1()
3bb04e461f84949712738592c61f4080abb5a733
Coopelia/LeetCode-Solution
/py/384.py
593
3.796875
4
''' 打乱数组 ''' import random from typing import List class Solution: def __init__(self, nums: List[int]): self.original = nums def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """ return self.original def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ tmplist = self.original.copy() res = [] while tmplist: res.append(tmplist.pop(random.randint(0, len(tmplist) - 1))) return res
ad525b6f818470b79566d0cbb092e53602d03f7b
MichaelDeutschCoding/Python_Baby_Projects
/animal_classes.py
1,378
3.875
4
class Pet: def __init__(self, name, weight, species): self.name = name self.weight = weight self.species = species self.alive = True self.offspring = [] print(f'{self.name} successfully initiated.') def __repr__(self): if self.offspring: return f'Meet {self.name}. A {self.species} that weighs {self.weight} kg. {self.name} is alive: {self.alive} and has {len(self.offspring)} children, named {", ".join(self.offspring)}' else: return f'Meet {self.name}. A {self.species} that weighs {self.weight} kg. {self.name} is alive: {self.alive}' def birth(self, baby_name): self.offspring.append(baby_name) print(f'Congratulations to {self.name} on the birth of a new baby {self.species} named {baby_name}!') class Dog(Pet): def __init__(self, name, weight, howls): Pet.__init__(self, name, weight, 'dog') self.howls = howls def __repr__(self): return super().__repr__() + f". Does {self.name} howl? " + str(self.howls) billy = Pet('Billy', 22, 'goat') rover = Pet('Rover', 13, 'dog') rover.birth('Spot') rover.birth('Samantha') chewy = Dog('Chewie', 15, True) chewy.birth('Chewbacca Jr') print(billy) print(rover) print(chewy) print(chewy.offspring) billy.alive = False print(billy)
f9f29d0d9f2a06e069ee1b2972053d436d786f29
MichaelDeutschCoding/Python_Baby_Projects
/connect4.py
632
3.84375
4
ROW_COUNT = 6 COLUMN_COUNT = 7 def create_board(): board = [] for row in..... return board def drop_piece(board, row, col, piece): pass def valid_location(board, col): return board[5][col] == 0 def next_open_row(board, col): for r in range(ROW_COUNT): if board[r][col] == 0: return r def printer(board): pass #for row in board[::-1]: print(row) #print column numbers board = create_board() game_over = False turn = 0 while not game_over: if turn == 0: col = int(input("Player One, choose a column: ") if valid_location(board, col):
96cc50582d0ec13cdec24e10c67d210e828cfb9b
MichaelDeutschCoding/Python_Baby_Projects
/Battleship.py
3,607
4.1875
4
from random import randrange, choice from string import digits # TO DOs # multiple ships # various sized ships # define class (ship) # two players # merge board coordinates into a tuple instead of separate components of row/col def battleship(): print() print("\t \t Let's Play Battleship!") print("You may press 'Q' at any time to quit.") sz = 5 global again again = "" board = [] for x in range(sz): board.append(["O"] * sz) def print_board(board): num = 65 print(" " + " ".join(digits[1:sz + 1])) for row in board: print(chr(num), " ".join(row)) num +=1 print_board(board) ship_row = randrange(sz) ship_col = randrange(sz) #hide a ship of length 3 directions = [] if ship_row >= 2: directions.append("up") if ship_row <= (sz - 3): directions.append("down") if ship_col >= 2: directions.append("left") if ship_col <= (sz - 3): directions.append("right") direction = choice(directions) print(directions) #### print(direction) #### if direction == "up": ship2_row = ship_row - 1 ship3_row = ship_row - 2 ship2_col = ship_col ship3_col = ship_col if direction == "down": ship2_row = ship_row + 1 ship3_row = ship_row + 2 ship2_col = ship_col ship3_col = ship_col else: pass if direction == "left": ship2_col = ship_col -1 ship3_col = ship_col -2 ship2_row = ship_row ship3_row = ship_row else: pass if direction == "right": ship2_col = ship_col + 1 ship3_col = ship_col + 2 ship2_row = ship_row ship3_row = ship_row else: pass print("ship row:", ship_row) print("ship col:", ship_col) print("ship2:", ship2_row, ship2_col) print(ship3_row, ship3_col) t = 0 #turn counter while True: print() print("\tTurn", t+1) guess = (input("Guess a Coordinate (letter first): ")).upper() if guess == "Q": print("Sorry to see you go.") return elif not len(guess) == 2 or not guess[0].isalpha() or not guess[1].isdigit(): #should it be If not len(guess) == 2 print("Invalid Entry.") continue guess_row = ord(guess[0]) - 65 guess_col = int(guess[1]) - 1 if guess_row < 0 or guess_row > sz - 1 or guess_col < 0 or guess_col > sz -1: print("Oops, that's not even in the ocean!") continue elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "#": print("You've already guessed that spot.") continue if ((guess_row == ship_row and guess_col == ship_col) or (guess_row == ship2_row and guess_col == ship2_col) or (guess_row == ship3_row and guess_col == ship3_col)): board[guess_row][guess_col] = "#" print("Hit!") print_board(board) if (board[ship_row][ship_col] == "#" and board[ship2_row][ship2_col] == "#" and board[ship3_row][ship3_col] == "#"): print("You sunk my battleship!!") print("Congratulations, you won!".center(75, '*')) break else: t +=1 continue else: print("You missed my battleship.") board[guess_row][guess_col] = "X" t +=1 print_board(board) again = input("Do you want to play again? type 'Y' for yes: ").upper() def play(): battleship() while again == "Y": print() battleship() else: print("Thanks for playing. Goodbye.") play() blah = input("MD")
56562d9c21637289ec49096572dd5297f9b0261c
rgb-24bit/scripts
/py/prime.py
654
3.921875
4
# -*- coding: utf-8 -*- """ Obtaining a prime number within the numerical range is designated ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2019 by rgb-24bit. :license: MIT, see LICENSE for more details. """ import sys def eratosthenes(n): is_prime = [True] * (n + 1) is_prime[1] = False for i in range(2, int(n ** 0.5) + 1): if is_prime[i]: for j in range(i * i, n + 1, i): is_prime[j] = False return [x for x in range(2, n + 1) if is_prime[x]] if __name__ == '__main__': prog, *args = sys.argv for arg in args: print(eratosthenes(int(arg)))
51d409c780d13e35d3a4626a10273ef0d32e03a6
Raivias/assimilation
/old/vector.py
1,173
4.25
4
class Vector: """ Class to use of pose, speed, and accelertation. Generally anything that has three directional components """ def __init__(self, a, b, c): """ The three parts of the set :param a: x, i, alpha :param b: y, j, beta :param c: z, k, gamma """ self.a = a self.b = b self.c = c def __add__(self, other): a = self.a + other.a b = self.b + other.b c = self.c + other.c return Vector(a, b, c) def __sub__(self, other): a = self.a - other.a b = self.b - other.b c = self.c - other.c return Vector(a, b, c) def __mul__(self, other): if other is Vector: return self.cross_mul(other) def cross_mul(self, other): """ Cross multiply :param other: Another Vector :return: Cross multiple of two matices """ a = (self.b * other.c) - (self.c * other.b) b = (self.c * other.a) - (self.a * other.c) c = (self.a * other.b) - (self.b * other.a) return Vector(a, b, c) def scalar_mul(self, other): pass
f3b74c75bfa4ad15798649420d2ed7aec23bd441
shangsuru/machine-learning
/sml/hw4/1a.py
9,046
3.796875
4
import numpy as np from matplotlib import pyplot as plt """ # Backpropagation dL = (-error)@np.reshape(np.insert(a[-1], 0, 1), (1, -1)) self.weights[-1] += learning_rate * dL for i in range(1, len(self.weights) - 1): prod = None for k in range(i, len(self.weights) - 1): val = ( self.weights[k+1] @ np.insert(self.activation_func_df[k](z[k]), 0, 1) ) prod = val if prod is None else prod @ val dL = - ( (np.reshape(prod, (-1, 1)) @ error) @ np.reshape(np.insert(a[i], 0, 1), (1, -1)) ) self.weights[i] += learning_rate * dL """ class NeuralNetworkold: """Represents a neural network. Args: layers: An array of numbers specifying the neurons per layer. activation_func: An array of activation functions corresponding to each layer of the neural network except the first. actionvation_func_df: An array of the derivatives of the respective activation functions. Attributes: activation_func: The activation functions for each layer of the network. weights: A numpy array of weights. """ def __init__(self, layers, activation_func, activation_func_df, penalty_func, penalty_func_df, feature_func): self.dim = layers self.activation_func = activation_func self.activation_func_df = activation_func_df self.penalty_func = penalty_func self.penalty_func_df = penalty_func_df self.feature_func = feature_func self.weights = [np.random.random((layers[i + 1], layers[i] + 1)) for i in range(len(layers) - 1)] def predict(self, x): """Predicts the value of a data point. Args: X: The input vector to predict an output value for. Returns: The predicted value(s). """ a = x z = None for i, weight in enumerate(self.weights[:-1]): z = weight@np.insert(a, 0, 1) a = self.activation_func[i](z) y = self.weights[-1]@np.insert(a, 0, 1) return np.argsort(y)[-1] def train(self, x, y, learning_rate=.1): """Trains the neural network on a single data point. Args: X: The input vector. Y: The output value corresponding to the input vectors. """ # Forwardpropagation: build up prediction matrix z = [] a = [x] for i, weight in enumerate(self.weights[:-1]): z.append(weight@self.feature_func(a[-1])) a.append(self.activation_func[i](z[-1])) pred_y = (self.weights[-1]@self.feature_func(a[-1])).reshape(-1, 1) K = len(self.weights) d = [None] * K d[-1] = (pred_y - y).reshape(-1, 1)@a[-1].reshape(1, -1) for i in range(1, K): k = K - i - 1 d[k] = d[k+1]@(self.weights[k + 1]@np.append(self.activation_func_df[k](z[k]),1)) for i in range(K): self.weights[i] -= learning_rate * (d[i]@x[i]) class NeuralNetwork: """Represents a neural network. Args: layers: An array of numbers specifying the neurons per layer. activation_func: An array of activation functions corresponding to each layer of the neural network except the first. actionvation_func_df: An array of the derivatives of the respective activation functions. Attributes: activation_func: The activation functions for each layer of the network. weights: A numpy array of weights. """ def __init__(self, layers, activation_func, activation_func_df, penalty_func, penalty_func_df, feature_func): self.dim = layers self.activation_func = activation_func self.activation_func_df = activation_func_df self.penalty_func = penalty_func self.penalty_func_df = penalty_func_df self.feature_func = feature_func self.weights = [np.random.random((layers[i + 1], layers[i])) * 1e-4 for i in range(len(layers) - 1)] self.bias = [np.random.random((layers[i + 1],)) * 1e-4 for i in range(len(layers) - 1)] def predict(self, x): """Predicts the value of a data point. Args: X: The input vector to predict an output value for. Returns: The predicted value(s). """ a = x z = None for i, weight in enumerate(self.weights): z = weight@a + self.bias[i] a = self.activation_func[i](z) y = a return np.argsort(y)[-1] def train(self, x, y, learning_rate=.01): """Trains the neural network on a single data point. Args: X: The input vector. Y: The output value corresponding to the input vectors. """ # forward propagate def fp(): h = [x] a = [] for i in range(len(self.weights)): a.append(self.bias[i] + self.weights[i]@h[i]) h.append(self.activation_func[i](a[i])) return h, a h, a = fp() pred_y = h[-1] g = self.penalty_func_df(pred_y, y).reshape(-1, 1) K = len(self.weights) delta_b = [None] * K delta_W = [None] * K for i in range(K): k = K - i - 1 g = g * self.activation_func_df[k](a[k]).reshape(-1, 1) delta_b[k] = g delta_W[k] = g@h[k].reshape(1, -1) g = self.weights[k].T@g for i in range(K): self.weights[i] = self.weights[i] - learning_rate * delta_W[i] self.bias[i] = self.bias[i] - learning_rate * delta_b[i].reshape(-1) def gradientAtPoint(self, x, y): def fp(): h = [x] a = [] for i in range(len(self.weights)): a.append(self.bias[i] + self.weights[i]@h[i]) h.append(self.activation_func[i](a[i])) return h, a h, a = fp() pred_y = h[-1] g = self.penalty_func_df(y, pred_y).reshape(-1, 1) K = len(self.weights) delta_b = [None] * K delta_W = [None] * K for i in range(K): k = K - i - 1 g = g * self.activation_func_df[k](a[k]).reshape(-1, 1) delta_b[k] = g delta_W[k] = g@h[k].reshape(1, -1) g = self.weights[k].T@g return delta_W, delta_b def onehot(self, y): ret = [0] * self.dim[-1] ret[int(y)] = 1 return np.array(ret).reshape(1,-1) def gradientDescent(self, X, Y, epoch=10, learning_rate=1): for j in range(epoch): print(j) dw_total = None db_total = None for i in range(len(X)): dw, db = self.gradientAtPoint(X[i], self.onehot(Y[i])) dw_total = dw if dw_total is None else dw_total + dw db_total = db if db_total is None else db_total + db for i in range(len(self.weights)): self.weights[i] = self.weights[i] - learning_rate * dw_total[i] / len(X) self.bias[i] = self.bias[i] - learning_rate * db_total[i].reshape(-1) / len(X) def onehot(y): ret = [0] * 10 ret[int(y)] = 1 return np.array(ret).reshape(1,-1) def error(nn, X, Y): error = 0 for i, x in enumerate(X): y = Y[i] y_ = nn.predict(x) error += 1 if y != y_ else 0 return error / len(X) def main(): # Prepare data X_train = np.loadtxt('./dataSets/mnist_small_train_in.txt', delimiter=",") Y_train = np.loadtxt('./dataSets/mnist_small_train_out.txt', delimiter=",") X_test = np.loadtxt('./dataSets/mnist_small_test_in.txt', delimiter=",") Y_test = np.loadtxt('./dataSets/mnist_small_test_out.txt', delimiter=",") D = X_train[0].shape[0] # Create and train neural network def act_func(x): return 1 / (1 + np.exp(-x)) def act_func_df(x): return act_func(x) * (1- act_func(x)) def pen_func(x, y): return .5*(x - y)**2 def pen_func_df(x, y): return (x - y) ff = lambda x: np.append(x, 1) layers = [D, 200, 10] nn = NeuralNetwork( layers, [act_func] * (len(layers) - 1), [act_func_df] * (len(layers) - 1), pen_func, pen_func_df, ff ) print("Pre-Training:") print("Training Error: {}".format(error(nn, X_train, Y_train))) print("Test Error: {}".format(error(nn, X_test, Y_test))) nn.gradientDescent(X_train, Y_train) print("Post-Training:") print("Training Error: {}".format(error(nn, X_train, Y_train))) print("Test Error: {}".format(error(nn, X_test, Y_test))) if __name__ == "__main__": main()
277907f7ebb91a70565ba791fe9131058135a351
dafydds/adventofcode2018
/day1.py
662
3.5
4
with open('data/day1_input.txt', 'r') as fp: lines = fp.readlines() vals = [int(x) for x in lines] print(sum(vals)) def get_repeated_value(vals): counts = {} current_value = 0 counts[current_value] = 1 break_while = False while True: for val in vals: current_value += val previous_counts = counts.get(current_value, 0) if (previous_counts > 0): return current_value break_while = True break counts[current_value] = 1 if break_while: break answer2 = get_repeated_value(vals) print(answer2)
ae13cecbf688c569880bb932bb4a5b4e7ae09e14
andyshen55/MITx6.0001
/ps1/ps1c.py
1,782
4.0625
4
def guessRate(begin, end): #finds midpoint of the given search range and returns it as a decimal guess = ((begin + end) / 2) / 10000.0 return guess def findSaveRate(starting_salary): #program constants portion_down_payment = 0.25 total_cost = 1000000 down = total_cost * portion_down_payment r = 0.04 semi_annual_raise = .07 months = 36 #search counter, search boundaries searches = 0 begin = 0 end = 10000 #continue until there are no more valid save rate guesses. while (end - begin) > 1: searches += 1 currentGuess = guessRate(begin, end) #reinitialize variables for new iteration current_savings = 0.0 month = 1 annual_salary = starting_salary while month <= months: current_savings *= 1 + (r / 12) current_savings += (annual_salary / 12) * currentGuess #increases salary semi-annually after every 6th month if (not (month % 6)): annual_salary *= 1 + semi_annual_raise month += 1 #checks if savings are within 100 dollars of required down payment costDiff = current_savings - down #updates upper/lower bounds if costDiff > 100: end = currentGuess * 10000 elif costDiff < 0: begin = currentGuess * 10000 else: print("Best savings rate:", str(currentGuess)) print("Steps in bisection search:", str(searches)) return #if impossible to save for down payment within 36 months print("It is not possible to pay the down payment in three years.") if __name__ == "__main__": findSaveRate(float(input("Enter the starting salary: ")))
904e4fdfd5cbbf3b0071e26be2d49f42ab9796b0
vgomesdcc/UJ_TeoCompPYTHON
/p3.py
253
3.875
4
print("Insira as notas das provas e do trabalho") prova1 = int(input()) prova2 = int(input()) trabalho = int(input()) prova1 = prova1*3 prova2 = prova2*3 if (prova1+prova2+trabalho)/7 >= 7: print("Aprovado") else: print("Reprovado")
f1feb135f8c763fcf9c8bf51d0456d143b08c984
chouqin/test-code
/pytest/test_func.py
381
3.734375
4
import datetime def add_date(day): day += datetime.timedelta(days=1) return day def append_list(li): li.append(1) return li def two_return(): return 1, 2 if __name__ == "__main__": d1 = datetime.date(2012, 3, 14) d2 = add_date(d1) print d1, d2 l1 = [2, 3] l2 = append_list(l1) print l1, l2 a, b = two_return() print a, b
b3626a37d0b7cd47b4dcdebb19334ee43c3381d8
IvanPLebedev/TasksForBeginer
/Task22.py
637
3.984375
4
''' Задача 22 Напишите программу, которая принимает текст и выводит два слова: наиболее часто встречающееся и самое длинное. ''' import collections text = 'Напишите программу и которая принимает текст и выводит два слова наиболее часто встречающееся и самое длинное' words = text.split() counter = collections.Counter(words) common, occurrences = counter.most_common()[0] longest = max(words, key=len) print(occurrences) print(common, longest)