blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
b35e2f33b1f9b2f3af1e5f10a783b9245a6127f7
janaobsteter/PyCharmProjects
/Pratice/max.py
472
3.59375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT #use function product(*ListOfLists) from itertools import product k, m = map(int, input().split(" ")) lists = [] for l in range(0, k): lists.append([x for x in map(int, input().split(" "))]) if sum([m ^ 2 for m in [max(l) for l in lists]]) < m: print(sum([mx ** 2 for mx in [max(l) for l in lists]])) else: print(max([(sum(map(lambda x: pow(x, 2), l)) % m, l) for l in product(*lists)]))
4fe49c1db08ccc139af1ca077a2db6c630b1a462
chenmingjian/did_chenmingjian_coding_today
/.leetcode/106.从中序与后序遍历序列构造二叉树.py
1,019
3.640625
4
# # @lc app=leetcode.cn id=106 lang=python3 # # [106] 从中序与后序遍历序列构造二叉树 # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def ok(p, i): # print(p, i) if len(p) == 0: return node = TreeNode(p[-1]) index = i.index(p[-1]) # print(' ', p[-(len(i) - index):-1], i[index+1:]) node.right = ok(p[-(len(i) - index):-1], i[index+1:]) # assert(len(p[-(1+index):-1]) == len(i[index+1:])) # print(' ', p[:len(i[:index])], i[:index]) node.left = ok(p[:len(i[:index])], i[:index]) # assert( len(p[:-(1+index)]) == len(i[:index])) return node return ok(postorder, inorder) # @lc code=end
4319c0b12ed945e3586c16032d2606c38377a837
DOYEON96/TIL
/0719/algoithm/Code11-03.py
451
3.703125
4
# 함수 def selectionSort(ary): n = len(ary) for i in range(n-1): minIdx=i for j in range(i+1, len(ary)): if ary[minIdx] > ary[j]: minIdx = j ary[i], ary[minIdx] = ary[minIdx], ary[i] return ary # 전역 import random dataAry = [random.randint(50, 200) for _ in range(10)] # 메인 print('정렬 전 : ', dataAry) dataAry = selectionSort(dataAry) print('정렬 후 : ', dataAry)
1735b1909a44dfb898755a9dd74023c25993f451
Universatile/AdventofCode
/day6.py
1,020
3.90625
4
# Day 6 of Advent of Code # Author: Jason Rennie def redist(banks): """Resdistributes the blocks from the largest memory bank to other banks, sequentially with one per bank until completely redistributed. """ k = max(banks) i = banks.index(k) end = len(banks) banks[i] = 0 while k > 0: i += 1 if i == end: i = 0 banks[i] += 1 k -= 1 return banks def count_cycles(banks): """Records permutations and checks for the first repeat. Prints number of cycles total, and number of cycles between repeats. """ perms = [] while banks not in perms: perms.append(banks) banks = redist(list(banks)) print("The numbers of cycles required to redistribute is:", len(perms)) print("The numbers of cycles between repeats is:", len(perms) - perms.index(banks)) file = open("day6.txt", "r") banks = [int(n) for n in file.read().split()] # Initial configuration file.close() count_cycles(banks)
f337e0063a053b9be1238f26a9e9b71110fedd3c
dlhauer/Sprint-Challenge--Intro-Python
/src/oop/oop2.py
450
3.5
4
class GroundVehicle(): def __init__(self, num_wheels=4): self.num_wheels = num_wheels def drive(self): return "vroooom" class Motorcycle(GroundVehicle): def __init__(self): super().__init__(2) def drive(self): return "BRAAAP!!" vehicles = [ GroundVehicle(), GroundVehicle(), Motorcycle(), GroundVehicle(), Motorcycle(), ] for vehicle in vehicles: print(vehicle.drive())
afc891b2b62e67286db2ae12893a3b5c9ac16b85
harshitkakkar/PythonBasics
/Basics/pandas2_python.py
1,117
3.703125
4
import pandas as pd import sqlite3 df = pd.read_csv("nwedemo.csv") df["esal"]=pd.Series([1000,1200,1300,900,200],dtype="float") print(df) print("------------------") print(df.sum()) print("------------------") print(df["Pid"].max()) print("------------------") print(df["esal"].min()) print("------------------") print(df.sort_index(ascending=False)) print("------------------") df.sort_values(by="Age", inplace=True) print(df) print("------------------") print(df.isnull()) print("------------------") print(df["Age"].notnull()) print("------------------") print(df.dropna(axis=1,how="all")) print("------------------") print(df.dropna(axis=0,how="all")) print("------------------") print(df.drop_duplicates()) print("------------------") print(df.drop_duplicates("Pid")) # how= any drop full row(since axis =0) if any value is null #and all = if whole row is null then only drop it ############################################### print("------------------") print(df.replace({"Genny":"Surabhi", "Kanu":"Kanika", 21:25})) print("------------------") print(df.fillna(0.0)) print("------------------")
669dfe62d9f641072d3157e23e48208c7d41a993
daniel-reich/ubiquitous-fiesta
/GaJkMnuHLuPmXZK7h_13.py
324
3.640625
4
def letters(word1, word2): s, u1, u2 = '','','' for i in word1: if i in word2: if i not in s: s += i else: if i not in u1: u1 += i for i in word2: if i not in word1: if i not in u2: u2 += i return [''.join(sorted(s)), ''.join(sorted(u1)), ''.join(sorted(u2))]
d0a49722a651b6741471772eb5161fbd34a7e470
BlackRussians/Tic-Tac-Toe
/Stage #5/tictactoe.py
2,389
3.5
4
def make_field(cells): for i in range(len(cells)): if cells[i] == "_": cells[i] = " " print('---------') for i in range(0, 7, 3): print("| {} {} {} |".format(cells[i], cells[i+1], cells[i+2])) print('---------') def chk_field(cells): global active x_win = 0 o_win = 0 win_patterns = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)] for a, b, c in win_patterns: if (cells[a], cells[b], cells[c]) == ('X', 'X', 'X'): x_win += 1 if (cells[a], cells[b], cells[c]) == ('O', 'O', 'O'): o_win += 1 if x_win > 0 and o_win > 0 or abs(cells.count('X')-cells.count('O')) == 2: print('Impossible') active = 0 elif x_win == 1: print('X wins') active = 0 elif o_win == 1: print('O wins') active = 0 elif cells.count('X') >= 5 and cells.count('X') >= 5: print('Draw') active = 0 def main(): turns = 0 cells = ['_', '_', '_', '_', '_', '_', '_', '_', '_'] make_field(cells) move_patterns = [(1, 3), (2, 3), (3, 3), (1, 2), (2, 2), (3, 2), (1, 1), (2, 1), (3, 1)] while active: try: coordinates = tuple(map(int, input("Enter the coordinates: > ").split())) if coordinates[0] > 3 or coordinates[1] > 3 or coordinates[0] <= 0 or coordinates[1] <= 0: print('Coordinates should be from 1 to 3!') for cell in move_patterns: if cell == coordinates: if cells[move_patterns.index(cell)] != ' ': print('This cell is occupied! Choose another one!') else: if turns == 0: turns += 1 cells[move_patterns.index(cell)] = 'X' make_field(cells) elif turns == 1: turns -= 1 cells[move_patterns.index(cell)] = 'O' make_field(cells) chk_field(cells) except ValueError: print('You should enter numbers!') continue except IndexError: print('You should enter numbers!') continue if __name__ == '__main__': active = 1 main()
93fc2a939cec4ffbb5149514eb94cda5c51c7be3
f1amingo/leetcode-python
/剑指offer/剑指 Offer 58 - I. 翻转单词顺序.py
1,012
3.8125
4
# 翻转单词,而不是字符,空格分隔 # 1.移除前后的多余空格 # 2.单词之间也可能有多空格 class Solution: def reverseWords(self, s: str) -> str: if not s: return '' start, end = 0, len(s) - 1 ans = [] while start <= end: # 倒序找到第一个非空字符 rt = end while start <= rt and s[rt] == ' ': rt -= 1 # 到头了 if rt < start: break # 继续从rt开始找到第一个空格 lt = rt - 1 while start <= lt and s[lt] != ' ': lt -= 1 ans.append(s[lt + 1:rt + 1]) end = lt - 1 # lt是空格 return ' '.join(ans) assert Solution().reverseWords("the sky is blue") == "blue is sky the" assert Solution().reverseWords(" hello world! ") == "world! hello" assert Solution().reverseWords("a good example") == "example good a"
3f8b55d7b9970d207a89fba19192a472d6e527fc
AlexandraFil/Geekbrains_2.0
/Python_start/lesson_2/1.py
616
3.859375
4
# 1. Создать список и заполнить его элементами различных типов данных. # Реализовать скрипт проверки типа данных каждого элемента. # Использовать функцию type() для проверки типа. # Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. my_list = [1, 1.1, 34.56, False, (1, 2, 3, 4), True, ['one', "two"], 'Str', {1, 1, 3, 5}, {1 : 1, 2 : 2}] for i in my_list: print(type(i))
05a8e6094da25444a389a35d2fd62afd30306a8a
t3hpr1m3/More-Python-Testing
/Login.py
547
3.8125
4
import pickle dict_1 = { } print(dict_1) filename = 'Email_dict.txt' file = open(filename, 'rb') x = pickle.load(file) dict_1.update(x) print(dict_1) def login(): a = input('Please enter your Email: ') if a in dict_1.keys(): b = input('Please enter your password!: ') if dict_1[a] == b: return 'You may login!' elif dict_1[a] != b: print('Invalid password!') return login() elif a not in dict_1.keys(): print('Invalid Email!') return login() print(login())
55527d79419603521fa1a7c6f861f4304c5ccc02
DaHuO/Supergraph
/codes/CodeJamCrawler/16_0_2/Nol/codeJam2.py
1,244
3.765625
4
#!/usr/bin/env python3 #flip the N first pancakes of the S piles # aka "the maneuver" def flipPiles(S,N): toflip=S[:N] flipped=toflip.translate(str.maketrans("+-","-+")) flipped=flipped[::-1] return flipped+S[N:] def main(): inFile=open("dataset.txt",'r') outFile=open("output.txt",'w') print("Nombre de cas : "+str(int(inFile.readline()))) case=0 for line in inFile: case=case+1 i=0#number of time we execute the maneuver P=line while '-' in P:#as long as there is a pankake that is not is the right position we work i=i+1 # we assume that the optimal way is to switch the first chain of pancake #on the same side until that chain match the whole piles. #At that point, eather there are all on happy side and we are done or we have to flipped all of them c=P[0].translate(str.maketrans("+-","-+"))#seeking the first character which differ from the first one N=P.find(c) if N==-1: N=len(P) P=flipPiles(P,N) outFile.write("Case #"+str(case)+": "+str(i)+'\n'); inFile.close() outFile.close() return main()
5e4d48ed166b8e2923013b235b4b4987efc45fc3
arichen/algorithm-notes
/tic_tac_toe.py
1,432
3.765625
4
from collections import defaultdict class TicTacToe: def __init__(self, n = 3, current = 0): # current symbols: 0 or 1 self.n = n self.board = [[None] * n for _ in range(n)] self.current = current self.count = 0 self.is_finished = False self.out = {0: "O", 1: "X", None: " "} # marks moves self.rows = [defaultdict(int), defaultdict(int)] self.cols = [defaultdict(int), defaultdict(int)] self.diag1 = [0, 0] self.diag2 = [0, 0] def move(self, r, c): if self.is_finished: raise Exception("game finished") if not self.board[r][c] is None: raise Exception("already occupied") self.count += 1 self.board[r][c] = self.current self.rows[self.current][r] += 1 self.cols[self.current][c] += 1 if r == c: self.diag1[self.current] += 1 if r + c == self.n - 1: self.diag2[self.current] += 1 if self.check(r, c): self.is_finished = True self.print() return self.current = (self.current + 1) % 2 def check(self, r, c): # check if current symbol wins # or no more available spot if self.count == self.n * self.n: return True if (self.rows[self.current][r] == self.n or self.cols[self.current][c] == self.n or self.diag1[self.current] == self.n or self.diag2[self.current] == self.n): return True return False def print(self): for r in self.board: print([self.out[x] for x in r]) TicTacToe()
47483c87e95bc0091524b82df46b2b178e9e4cf9
r-luis/Python-CursoemVideo
/Download/PythonExercicios/ex077.py
501
4.25
4
'''Desafio 77 Crie um programa que tenha uma tupla com várias palavras (Não usar acentos). Depois disso, você deve mostrar para cada palavra, quais são as suas vogais.''' palavras = ('Luffy', 'Zoro', 'Nami', 'Sanji', 'Chopper', 'Robin', 'Franky', 'Brook', 'Jimbe') vogais = 'aeiou' for p in palavras: print(f'\nA palavra {p.upper()} temos como vogal: ', end='') for letra in p: if letra in p: if letra.lower() in vogais: print(letra.upper(), end=' ')
fb8947d9297b34e21a756c46b8a701602aea55d0
PythonCHB/Sp2018-Accelerated
/students/ahwall/Lesson 02 Homework/FibLuc_Seq Exercise_HW2/FibLucSeq.py
528
3.578125
4
def fibinacci(x): a = 0 b = 1 c = 0 if (x == 0): print(x) else: for i in range(x): a = b b = c c = b + a print(c) def lucas(x): a = 2 b = 1 if x == 0: print(2) elif x == 1: print(1) else: for i in range(2, x + 1): c = b + a a = b b = c print(c) def sum_series(x, a = 0, b = 1): if (a == 2) and (b == 1): lucas(x) else: fibinacci(x)
d4c7f190ff2183168e1a8e3b08fcc9a3720f9cd3
life-sync/Python
/subhash1612/anagram.py
839
4.34375
4
''' This program checks if two strings are anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase ''' def check(str1,str2): #Function to check if they are anagrams if(len(str1) != len(str2)): #Comparing the lengths of the two strings print("The strings are not anagrams") else: str1 = str1.lower() str2 = str2.lower() str1 = sorted(str1) #Sort each string alphabetically str2 = sorted(str2) if(str1 == str2): #If they are equal then they are anagrams print("The strings are anagrams") else: print("The strings are not anagrams") def main(): #Driver function str1 = input("Enter the first string: ") str2 = input("Enter the second string: ") check(str1,str2) main()
3c75d4c85b40335b0c91fd4c8f420931b2fe0562
jakubszczyglewski/Tic-Tac-Toe
/tictactoe.py
5,788
3.8125
4
import random class Player: def __init__(self, sign): self.sign = sign def move(self, moves, sign): print('Your move, please choose a field.') player_move = input() while player_move not in moves or moves[player_move] != '_': print('Something is wrong, you may want to check your move') print('Your move, please choose a field.') player_move = input() moves.pop(player_move) moves[player_move] = str(sign) class Computer(Player): def __init__(self, sign): super().__init__(sign) def move(self, moves, sign_own, sign_op): abc = '' for key, value in moves.items(): efg = value if abc == efg and value == '_': player_move = key moves.pop(player_move) moves[player_move] = str(sign_own) break else: choice = random.choice(list(moves.keys())) while moves[choice] == 'x' or moves[choice] == 'o': choice = random.choice(list(moves.keys())) moves.pop(choice) moves[choice] = str(sign_own) break class Board: def __init__(self): self.moves = { 'top_left': '_', 'top_mid': '_', 'top_right': '_', 'mid_left': '_', 'mid_mid': '_', 'mid_right': '_', 'bot_left': '_', 'bot_mid': '_', 'bot_right': '_'} def action(self, player_move, sign): self.moves.pop(player_move) self.moves[player_move] = str(sign) def winning_board(self, player, sign): return ((self.moves['top_left'] == self.moves['top_mid'] == self.moves['top_right'] == str(sign)) or (self.moves['mid_left'] == self.moves['mid_mid'] == self.moves['mid_right'] == str(sign)) or (self.moves['bot_left'] == self.moves['bot_mid'] == self.moves['bot_right'] == str(sign)) or (self.moves['top_left'] == self.moves['mid_mid'] == self.moves['bot_right'] == str(sign)) or (self.moves['bot_left'] == self.moves['mid_mid'] == self.moves['top_right'] == str(sign)) or (self.moves['top_left'] == self.moves['mid_left'] == self.moves['bot_left'] == str(sign)) or (self.moves['top_mid'] == self.moves['mid_mid'] == self.moves['bot_mid'] == str(sign)) or (self.moves['top_right'] == self.moves['mid_right'] == self.moves['bot_right'] == str(sign))) def advice(self): while True: print('Do you want me to remind you the name of each field?') answer = input().capitalize() if answer == 'Yes': print( 'In order to choose where you want put an X please type in the name of field as per below legend:') print('top_left|top_mid|top_right') print('mid_left|mid_mid|mid_right') print('bot_left|bot_mid|bot_right') break elif answer == 'No': break else: print('I do not understand, please repeat...') def print_board(self): print(self.moves['top_left'], '|', self.moves['top_mid'], '|', self.moves['top_right']) print(self.moves['mid_left'], '|', self.moves['mid_mid'], '|', self.moves['mid_right']) print(self.moves['bot_left'], '|', self.moves['bot_mid'], '|', self.moves['bot_right']) def starting_board(self): print('In order to choose where you want put your marker please type in the name of field as per below legend:') print('top_left|top_mid|top_right') print('mid_left|mid_mid|mid_right') print('bot_left|bot_mid|bot_right') class Game(): def __init__(self): pass def round_log(self, x, moves): print(f'Round {x}!') f = open(f"board_round_{x}.txt", "w") f.write(str(moves)) f.close() def choose_gametype(self): global playerA, playerB if random.randrange(0, 2) == 0: playerA_sign = 'x' playerB_sign = 'o' else: playerA_sign = 'o' playerB_sign = 'x' while True: print('Do you want to play?') answer = input().capitalize() if answer == 'Yes': print('With a friend?') answer2 = answer = input().capitalize() if answer2 == 'Yes': playerA = Player(playerA_sign) playerB = Player(playerB_sign) break elif answer == 'No': playerA = Player(playerA_sign) playerB = Computer(playerB_sign) break else: print('I do not understand, please repeat...') elif answer == 'No': playerA = Computer(playerA_sign) playerB = Computer(playerB_sign) break else: print('I do not understand, please repeat...') def run(self): self.choose_gametype() b = Board() b.starting_board() x = 0 while x < 10: if b.winning_board(playerB, playerB.sign): print('Player B wins!') break elif '_' not in b.moves.values(): print('TIE!') break if isinstance(playerA, Computer) and isinstance(playerB, Computer): self.round_log(x, b.moves) b.print_board() playerA.move(b.moves, playerA.sign, playerB.sign) print('Player A move!') b.print_board() if b.winning_board(playerA, playerA.sign): print('Player A wins!') break elif '_' not in b.moves.values(): print('TIE!') break playerB.move(b.moves, playerB.sign, playerA.sign) print('Player B move!') elif isinstance(playerA, Player) and isinstance(playerB, Computer): self.round_log(x, b.moves) b.print_board() b.advice() playerA.move(b.moves, playerA.sign) print('Player A move!') b.print_board() if b.winning_board(playerA, playerA.sign): print('Player A wins!') break elif '_' not in b.moves.values(): print('TIE!') break playerB.move(b.moves, playerB.sign, playerB.sign) print('Player B move!') else: self.round_log(x, b.moves) b.print_board() b.advice() playerA.move(b.moves, playerA.sign) print('Player A move!') b.print_board() if b.winning_board(playerA, playerA.sign): print('Player A wins!') break elif '_' not in b.moves.values(): print('TIE!') break b.advice() playerB.move(b.moves, playerB.sign) print('Player B move!') x += 1 continue game = Game() game.run()
30576bf602b971f024e69afe8607f86945d61127
emanonGarcia/mystery_word
/mystery_word.py
3,818
3.96875
4
import random import string MAX_GUESSES = 8 def lets_play(): answer = input("Let's play: [Y]es or [N]o ") if answer.lower() == 'y': print_game_title() return True elif answer.lower() == 'n': print("Maybe next time...") exit() else: lets_play() return True def get_mystery_word(lower, upper): with open("/usr/share/dict/words", 'r') as f: word_bank = [word.strip() for word in f if len(word.strip()) >= lower and len(word.strip()) <= upper] rand_word = random.choice(word_bank) print('''\nWith {} words to play, I'll pick a one at random. Your word is {} letters long'''.format(len(word_bank), len(rand_word))) return(rand_word.upper()) def easy_mode(): word = get_mystery_word(4, 6) game_core(word) def normal_mode(): word = get_mystery_word(6, 8) game_core(word) def hard_mode(): word = get_mystery_word(8, 45) game_core(word) def mystery_word_game(): if lets_play(): user_input = input("Pick a mode. [E]asy, [N]ormal, [H]ard: ") user_input = user_input.lower() if user_input == 'e': easy_mode() elif user_input == 'n': normal_mode() elif user_input == 'h': hard_mode() else: print("Doesn't match a difficulty. Bye!") exit() def print_game_title(): print(''' ################################################### # "Mystery Word" # ################################################### ''') return def is_correct(correct_guesses, mystery_word): m_list = [letter for letter in set(mystery_word)] correct_guesses.sort() m_list.sort() return correct_guesses == m_list def victory(guess_count, mystery_word): print("\n" + "*" * 20) print("YOU GOT IT!") print("The mystery word was {}".format(mystery_word)) print("It only took you {} guess(es)".format(guess_count)) print("Game Over") print("*" * 20 + '\n') mystery_word_game() def display_guesses(correct_guesses, wrong_guesses): print("\nWrong guesses: {}".format(wrong_guesses)) def print_guess_count(num_of_guesses): print("\nAttempt: {0}/8".format(num_of_guesses)) def get_user_guess(): next_try = input("\nGuess a letter: ") return next_try.upper() def game_core(mystery_word='HELP'): guess_count = 1 correct_guesses = [] wrong_guesses = [] len_of_mystery = len(mystery_word) mystery_list = ['_ '] * ((len_of_mystery)-1) + ['_'] while guess_count <= MAX_GUESSES: print(''.join(mystery_list)) print_guess_count(guess_count) display_guesses(correct_guesses, wrong_guesses) user_guess = get_user_guess() mystery_list = [user_guess if letter == user_guess else blank for blank, letter in zip(mystery_list, mystery_word)] if len(user_guess) == 1 and user_guess in string.ascii_letters: if user_guess in mystery_word and user_guess not in correct_guesses: print("Great guess!\n") correct_guesses.append(user_guess) elif user_guess not in mystery_word and user_guess not in wrong_guesses: print("Nope, guess again\n") guess_count += 1 wrong_guesses.append(user_guess) else: print("You guessed that already...") continue else: print("Opps, let's try again..") continue if is_correct(correct_guesses, mystery_word): victory(guess_count, mystery_word) print("\nThe mystery word was {}".format(mystery_word)) print("All out of guesses. Game over") def main(): mystery_word_game() if __name__ == '__main__': main()
f66e2344c4b4d9bb46be28cf04fd908dea77fe21
vardecab/coursera-py4e
/Course 1 - Programming for Everybody (Getting Started with Python)/7 • Largest, Smallest & Error.py
968
4
4
# 5.2 | Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. # Once 'done' is entered, print out the largest and smallest of the numbers. # If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message # and ignore the number. # Enter the numbers from the book for problem 5.1. Match the desired output as shown: # Invalid input # Maximum is 7 # Minimum is 4 largest = None smallest = None store = [] # most important thing! while True: try: num = raw_input("Enter a number: ") if num == "done" : break else: store.append(num) except: print("Invalid input") # Python 30[00] syntax largest=max(store) smallest=min(store) print "Invalid input" print "Maximum is", largest print "Minimum is", smallest # code from: https://pr4e.dr-chuck.com/tsugi/mod/pythonauto/index.php?PHPSESSID=dc494bff41ebaa8cec27b6d1652b5c7f
3e90e2cf23a86e987166a942b49e2930935a4cc2
cassiomedeiros/q_learning_project
/qlearning/estado.py
2,481
3.53125
4
import numpy as np from typing import Tuple, List class Estado: """Classe responsável por mover o agente dentro do espaço vetorial. """ def __init__(self, estado: Tuple[int, int]=(5, 0)): self.estado = estado self.entregou_objeto: bool = False self.deterministico: bool = True self._estados_entrega: List[Tuple[int, int]] = [ (0, 2), (0, 4), (0, 3) ] self._estados_bloqueados: List[Tuple[int, int]] = [ (1, 3), (4, 0), (4, 1), (4, 3), (4, 4), (4, 5), (4, 6), (5, 6)] def obter_recompensa(self) -> int: """Obtém a recompensa para o estado atual. """ if self.estado in self._estados_entrega: return 1 else: return 0 def entregou(self) -> bool: """Verifica se o estado atual é uma posição de entrega. """ if self.estado in self._estados_entrega: self.entregou_objeto = True def _mover(self, movimento): if movimento == "cima": return np.random.choice(["cima", "esquerda", "direita"], p=[0.8, 0.1, 0.1]) if movimento == "baixo": return np.random.choice(["baixo", "esquerda", "direita"], p=[0.8, 0.1, 0.1]) if movimento == "esquerda": return np.random.choice(["esquerda", "cima", "baixo"], p=[0.8, 0.1, 0.1]) if movimento == "direita": return np.random.choice(["direita", "cima", "baixo"], p=[0.8, 0.1, 0.1]) def proximo_movimento(self, movimento): if self.deterministico: if movimento == "cima": proximo_estado = (self.estado[0] - 1, self.estado[1]) elif movimento == "baixo": proximo_estado = (self.estado[0] + 1, self.estado[1]) elif movimento == "esquerda": proximo_estado = (self.estado[0], self.estado[1] - 1) else: proximo_estado = (self.estado[0], self.estado[1] + 1) self.deterministico = False else: movimento = self._mover(movimento) self.deterministico = True proximo_estado = self.proximo_movimento(movimento) if (proximo_estado[0] >= 0) and (proximo_estado[0] <= 5): if (proximo_estado[1] >= 0) and (proximo_estado[1] <= 6): if proximo_estado not in self._estados_bloqueados: return proximo_estado return self.estado
9cbb001f8c12a0ae850cbd5d2e43dca37ff2536a
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/hard_algo/4_1.py
11,483
3.703125
4
Maximum size of square such that all submatrices of that size have sum less than K Given an **N x M** matrix of integers and an integer **K** , the task is to find the size of the maximum square sub-matrix **(S x S)** , such that **all square sub-matrices** of the given matrix of that size have a sum less than **K**. **Examples:** **Input:** K = 30 mat[N][M] = {{1, 2, 3, 4, 6}, {5, 3, 8, 1, 2}, {4, 6, 7, 5, 5}, {2, 4, 8, 9, 4} }; **Output:** 2 **Explanation:** All Sub-matrices of size **2 x 2** have sum less than 30 **Input :** K = 100 mat[N][M] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; **Output:** 3 **Explanation:** All Sub-matrices of size **3 x 3** have sum less than 100 **Naive Approach** The basic solution is to choose the size **S** of the submatrix and find all the submatrices of that size and check that the sum of all sub-matrices is less than the given sum whereas, this can be improved by computing the sum of the matrix using this approach. Therefore, the task will be to choose the maximum size possible and the starting and ending position of the every possible sub-matrices. Due to which the overall time complexity will be O(N3). Below is the implementation of the above approach: ## C++ __ __ __ __ __ __ __ // C++ implementation to find the // maximum size square submatrix // such that their sum is less than K #include <bits/stdc++.h> using namespace std; // Size of matrix #define N 4 #define M 5 // Function to preprocess the matrix // for computing the sum of every // possible matrix of the given size void preProcess(int mat[N][M], int aux[N][M]) { // Loop to copy the first row // of the matrix into the aux matrix for (int i = 0; i < M; i++) aux[0][i] = mat[0][i]; // Computing the sum column-wise for (int i = 1; i < N; i++) for (int j = 0; j < M; j++) aux[i][j] = mat[i][j] + aux[i - 1][j]; // Computing row wise sum for (int i = 0; i < N; i++) for (int j = 1; j < M; j++) aux[i][j] += aux[i][j - 1]; } // Function to find the sum of a // submatrix with the given indices int sumQuery(int aux[N][M], int tli, int tlj, int rbi, int rbj) { // Overall sum from the top to // right corner of matrix int res = aux[rbi][rbj]; // Removing the sum from the top // corer of the matrix if (tli > 0) res = res - aux[tli - 1][rbj]; // Remove the overlapping sum if (tlj > 0) res = res - aux[rbi][tlj - 1]; // Add the sum of top corner // which is substracted twice if (tli > 0 && tlj > 0) res = res + aux[tli - 1][tlj - 1]; return res; } // Function to find the maximum // square size possible with the // such that every submatrix have // sum less than the given sum int maximumSquareSize(int mat[N][M], int K) { int aux[N][M]; preProcess(mat, aux); // Loop to choose the size of matrix for (int i = min(N, M); i >= 1; i--) { bool satisfies = true; // Loop to find the sum of the // matrix of every possible submatrix for (int x = 0; x < N; x++) { for (int y = 0; y < M; y++) { if (x + i - 1 <= N - 1 && y + i - 1 <= M - 1) { if (sumQuery(aux, x, y, x + i - 1, y + i - 1) > K) satisfies = false; } } } if (satisfies == true) return (i); } return 0; } // Driver Code int main() { int K = 30; int mat[N][M] = { { 1, 2, 3, 4, 6 }, { 5, 3, 8, 1, 2 }, { 4, 6, 7, 5, 5 }, { 2, 4, 8, 9, 4 } }; cout << maximumSquareSize(mat, K); return 0; } --- __ __ ## Java __ __ __ __ __ __ __ // Java implementation to find the // maximum size square submatrix // such that their sum is less than K class GFG{ // Size of matrix static final int N = 4; static final int M = 5; // Function to preprocess the matrix // for computing the sum of every // possible matrix of the given size static void preProcess(int [][]mat, int [][]aux) { // Loop to copy the first row // of the matrix into the aux matrix for (int i = 0; i < M; i++) aux[0][i] = mat[0][i]; // Computing the sum column-wise for (int i = 1; i < N; i++) for (int j = 0; j < M; j++) aux[i][j] = mat[i][j] + aux[i - 1][j]; // Computing row wise sum for (int i = 0; i < N; i++) for (int j = 1; j < M; j++) aux[i][j] += aux[i][j - 1]; } // Function to find the sum of a // submatrix with the given indices static int sumQuery(int [][]aux, int tli, int tlj, int rbi, int rbj) { // Overall sum from the top to // right corner of matrix int res = aux[rbi][rbj]; // Removing the sum from the top // corer of the matrix if (tli > 0) res = res - aux[tli - 1][rbj]; // Remove the overlapping sum if (tlj > 0) res = res - aux[rbi][tlj - 1]; // Add the sum of top corner // which is substracted twice if (tli > 0 && tlj > 0) res = res + aux[tli - 1][tlj - 1]; return res; } // Function to find the maximum // square size possible with the // such that every submatrix have // sum less than the given sum static int maximumSquareSize(int [][]mat, int K) { int [][]aux = new int[N][M]; preProcess(mat, aux); // Loop to choose the size of matrix for (int i = Math.min(N, M); i >= 1; i--) { boolean satisfies = true; // Loop to find the sum of the // matrix of every possible submatrix for (int x = 0; x < N; x++) { for (int y = 0; y < M; y++) { if (x + i - 1 <= N - 1 && y + i - 1 <= M - 1) { if (sumQuery(aux, x, y, x + i - 1, y + i - 1) > K) satisfies = false; } } } if (satisfies == true) return (i); } return 0; } // Driver Code public static void main(String[] args) { int K = 30; int mat[][] = { { 1, 2, 3, 4, 6 }, { 5, 3, 8, 1, 2 }, { 4, 6, 7, 5, 5 }, { 2, 4, 8, 9, 4 } }; System.out.print(maximumSquareSize(mat, K)); } } // This code is contributed by PrinciRaj1992 --- __ __ ## Python3 __ __ __ __ __ __ __ # Python3 implementation to find the # maximum size square submatrix # such that their sum is less than K # Size of matrix N = 4 M = 5 # Function to preprocess the matrix # for computing the sum of every # possible matrix of the given size def preProcess(mat, aux): # Loop to copy the first row # of the matrix into the aux matrix for i in range (M): aux[0][i] = mat[0][i] # Computing the sum column-wise for i in range (1, N): for j in range (M): aux[i][j] = (mat[i][j] + aux[i - 1][j]) # Computing row wise sum for i in range (N): for j in range (1, M): aux[i][j] += aux[i][j - 1] # Function to find the sum of a # submatrix with the given indices def sumQuery(aux, tli, tlj, rbi, rbj): # Overall sum from the top to # right corner of matrix res = aux[rbi][rbj] # Removing the sum from the top # corer of the matrix if (tli > 0): res = res - aux[tli - 1][rbj] # Remove the overlapping sum if (tlj > 0): res = res - aux[rbi][tlj - 1] # Add the sum of top corner # which is substracted twice if (tli > 0 and tlj > 0): res = (res + aux[tli - 1][tlj - 1]) return res # Function to find the maximum # square size possible with the # such that every submatrix have # sum less than the given sum def maximumSquareSize(mat, K): aux = [[0 for x in range (M)] for y in range (N)] preProcess(mat, aux) # Loop to choose the size of matrix for i in range (min(N, M), 0, -1): satisfies = True # Loop to find the sum of the # matrix of every possible submatrix for x in range (N): for y in range (M) : if (x + i - 1 <= N - 1 and y + i - 1 <= M - 1): if (sumQuery(aux, x, y, x + i - 1, y + i - 1) > K): satisfies = False if (satisfies == True): return (i) return 0 # Driver Code if __name__ == "__main__": K = 30 mat = [[1, 2, 3, 4, 6], [5, 3, 8, 1, 2], [4, 6, 7, 5, 5], [2, 4, 8, 9, 4]] print( maximumSquareSize(mat, K)) # This code is contributed by Chitranayal --- __ __ ## C# __ __ __ __ __ __ __ // C# implementation to find the // maximum size square submatrix // such that their sum is less than K using System; public class GFG{ // Size of matrix static readonly int N = 4; static readonly int M = 5; // Function to preprocess the matrix // for computing the sum of every // possible matrix of the given size static void preProcess(int [,]mat, int [,]aux) { // Loop to copy the first row // of the matrix into the aux matrix for (int i = 0; i < M; i++) aux[0,i] = mat[0,i]; // Computing the sum column-wise for (int i = 1; i < N; i++) for (int j = 0; j < M; j++) aux[i,j] = mat[i,j] + aux[i - 1,j]; // Computing row wise sum for (int i = 0; i < N; i++) for (int j = 1; j < M; j++) aux[i,j] += aux[i,j - 1]; } // Function to find the sum of a // submatrix with the given indices static int sumQuery(int [,]aux, int tli, int tlj, int rbi, int rbj) { // Overall sum from the top to // right corner of matrix int res = aux[rbi,rbj]; // Removing the sum from the top // corer of the matrix if (tli > 0) res = res - aux[tli - 1,rbj]; // Remove the overlapping sum if (tlj > 0) res = res - aux[rbi,tlj - 1]; // Add the sum of top corner // which is substracted twice if (tli > 0 && tlj > 0) res = res + aux[tli - 1,tlj - 1]; return res; } // Function to find the maximum // square size possible with the // such that every submatrix have // sum less than the given sum static int maximumSquareSize(int [,]mat, int K) { int [,]aux = new int[N,M]; preProcess(mat, aux); // Loop to choose the size of matrix for (int i = Math.Min(N, M); i >= 1; i--) { bool satisfies = true; // Loop to find the sum of the // matrix of every possible submatrix for (int x = 0; x < N; x++) { for (int y = 0; y < M; y++) { if (x + i - 1 <= N - 1 && y + i - 1 <= M - 1) { if (sumQuery(aux, x, y, x + i - 1, y + i - 1) > K) satisfies = false; } } } if (satisfies == true) return (i); } return 0; } // Driver Code public static void Main(String[] args) { int K = 30; int [,]mat = { { 1, 2, 3, 4, 6 }, { 5, 3, 8, 1, 2 }, { 4, 6, 7, 5, 5 }, { 2, 4, 8, 9, 4 } }; Console.Write(maximumSquareSize(mat, K)); } } // This code contributed by PrinciRaj1992 --- __ __ **Output:** 2
601b00c80794e71cf0cca6148d29b855fa998aed
jfriend08/practice
/linkList/compStringLinkList.py
940
3.890625
4
''' Compare two strings represented as linked lists Input: list1 = g->e->e->k->s->a list2 = g->e->e->k->s->b Output: -1 Input: list1 = g->e->e->k->s->a list2 = g->e->e->k->s Output: 1 Input: list1 = g->e->e->k->s list2 = g->e->e->k->s Output: 0 ''' from ListNode import ListNode def compareString(h1, h2): p1, p2 = h1, h2 if p1 == None or p2 == None: return -1 while p1 != None and p2 != None: if p1.val != p2.val: return -1 p1 = p1.next p2 = p2.next return (0 if p1==None and p2==None else 1) n1, n2, n3, n4, n5, n6 = ListNode("g"), ListNode("e"), ListNode("e"), ListNode("k"), ListNode("s"), ListNode("a") n1.next = n2 n2.next = n3 n3.next = n4 n4.next = n5 n5.next = n6 N1, N2, N3, N4, N5, N6 = ListNode("g"), ListNode("e"), ListNode("e"), ListNode("k"), ListNode("s"), ListNode("b") N1.next = N2 N2.next = N3 N3.next = N4 N4.next = N5 # N5.next = N6 print compareString(n1, N1)
b4c4803692537a2c2881b6da571b9c0d5f8c3145
heenashree/HRCodes
/minion-game.py
88
3.578125
4
A = [i for i in input().upper().split()] print(A) for i in range(len(A)): if (A[i])
fb2163e6f84be0a1b210e0c5e32ceeacafc3488a
CrazyHatish/DAS5334
/AulaN/Exercise6.py
137
3.796875
4
def is_anagram(s1, s2): l1 = list(s1) l2 = list(s2) return sorted(l1) == sorted(l2) print(is_anagram("batata", "tatbaa"))
2564e32ecf9c32308b08890bc9950caec284b782
brianchiang-tw/leetcode
/2020_August_Leetcode_30_days_challenge/Week_3_Sort Array by Parity/by_two-pointers_and_swap.py
1,892
4.25
4
''' Description: Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example 1: Input: [3,1,2,4] Output: [2,4,3,1] The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. Note: 1 <= A.length <= 5000 0 <= A[i] <= 5000 ''' from typing import List class Solution: def sortArrayByParity(self, A: List[int]) -> List[int]: # ------------------------------------------------ def swap(arr, odd_idx ): arr[swap.even_idx], arr[odd_idx] = arr[odd_idx], arr[swap.even_idx] swap.even_idx += 1 # ------------------------------------------------ swap.even_idx = 0 is_even_number = lambda x: not( x & 1 ) for i in range( len(A) ): # scan each element if is_even_number(A[i]): swap(A, i) # swap even number to the left-hand side return A # n : the length of input array, A ## Time Complexity: O( n ) # # The overhead in time is the cost of iteration, which is of O( n ) ## Space Complexity: O( n ) # # The overhead in space is the storage for loop index and temporary variable, which is of O( 1 ) import unittest class Testing( unittest.TestCase ): def test_case_1( self ): res = Solution().sortArrayByParity( A = [3,1,2,4] ) check_even = all( map(lambda x: x%2 == 0, res[:len(res)//2] ) ) self.assertEqual(check_even, True) def test_case_2( self ): res = Solution().sortArrayByParity( A = [7,1,2,5,6,8] ) check_even = all( map(lambda x: x%2 == 0, res[:len(res)//2] ) ) self.assertEqual(check_even, True) if __name__ == '__main__': unittest.main()
67bb7c668146f5fa00b9547ea1fcef9f1ef8fcc3
alexjercan/algorithms
/old/leetcode/problems/merge-sorted-array.py
745
3.953125
4
from typing import List class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: array_len = m i = 0 j = 0 while i < array_len and j < n: if nums1[i] >= nums2[j]: insert(nums1, i, nums2[j]) i = i + 1 j = j + 1 array_len = array_len + 1 else: i = i + 1 while j < n: insert(nums1, i, nums2[j]) i = i + 1 j = j + 1 def insert(nums, index, num): for i in range(len(nums) - 1, index, -1): nums[i] = nums[i - 1] nums[index] = num nums1 = [1, 2, 3, 0, 0, 0] Solution().merge(nums1, 3, [2, 5, 6], 3) print(nums1)
63eacee47ea7dfcae872d03123e2db3fec20327d
usercngit/INF123_TeamCSS
/srcGame/GetUsername.py
1,353
3.71875
4
""" @author: Sofanah """ import pygame from pygame.locals import * import string class GetUsername: def __init__(self, window, height, width): self._screen = window self._height = height self._width = width def get_key(self): while True: event = pygame.event.poll() if event.type == KEYDOWN: return event.key # elif event.type == pygame.QUIT: # exit() else: pass def draw(self, username): tfont = pygame.font.Font(None, 20) pygame.draw.rect(self._screen, (0,0,0), ((self._width/2)-100, (self._height/2)-10, 200,20), 0) pygame.draw.rect(self._screen, (255,255,255), ((self._width/2)-102, (self._height/2)-12, 204,24), 1) if len(username) != 0: self._screen.blit(tfont.render(username, 1, (255,0,0)), ((self._width/ 2) - 100, (self._height/ 2) - 10)) pygame.display.update() def get_data(self): username = [] self.draw("Username: " + string.join(username,"")) while True: inputkey = self.get_key() if inputkey == K_BACKSPACE: print "delete" username = username[0:-1] elif inputkey == K_RETURN: break elif inputkey <=127: username.append(chr(inputkey)) self.draw("Username: "+ string.join(username,"")) return string.join(username,"") pygame.init() screen = pygame.display.set_mode((320,240)) start = GetUsername(screen, 320, 240) print (start.get_data())
9cc22875e1b88e774b90f075b810ef602e35739d
daniel-reich/turbo-robot
/eA94BuKYjwMoNQSE2_13.py
557
4.3125
4
""" Create a function that returns `True` if a given inequality expression is correct and `False` otherwise. ### Examples correct_signs("3 < 7 < 11") ➞ True correct_signs("13 > 44 > 33 > 1") ➞ False correct_signs("1 < 2 < 6 < 9 > 3") ➞ True ### Notes N/A """ def correct_signs(txt): chars = txt.split(" ") for i in range(2, len(chars), 2): if chars[i-1] == ">": if not(int(chars[i-2]) > int(chars[i])): return False elif not(int(chars[i-2]) < int(chars[i])): return False return True
07037668596908c2a8aa226c6c2fd09e73181559
jefferyyuan/interviewjam
/dynamic_programming/leetcode_House_Robber.py
710
3.5625
4
"""leetcode_House_Robber.py https://leetcode.com/problems/house-robber/ """ class Solution: """DP. dp[i] = max(dp[i - 2] + arr[i], dp[i - 1]) Yes you can use an array to represent dp states but in this case use two variables are good enought, just like fibonacci. """ def rob(self, nums): """""" if not nums: return 0 if len(nums) == 1: return nums[0] prev, cur = nums[0], max(nums[0:2]) for i in nums[2:]: prev, cur = cur, max((prev + i), cur) return max(cur, prev) def main(): nums = [1, 2, 3, 4, 5] sol = Solution() print sol.rob(nums) if __name__ == '__main__': main()
49e75e4a132e40c105e00eee4d6a2f6f3f0b10aa
SAIKUMARAR7/Python
/area_circle.py
76
3.96875
4
r=int(input("enter the radius")) print("area of circle is",round(3.14*r*r))
28ee60df40b07e022b5524f324ccaf23f8ceae1f
Thiago-Mauricio/Curso-de-python
/Curso em Video/Aula17 Listas parte1/Aula17 Listas.py
696
3.875
4
l = [] for c in range(1,10): l.insert(0, c) print(l) l = [] for c in range(1,10): l.append(c) print(l) num = [2, 5, 9, 1] num[2] = 3 num.append(7) num.sort(reverse=True) num.insert(2, 0) if 4 in num: num.remove(4) print(num) print(f'essa lista tem {len(num)} elementos.') valores = [] valores.append(5) valores.append(9) valores.append(4) for v in valores: print(f'{v}...', end='') print('') for c, i in enumerate(valores): print(f'Na posição {c} encontrei o valor {i}!') print('Cheguei ao final da lista !') a = [2, 3, 4, 7] #ligação entra a listas b = a, a = b b = a #cópia da lista: c = a[:] b[2] = 8 print(f'Lista: {a}') print(f'Lista: {b}') print(f'Lista: {c}')
0859f2533db665fdc00e3b5cb67946d50188d667
rudeqit/crypto
/graph/graph.py
3,534
3.65625
4
#!/usr/bin/env python3 # Take it from here: https://github.com/plutasnyy/Cycles-in-graphs from random import randint import copy import time class Graph: def __init__(self, number_of_vertices, density): ''' minimum destinity -> n * (n-1) / 2 * d >= n - 1 is equal to d >= 2/n ''' if density < 200 / number_of_vertices: density = 200 / number_of_vertices self.matrix = [] self.number_of_vertices = int(number_of_vertices) self.create_full_graph() self.delete_edges(density) self.number_of_edges = self.count_edge() def find_non_empty_index(self): x, y = 0, 0 x_counter, y_counter = 1, 1 temp = self.number_of_vertices while (self.matrix[x][y] == 0 or x_counter <= 1 or y_counter <= 1): x, y = randint(1,temp), randint(1,temp) x_counter = self.matrix[x].count(1) y_counter = self.matrix[y].count(1) return x, y def delete_edges(self, density): full_count_edges = self.number_of_vertices * (self.number_of_vertices - 1) / 2 for i in range(int(full_count_edges * (100 - density) / 100)): x, y = self.find_non_empty_index() self.matrix[x][y] = self.matrix[y][x] = 0 def count_edge(self): temp = 0 for i in self.matrix: temp += i.count(1) return temp / 2 def create_full_graph(self): for i in range(0, self.number_of_vertices + 1): X = [] for j in range(0, self.number_of_vertices + 1): if j * i == 0 or j == i: X.append(0) else: X.append(1) self.matrix.append(X) def print_neighbours_list(self): # print(self.matrix) for i in range(1, self.number_of_vertices + 1): X = [x for x in range(len(self.matrix[i])) if self.matrix[i][x]] print(i, X) def delete_reverse_list(self, temp_list): for i in temp_list: if i[::-1] in temp_list: temp_list.remove(i[::-1]) def print_list(self, temp_list): for i in temp_list: print(i) def find_hamilton_cycle(self, vertice, visited=[], one_path=False): if one_path == False or self.capture_hamilton == False: visited.append(vertice) if len(visited) == self.number_of_vertices: if self.matrix[visited[0]][visited[-1]] == 1: visited.append(visited[0]) self.hamilton_cycle.append(copy.deepcopy(visited)) # list() copy the array, without it doesn`t work self.capture_hamilton = True for i in range(1, self.number_of_vertices + 1): if self.matrix[vertice][i] == 1 and i not in visited: self.find_hamilton_cycle(i,copy.deepcopy(visited), one_path) visited.pop() def hamilton(self, one_path=False): self.capture_hamilton = False self.hamilton_cycle = [] self.find_hamilton_cycle(1, [], one_path) self.delete_reverse_list(self.hamilton_cycle) if len(self.hamilton_cycle) > 0: print("Hamilton cicle: ") self.print_list(self.hamilton_cycle) return self.hamilton_cycle if __name__ == "__main__": graph = Graph(5, 70) graph.print_neighbours_list() start = time.time() graph.hamilton() print("hamilton", time.time() - start)
ed2ec2292903b50b00ab779d56fdda5e6d20be19
SimonVarga2008/sandbox
/demo.py
238
3.765625
4
sum = 0 for i in range ( 0 ): sum += i print ( sum ) x = 5 y = "Nieco" print( x, y ) print2 = 22 print( print2 ) def print3(item): print(item) print(item) print3( 33 ) print() def x2( x ): print( x * x ) x2( 5 )
7972cb83a570b01fa1c7ec2827edb8fd136ae2d8
leonhostetler/undergrad-projects
/computational-physics/03_plotting/sunspots.py
804
3.6875
4
#! /usr/bin/env python """ Plot the observed number of sunspots for each month. Leon Hostetler, Feb. 2, 2017 USAGE: sunspots.py """ from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt # Main body of program r = 5 # The 'half-length' of the weighted average # Load the data from the file data = np.loadtxt("sunspots.txt", float) x = data[0:1001, 0] y = data[0:1001, 1] # Compute the weighted average X = x[r:len(x)-r] Y = [] for k in range(r, len(x)-r): avg = 0 for m in range(k-r, k+r+1): avg += y[m] Y.append(avg/(2*r+1)) # Plot the results plt.plot(x, y, linewidth=.5, c="g") plt.plot(X, Y, linewidth=2, c="k") plt.title("Sunspots per Month") plt.xlabel("Month") plt.ylabel("Number of Sunspots") plt.savefig("sunpots.png") plt.show()
936af4208862ce16bfb4dec8e7c9e94df5a2ae54
romskr9/python_examples
/math/myparser.py
2,411
3.515625
4
from mymath import * class Parser: def __init__(self, name = None): self.init(name) def init(self, name = None): self.token = None self.one = None if name: self.name = name self.f = file(name, 'r') def getone(self): if self.one: result = self.one self.one = None # print 'got one char from buffer', result return result else: result = self.f.read(1) # print 'read one char from file', result, len (result) return result def putone(self, one): self.one = one def get(self): if self.token: result = self.token self.token = None return result else: c = self.getone() while c.isspace(): c = self.getone() if c == '': return 'end' elif c.isupper(): result = c c = self.getone() while c.islower(): result += c c = self.getone() self.putone(c) return result elif c.islower() or c in '+-*()': return c elif c.isdigit(): result = c c = self.getone() while c.isdigit(): result += c c = self.getone() self.putone(c) return result else: print 'error>>', c def put(self, token): self.token = token def read(self): return self.readSum() token = self.get() def readSum(self): token = self.get() if token != '-': self.put(token) n1 = self.readProduct() if token == '-': n1.multiplewith(-1) if n1 is not None: token = self.get() if token in ['+', '-']: n = Node('+') n.data.append(n1) while token in ['+', '-']: n2 = self.readProduct() if token == '-': n2.multiplewith(-1) n.data.append(n2) token = self.get() self.put(token) return n else: self.put(token) return n1 else: return n1 def readProduct(self): n1 = self.readAtom() if n1 is not None: token = self.get() self.put(token) if token not in ['+', '-', ')', 'end']: n = Node('*') n.data.append(n1) while token not in ['+', '-', ')', 'end']: n2 = self.readAtom() n.data.append(n2) token = self.get() self.put(token) return n else: return n1 else: return n1 def readAtom(self): token = self.get() if token.isalpha(): n = Node('A', token) return n elif token.isdigit(): n = Node('D', int(token)) return n elif token == '(': n = self.readSum() token = self.get() return n
3e98206e8874bf1a5a58b4fd84516e9251c2c181
mmkhaque/LeetCode_Practice
/1213. Intersection of Three Sorted Arrays.py
1,161
4.28125
4
''' Time: O(N) Space: O(N) ''' ''' Better here https://leetcode.com/problems/intersection-of-three-sorted-arrays/solution/ ''' ''' Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays. Example 1: Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8] Output: [1,5] Explanation: Only 1 and 5 appeared in the three arrays. Example 2: Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764] Output: [] ''' class Solution: def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: d = collections.defaultdict(list) for i in range(len(arr1)): d[arr1[i]].append('1') for i in range(len(arr2)): d[arr2[i]].append('2') for i in range(len(arr3)): d[arr3[i]].append('3') result = [] for key, values in d.items(): if len(values) == 3: result.append(key) return result
ceb26aefe922da6142caee7622ddf7b4eff36c38
geddings/pynancial
/tests/test_pynancial.py
1,661
3.515625
4
from collections import namedtuple Bracket = namedtuple('Bracket', ['rate', 'floor', 'ceiling']) class MarriedFilingJointly(object): def __init__(self): self.brackets = [ Bracket(rate=0.10, floor=0, ceiling=19750), Bracket(rate=0.12, floor=19751, ceiling=80250), Bracket(rate=0.22, floor=80251, ceiling=171050), Bracket(rate=0.24, floor=171051, ceiling=326600), Bracket(rate=0.32, floor=326601, ceiling=414700), Bracket(rate=0.35, floor=414701, ceiling=622050), Bracket(rate=0.37, floor=622051, ceiling=None), ] def marginal_tax_rate(self, taxable_income): for bracket in self.brackets: if taxable_income < bracket.ceiling: return bracket.rate def taxes_owed(self, taxable_income): taxes = 0 for bracket in self.brackets: if taxable_income > bracket.ceiling: taxes += bracket.ceiling * bracket.rate else: taxes += (taxable_income - bracket.floor) * bracket.rate return round(taxes, 2) def effective_tax_rate(self, taxable_income): return round(self.taxes_owed(taxable_income) / taxable_income, 2) if __name__ == '__main__': income = 145000 filing_status = MarriedFilingJointly() print("Income: {income}".format(income=income)) print("Marginal tax rate: {rate}".format(rate=filing_status.marginal_tax_rate(income))) print("Effective tax rate: {rate}".format(rate=filing_status.effective_tax_rate(income))) print("Taxes owed: {rate}".format(rate=filing_status.taxes_owed(income)))
0648d6e1fd48aa2b4155f01e9d8dc1ad7bdcf836
ydzhang12345/LeetCode
/22.Generate_Parentheses/sol.py
641
3.53125
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ from typing import List class Solution: def generateParenthesis(self, n: int) -> List[str]: out = set() left, right, s = 0, 0, '' def dfs(l, r, s): if l==n and r==n: out.add((s)) if l < n: dfs(l+1, r, s+'(') if r < l: dfs(l, r+1, s+')') dfs(left, right, s) return out s = Solution() print(s.generateParenthesis(0))
92eb9ba5db45831bbdb5f89bddaf3c5ca8943ce6
capncrockett/beedle_book
/Ch_09 - Simulation and Design/cube_field_solution.py
2,060
4.03125
4
# cube_field_solution # c09ex15.py # Puzzle problem. Imagine a cube circumscribed about a unit sphere. # An "eyeball" at the origin "sees" each wall as 1/6 of the field of # view. Suppose the eye is moved to (0.5, 0, 0), what proportion of # the total field of view is taken up by the side of the cube at x = 1. # This program approximates the solution to this problem using Monte Carlo # techniques. It generates rays in random directions from the point of # observation and determines the proportion that intersect the side of cube # at x = 1. # if x is the x position of the observer and (a,b,c) are the components of a # direction vector, the points along the ray from the observer in that # direction are given by the parametric equation: p = (x,0,0) + t(a,b,c) for # t >= 0. Solving for the time of intersection (when p.x == 1) we have get # t == (1-x)/ a. Thus the point of intersection is (1, (1-x)b/a, (1-x)c/a) # So the ray "strikes" the side of interest if: # (-1 <= (1-x)b/a <=1) and (-1 <= (1-x)c/a <= 1) from random import random def random_direction(): # Generate a random direction vector in 3-D space. # Method: generate a random point inside of a unit sphere. # (x,y,z) are chosen in the range -1.0 to 1.0. Any point falling # outside of the unit sphere is discarded. while True: # Generate points until a suitable one is found. x = 2 * random()-1 y = 2 * random()-1 z = 2 * random()-1 if x*x + y*y + z*z < 1 and (x, y, z) != (0, 0, 0): return x, y, z def main(): print("Puzzle problem solver.\n") x = float(input("Enter x position of the observer (-1 <= x < 1) ")) n = int(input("Number of samplings: ")) hits = 0 for i in range(n): a, b, c = random_direction() t = (1 - x) / a if t > 0 and (-1 <= t*b <= 1) and (-1 <= t*c <= 1): hits = hits + 1 print("Estimated FOV =", hits/n) if __name__ == '__main__': main()
c3769b66b74b2aa10daff6f8d39faa5478f97e9d
skye7803/new_project
/v2/main.py
4,549
3.59375
4
from world import World from player import Player class Main: actions = { 'help': { 'commands': ['h', 'help'], 'description': 'Show this help text', }, 'north': { 'commands': ['n', 'north'], 'description': 'Move in a north direction', }, 'south': { 'commands': ['s', 'south'], 'description': 'Move in a south direction', }, 'east': { 'commands': ['e', 'east'], 'description': 'Move in a east direction', }, 'west': { 'commands': ['w', 'west'], 'description': 'Move in a west direction', }, 'quit': { 'commands': ['q', 'quit'], 'description': 'End the game', }, } world_size = 4 def __init__(self): self.world = World(Main.world_size) self.player = Player() self.player.x = int(Main.world_size / 2) self.player.y = int(Main.world_size / 2) def mainloop(self): print('Welcome to the game...creatively named:') print(''' _ _ _______ ______ ____ ___ _ _____ ____ _____ | \ | | ____\ \ / / _ \| _ \ / _ \ | | ____/ ___|_ _| | \| | _| \ \ /\ / /| |_) | |_) | | | |_ | | _|| | | | | |\ | |___ \ V V / | __/| _ <| |_| | |_| | |__| |___ | | |_| \_|_____| \_/\_/ |_| |_| \_\\\___/ \___/|_____\____| |_| ''') self.show_help() print(self.world) # debug while True: location = self.player_location() print(f'location: ({self.player.x + 1}, {self.player.y + 1})') # debug (add one to make counting easy) print(f'You are in a {location}, it is {location.description()}') # could use location.biome also command = input('What would you like to do? ') if command in Main.actions['help']['commands']: self.show_help() elif command in Main.actions['north']['commands']: self.move('north') elif command in Main.actions['south']['commands']: self.move('south') elif command in Main.actions['east']['commands']: self.move('east') elif command in Main.actions['west']['commands']: self.move('west') elif command in Main.actions['quit']['commands']: self.quit() print('_' * 79) def show_help(self): print('Available Commands:') for name, action in Main.actions.items(): commands = ','.join(action['commands']) description = action['description'] # example of one way to have multiple prints show up on one line (set the "end" to something else) # print(commands, end=': ') # print(description) # better way to print help (lines everything up nicely by adding spaces so commands is always 8 chars wide) # https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals print(f'{commands:8} -> {description}') print() # extra newline def player_location(self): return self.world.grid[self.player.x][self.player.y] def show_blockage(self, direction): print(f"You can't go {direction} because {self.player_location().blockage()}") def move(self, direction): if direction == 'north': if self.player.x == 0: self.show_blockage(direction) else: self.player.x -= 1 elif direction == 'south': if self.player.x == self.world_size - 1: # account for 0-index arrays self.show_blockage(direction) else: self.player.x += 1 elif direction == 'east': if self.player.y == self.world_size - 1: # account for 0-index arrays self.show_blockage(direction) else: self.player.y += 1 elif direction == 'west': if self.player.y == 0: self.show_blockage(direction) else: self.player.y -= 1 def quit(self): confirm = input("Are you sure you want to quit the game? ('y' or 'yes' to end): ") if confirm not in ['y', 'yes']: return print(''' ____ _ | __ ) _ _ ___| | | _ \| | | |/ _ \ | | |_) | |_| | __/_| |____/ \__, |\___(_) |___/ ''') exit(0) Main().mainloop()
cb63ed5d91c5fd208da03eba11bfb3eb7d604ff1
emanoelmlsilva/Lista-IP
/exercicio05/programa06.py
882
3.921875
4
valor_produto = int(input('Informe o valor do produto: ')) tipo = str.lower(input('Informe a forma de pagamento:(Dinheiro / Cheque ou Cartao)')) if((tipo == 'dinheiro') and (valor_produto >= 100)): pagar = (valor_produto - (valor_produto*0.10)) elif((tipo != 'cheque') and (tipo != 'dinheiro') and (tipo != 'cartao')): pagar = 'Forma de pagamento invalida' elif(tipo == 'cartao'): escolha = str.lower(input('Debito ou Credito:')) if(escolha == 'debito'): pagar = valor_produto elif(escolha == 'credito'): quant = int(input('Informe a quantidade de parcelas (maxi = 3):')) pagar = valor_produto/quant else: print('Opçao nao existe') else: pagar = valor_produto if(tipo == 'cartao'): print('R$ {}'.format(valor_produto)) print('{} parcelas de R$ {}'.format(quant,pagar)) else: print('R$ {}'.format(pagar))
5fb9a27ad482228625151d0363d913f97e8c7ed5
Eacruzr/python-code
/individual/reto1.py
1,150
3.78125
4
print("Bienvenido al sistema de ubicación para zonas públicas WIFI") nombre_usuario='51743' #El usuario definido contraseña='34715' #La contraseña definida dato_usuario=input('Ingrese el nombre de usuario: ') #Se solicita el usuario a la persona if dato_usuario==nombre_usuario: #Se compara el usuario ingresado con el del sistema para hacer la verificacion dato_contraseña=input('Ingrese la contraseña: ') #Se solicita la contraseña al usuario if dato_contraseña==contraseña: #Se compara la contraseña ingresada con la registrada en el sistema print("Solucione el captcha de seguridad") segundo_dato=2*4+8-12 valor_captcha=743+segundo_dato #El valor del captcha captcha=int(input("Solucione 743+4 = ")) #Se solicita al usuario que ingrese la solucion del captcha if valor_captcha==captcha: #Se compara el dato ingresado por el usuario y el que esta en el sistema print("Sesión iniciada") #Se verifica que el proceso fue correcto else: print("Error") #Hubo un fallo en algun momento del proceso else: print("Error") else: print("Error")
15efd26ca928a0b61aa1b2f943081972c54f5072
JenZhen/LC
/lc_ladder/company/gg/high_freq/Isomorphic_String.py
1,405
4.15625
4
#! /usr/local/bin/python3 # https://leetcode.com/problems/isomorphic-strings/ # Example # Given two strings s and t, determine if they are isomorphic. # # Two strings are isomorphic if the characters in s can be replaced to get t. # # All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself. # # Example 1: # # Input: s = "egg", t = "add" # Output: true # Example 2: # # Input: s = "foo", t = "bar" # Output: false # Example 3: # # Input: s = "paper", t = "title" # Output: true # Note: # You may assume both s and t have the same length. """ Algo: D.S.: Solution: 注意:一对一关系需要2个map 来实现 Corner cases: """ class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return False s_to_t = {} t_to_s = {} for i in range(len(s)): src, tgt = s[i], t[i] if src not in s_to_t and tgt not in t_to_s: s_to_t[src] = tgt t_to_s[tgt] = src elif src in s_to_t and tgt in t_to_s: if s_to_t[src] != tgt or t_to_s[tgt] != src: return False else: return False return True # Test Cases if __name__ == "__main__": solution = Solution()
833ddf8db957715a7740e57ec0e4225e40ad737a
lunatic-7/python_course_noob-git-
/while_loop.py
129
3.90625
4
# loops # while loop, for loop # print("hello world") # 10 times i = 1 while i<=10: print(f"hello world {i}") i = i + 1
3e640c49e51eaa6a15bd927cd4b25e11245a7d32
stephenjust/arduino-gps-glasses
/server/pqueue.py
3,123
4.1875
4
""" Priority queue implementation as a binary heap pop_smallest() remove the element with the lowest priority return tuple (key, priority) update(key, priority) lower the priority of an element if priority is not lower do nothing, if key is not in priority queue, add it return True if priority of a key has changed or is added, otherwise False is_empty() return True if nothing is in the priority queue, otherwise False >>> q = PQueue() >>> q.is_empty() True >>> q.update("thing", 1) True >>> q.is_empty() False >>> q.update("another thing", 5) True >>> q.pop_smallest() ('thing', 1) >>> q.is_empty() False >>> q.update("thing", 3) True >>> q.update("another thing", 1) True >>> len(q) 2 >>> 'thing' in q True >>> 'nothing' in q False >>> q.pop_smallest() ('another thing', 1) >>> q.pop_smallest() ('thing', 3) >>> q.is_empty() True """ def _parent(i): """ >>> _parent(3) 1 >>> _parent(27) 13 """ return (i-1)//2 def _children(i): """ >>> _children(5) [11, 12] """ return [ 2*i + 1, 2*i + 2 ] class PQueue: def __init__(self): self._heap = [] self._keyindex = {} def __len__(self): return len(self._heap) def __contains__(self, key): return key in self._keyindex def update(self, key, priority): if key in self._keyindex: i = self._keyindex[key] # Update existing entry, possibly lower its priority if priority > self._priority(i): return False else: self._heap[i] = (key, priority) self._heapify_up(i) return True else: # Create a new heap entry self._heap.append( (key, priority) ) self._keyindex[key] = len(self._heap) - 1; self._heapify_up(len(self._heap) - 1) return True def pop_smallest(self): self._swap(0, len(self._heap) - 1) rv = self._heap.pop() del self._keyindex[rv[0]] self._heapify_down(0) return rv def is_empty(self): return len(self._heap) == 0 def _swap(self, i, j): (self._heap[i], self._heap[j]) = (self._heap[j], self._heap[i]) self._keyindex[self._heap[i][0]] = i self._keyindex[self._heap[j][0]] = j def _priority(self, i): return self._heap[i][1] def _heapify_down(self, i): children = [ c for c in _children(i) if c < len(self._heap) ] if not children: return # Find child with smallest priority minchild = min(children, key = self._priority) if self._priority(i) > self._priority(minchild): # Swap element i with its smallest child self._swap(i, minchild) self._heapify_down(minchild) def _heapify_up(self, i): if i == 0: return # compare i with its parent if self._priority(i) < self._priority(_parent(i)): self._swap(i, _parent(i)) self._heapify_up(_parent(i)) if __name__ == "__main__": import doctest doctest.testmod()
9cbd45bb5f2a735f4602c7d5f25639c4b1fbd210
osvaldohg/hacker_rank
/warmup/time_conversion.py
402
3.90625
4
#!/bin/python # https://www.hackerrank.com/challenges/time-conversion/problem # by oz import sys time = raw_input().strip() ltime=time.split(":") hour=int(ltime[0]) if "AM" in time: if hour==12: print "00"+time[2:8] else: print time[:-2] else: if hour==12: print time[:-2] else: hour=hour+12 print str(hour)+time[2:8]
27d0a50576656923cc061e99d24c633eabcf4ce4
srashee2/CourseProject
/SKlearn_w_subclass.py
6,263
3.53125
4
#!/usr/bin/env python # coding: utf-8 # # Import essential libraries # In[1]: import pandas as pd import matplotlib.pyplot as plt from sklearn.feature_extraction.text import CountVectorizer from sklearn.decomposition import LatentDirichletAllocation from nltk.stem import WordNetLemmatizer import pyLDAvis.sklearn # In[2]: def lemma_text(text): lemmatizer = WordNetLemmatizer() return [lemmatizer.lemmatize(word) for word in text] # In[3]: main_df = pd.read_csv('NYT2000_1.csv', usecols=['Body', 'Publication Day Of Month', 'Publication Month', 'Publication Year']) temp_df = pd.read_csv('NYT2000_2.csv', usecols=['Body', 'Publication Day Of Month', 'Publication Month', 'Publication Year']) main_df = pd.concat([main_df,temp_df], ignore_index=True) # In[4]: # Remove NaN values, lowercase contents of Body column, filters for bush and gore and resets the index print(main_df.shape) main_df.dropna(subset=['Body'], inplace=True) print(main_df.shape) main_df['Body'] = main_df['Body'].str.lower() main_df = main_df[main_df['Body'].str.contains('gore|bush')] main_df = main_df.reset_index(drop=True) # In[5]: # Create a single date column from day, month and year columns main_df['Date'] = pd.to_datetime( main_df['Publication Year'] * 10000 + main_df['Publication Month'] * 100 + main_df['Publication Day Of Month'], format='%Y%m%d') main_df.drop(['Publication Year', 'Publication Month', 'Publication Day Of Month'], axis=1, inplace=True) print(main_df.shape) # In[6]: # Remove unnecessary symbols, numbers, words less than 3 characters and apply lemmatizer main_df['Body'].replace([r'[,\.!?]', r'\d+', r'\b(\w{1,2})\b'], '', inplace=True, regex=True) main_df['Body'].apply(lemma_text) main_df['Body'] = main_df['Body'].str.replace('said', '', regex=False) print(main_df['Body'].head(10)) # In[7]: # Generate doc-term matrix cv = CountVectorizer(stop_words='english', max_df=3500) ft_cv = cv.fit_transform(main_df['Body']) vocabulary = cv.get_feature_names() doc_term_matrix = pd.DataFrame(ft_cv.toarray(), columns=vocabulary) print(doc_term_matrix.shape) # In[25]: # In[27]: from sklearn.utils import check_random_state from sklearn.decomposition._online_lda_fast import _dirichlet_expectation_2d class PTWGuidedLatentDirichletAllocation(LatentDirichletAllocation): def __init__(self, n_components=10, doc_topic_prior=None, topic_word_prior=None, learning_method='batch', learning_decay=0.7, learning_offset=10.0, max_iter=10, batch_size=128, evaluate_every=-1, total_samples=1000000.0, perp_tol=0.1, mean_change_tol=0.001, max_doc_update_iter=100, n_jobs=None, verbose=0, random_state=None, n_topics=None, ptws=None): super(PTWGuidedLatentDirichletAllocation, self).__init__(n_components, doc_topic_prior, topic_word_prior, learning_method, learning_decay, learning_offset, max_iter, batch_size, evaluate_every, total_samples, perp_tol, mean_change_tol, max_doc_update_iter, n_jobs, verbose, random_state, n_topics) self.ptws = ptws def _init_latent_vars(self, n_features): """Initialize latent variables.""" self.random_state_ = check_random_state(self.random_state) self.n_batch_iter_ = 1 self.n_iter_ = 0 if self.doc_topic_prior is None: self.doc_topic_prior_ = 1. / self.n_topics else: self.doc_topic_prior_ = self.doc_topic_prior if self.topic_word_prior is None: self.topic_word_prior_ = 1. / self.n_topics else: self.topic_word_prior_ = self.topic_word_prior init_gamma = 100. init_var = 1. / init_gamma # In the literature, this is called `lambda` self.components_ = self.random_state_.gamma( init_gamma, init_var, (self.n_topics, n_features)) # Transform topic values in matrix for prior topic words if self.ptws is not None: for ptw in self.ptws: word_index = ptw[0] word_topic_values = ptw[1] self.components_[:, word_index] *= word_topic_values # In the literature, this is `exp(E[log(beta)])` self.exp_dirichlet_component_ = np.exp( _dirichlet_expectation_2d(self.components_)) # In[31]: # Fit LDA model to doc-term matrix k = 15 lda = Lda(n_components=k) lda.fit(ft_cv) print('log likelihood score, 15 topics: ' + str(lda.score(ft_cv))) pyLDAvis.enable_notebook() p = pyLDAvis.sklearn.prepare(lda, ft_cv, cv) pyLDAvis.display(p) # In[16]: # Generate doc-topic matrix lda_out = lda.transform(ft_cv) doc_topic_matrix = pd.DataFrame(lda_out) doc_topic_matrix['Date'] = main_df['Date'] print(doc_topic_matrix.shape) aggregator = {i: 'sum' for i in range(k)} coverage_curve = doc_topic_matrix.groupby(['Date']).agg(aggregator) print(coverage_curve.shape) print(coverage_curve.head(10)) plt.rcParams['figure.figsize'] = [16, 10] plt.figure() coverage_curve.plot() plt.show() # In[10]: #Read the IEM data and Normalize one of the stocks iem_data = pd.read_excel('IEM2000.xlsx') iem_data.drop(['Units', '$Volume', 'LowPrice','HighPrice','AvgPrice'], axis=1, inplace=True) dem_data = iem_data[iem_data['Contract'].str.contains('Dem')] rep_data = iem_data[iem_data['Contract'].str.contains('Rep')] dem_data.set_index('Date', inplace=True) rep_data.set_index('Date', inplace=True) dem_data['NormLastPrice'] = dem_data['LastPrice'] / (dem_data['LastPrice'] + rep_data['LastPrice']) dem_data.drop(['LastPrice', 'Contract'], axis=1, inplace=True) print(dem_data.head()) # In[14]: combined_data = pd.concat([dem_data, coverage_curve], axis=1, join='inner') print(combined_data.head()) print(combined_data.tail()) print(pd.date_range(start='2000-05-01',end='2000-11-10').difference(combined_data.index)) # In[12]: from statsmodels.tsa.stattools import grangercausalitytests granger_results1 = grangercausalitytests(combined_data[['NormLastPrice',2]],5) granger_results2 = grangercausalitytests(combined_data[['NormLastPrice',7]],5) granger_results3 = grangercausalitytests(combined_data[['NormLastPrice',10]],5) granger_results4 = grangercausalitytests(combined_data[['NormLastPrice',11]],5) granger_results5 = grangercausalitytests(combined_data[['NormLastPrice',12]],5) # In[ ]:
9914afa82f6f497a41fc30c230dbcf3544a0aa4f
luisniebla/queue
/queue.py
929
3.953125
4
# Create the object type 'queue' class Queue: def __init__(self, n): self.Q = [0] * n self.tail = 0 self.head = 0 self.length = n def enqueue(self, x): self.Q[self.tail] = x if self.tail == self.length: self.tail = 0 else: self.tail += 1 def dequeue(self): x = self.Q[self.head] self.Q[self.head] = 0 if self.head == self.length: self.head = 0 else: self.head += 1 return x # TODO: Remove extra 0s def __str__(self): return print(self.Q) # Move to seperate file if this gets too big def test_queue(): q = Queue(3) assert q.Q == [0,0,0] q.enqueue(1) q.enqueue(2) assert q.Q == [1, 2, 0] q.dequeue() assert q.Q == [0, 2, 0] q.enqueue(3) assert q.Q == [0, 2, 3] if __name__ == '__main__': test_queue()
9da4356c719d0767fe227bc2eb297aa82627fae0
rfcamo/python-challenge
/PyParagraph/main.py
1,042
3.6875
4
# Imports of dependencies import os import re import string # Files to load and output fileload = "raw_data/paragraph_1.txt" # Open and read the txt file with open(fileload) as txtfile: paragraph_txt = txtfile.read() # Count word in the paragraph count_word = len(re.findall(r'\w+', paragraph_txt)) # Count sentence in the paragraph sen_count = len(re.findall(r'\.', paragraph_txt)) # Concatenate ascii to string letters = string.ascii_letters + " " # Paragraph split para_list = paragraph_txt.split() # Variable letter_total = 0 # Loop to the paragrahp for word in para_list: letter_total += len(word) count_word = len(para_list) avg_letter_count = letter_total/count_word words_per_sentence = count_word/sen_count # Output the result output = ( f"Paragraph Analysis\n" f"------------------\n" f"Approximate Word Count: {count_word}\n" f"Approximate Sentence Count: {sen_count}\n" f"Average Letter Count: {round(avg_letter_count, 1)}\n" f"Average Sentence Length: {words_per_sentence}") print(output)
f6e69661f699f5aa0ea96aa261221e98a2893a11
ganlanshu/leetcode
/sliding-window-maximum.py
2,134
3.59375
4
# coding=utf-8 """ 239. Sliding Window Maximum """ import collections class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] 先想到一个简单粗暴的方法 """ if not nums: return [] n = len(nums) res = [] for i in range(n-k+1): res.append(max(nums[i:i+k])) return res def maxSlidingWindow1(self, nums, k): """ :param nums: :param k: :return: 看了提示,用deque来做, 不过时间复杂度并不是O(n) """ if not nums: return [] queue = collections.deque(nums[:k]) res = [] res.append(max(queue)) n = len(nums) for i in range(k, n): queue.popleft() queue.append(nums[i]) res.append(max(queue)) return res def maxSlidingWindow2(self, nums, k): """ :param nums: :param k: :return: 滑动窗口的最大值总是在队列首部,队列里面的数据总是从大到小排列 遍历数组nums,使用deque维护滑动窗口内有可能成为最大值元素的下表 记当前下表为i,则滑动窗口的有效下标范围是[i-k+1,i] 若deque中的元素下标小于 i-k+1,将其从队列头部出队,nums中的元素逐个从 队尾入队 这样确保deque中的元素下标在[i-k+1,i]范围内 当下标i从对位入队是,依次弹出队尾小于等于nums[i]的元素的下标,因为滑动窗口 里面已经有了更大的元素,这些较小的在当前滑动窗口已经没有意义 deque的头元素是当前滑动窗口的最大值 """ dq = collections.deque() ans = [] for i in range(len(nums)): while dq and nums[dq[-1]] <= nums[i]: dq.pop() dq.append(i) if dq[0] == i-k: dq.popleft() if i >= k-1: ans.append(nums[dq[0]]) return ans
56b4c5dfe50189e8febe755465c6ea0837f6e27c
sgrade/pytest
/codeforces/987A.py
394
3.671875
4
# A. Infinity Gauntlet colors = { 'purple': 'Power', 'green': 'Time', 'blue': 'Space', 'orange': 'Soul', 'red': 'Reality', 'yellow': 'Mind' } n = int(input()) present = list() for _ in range(n): present.append(input()) ans = list() for color in colors.keys(): if color not in present: ans.append(colors[color]) print(len(ans)) print('\n'.join(ans))
494711637a4b7f3af7a65de242efecb471c0e280
SmartTech-SD/Chess_Board_in_Turtle_Python
/chess_board_in_Turtle.py
3,441
3.890625
4
# creating a simple chess board # Each row having 8 columns # total 4 column black and 4 column white alternativly import turtle t1=turtle.Turtle() screen=turtle.Screen() screen.bgcolor('blue violet') screen.title('***Chess Board***') t1.hideturtle() t1.penup() t1.goto(-20,200) t1.pendown() t1.color('pink') t1.write("CHESS BOARD",align='center',font=("times new roman",24,"bold")) t1.speed(0) t1.color('black') # chess outer boders def square(): t1.forward(350) t1.right(90) t1.forward(350) t1.right(90) t1.forward(350) t1.right(90) t1.forward(350) # changing the position of turtle t1.penup() t1.goto(-180,180) t1.pendown() t1.pensize(5) square() # pensize for inner boders t1.pensize(3) ### # loop for creating row ##################### for i in range(4): t1.right(90) t1.forward(350/8) ####################### # function for small square in row def small_square(): for j in range(4): t1.begin_fill() t1.fillcolor('white') t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/4) t1.end_fill() # t1.begin_fill() t1.fillcolor('black') t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.penup() t1.forward(350/4) t1.pendown() t1.end_fill() #### small_square() ############################################################### # move to the initial position #################################################################### def initial_position(): t1.penup() t1.right(180) t1.forward(350/8+350) t1.left(90) t1.forward(350/8) t1.left(180) t1.pendown() initial_position() #################################################################### # function for 2nd row square ###################################################################### def small_square2(): t1.right(90) t1.forward(350/8) for k in range(4): t1.begin_fill() t1.fillcolor('black') t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.penup() t1.forward(350/4) t1.pendown() t1.end_fill() # t1.begin_fill() t1.fillcolor('white') t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.forward(350/8) t1.right(90) t1.penup() t1.forward(350/4) t1.pendown() t1.end_fill() small_square2() initial_position() user_input=input('press "y" to continue: ') # for hold the out put screen ################################################################## # finally complited !!!!!!!
e53a199ee7041011103c852b16f22dc1b9bcb6ab
arsamigullin/problem_solving_python
/techniques/monotonous_stack/NLE.py
567
3.984375
4
# this monotonous technique helps to find Next Less Element (PLE) # instead of storing the value itself we will store the index- def find_nle(arr): stack = [] next_less = [-1] * len(arr) for i in range(len(arr)): while len(stack) > 0 and arr[stack[-1]] > arr[i]: next_less[stack.pop()] = i stack.append(i) #The next less element of 7 is 3. #The next less element of 8 is 3. #No next less element of 4 and 3. if __name__ == "__main__": find_nle([3,7,8,4]) # next_less = [-1,3,3,-1] this is an array with indices
d68efac49a2a5ca4c25ca565e1b8ba859fa2b58c
frankbozar/Competitive-Programming
/Barcelona Bootcamp/Day4/C.py
497
3.546875
4
z = int(input()) for _ in range(z): n = int(input()) if n == 1: print('1 1 1 2') elif n == 2: print('1 1 1 2') print('1 3 1 4') print('1 5 1 6') elif n == 3: print('1 1 1 2') print('1 3 1 4') print('2 3 3 3') print('1 5 2 5') print('2 4 3 4') print('4 3 4 4') elif n == 4: print(1,2,1,3) print(1,1,2,1) print(2,2,2,3) print(1,4,2,4) print(4,1,5,1) print(3,1,3,2) print(5,2,5,3) print(4,2,4,3) print(3,3,3,4) print(4,4,5,4) else: print('impossible')
d0a26e5f7f3747afa8f878ae0e08f545a02dcbc1
girish-patil/git-python-programs
/Python_Assessment/Q24.py
502
4.3125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 10 18:52:11 2017 @author: Girish Patil """ #24.Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. #Suppose the following input is supplied to the program: #34,67,55,33,12,98 #Then, the output should be: #['34', '67', '55', '33', '12', '98'] #('34', '67', '55', '33', '12', '98') n = input("Enter Numbers seperated by comma operator:-") print list(n) print tuple(n)
1b1cb110f7e1ca7b29184314bf3ee1a9ba504a29
cody-berry/gravitation
/Repulser.py
889
3.984375
4
from Attractor import * # Repulser is the oppisite of Attractor. class Repulser(Attractor): # We don't need a constructer because if we did, then it would be the exact # same. Python allows us to not contain a constructer if it is the exact # same as the class's constructer that it is 'inheriting' from. def show(self): # The difference here is that we're filling red, not green. fill(0, 100, 100, 75) circle(self.pos.x, self.pos.y, self.r*2) fill(self.c) circle(self.pos.x, self.pos.y, 10) def attract(self, mover): # Repulsing is the opposite of attracting. so we need to call the attract function for # Mover. 'self' needs to be replaced with a mover instance because otherwise Python # would get confused. return -1*Attractor.attract(Mover(self.pos.x, self.pos.y), mover)
3268821cc6c30890b9f9af1a1f3b62f7e1e8cf0d
amaxwong/mbs-3523
/OpenCV-3-webcam.py
615
3.5625
4
# Save this file as OpenCV-3-webcam.py import cv2 #import numpy as np print(cv2.__version__) # you may need to change the number inside () to 0 1 or 2, # depending on which webcam you are using capture = cv2.VideoCapture(0) # Below 2 lines are used to set the webcam window size capture.set(3,640) # 3 is the width of the frame capture.set(4,480) # 4 is the height of the frame # Start capturing and show frames on window named 'Frame' while True: success, img = capture.read() cv2.imshow('Frame', img) if cv2.waitKey(20) & 0xff == ord('q'): break capture.release() cv2.destroyAllWindows()
20659b5366b8b022995348a411331e1fe248fd79
siddeshshewde/Competitive-Programming
/CodeAbbey-Solutions/2. Sum in Loop/Solution.py
119
3.578125
4
def sum(): n = input() a = input() sum = 0 for i in a: sum = sum + i return sum
9e0959065f058dfb117b48fb8ed92cfb3345787e
abixadamj/Abix.Edukacja
/Python101xEDU/klasy.py
2,346
3.984375
4
class Torebka(object): ''' Tego opisu i tak nie widzimy ''' def __init__(self, zawartosc, nazwa='Torebeczka'): ''' Tu __init__ - co podajemy na starcie, czyli: elementy początkowe listy nazwę naszej torebki (Domyślnie: Torebeczka) ''' self.zawartosc_torebki = [] self.ilosc_elementow = 0 self.nazwa_torebki = nazwa for element in zawartosc: self.zawartosc_torebki.append(element) self.ilosc_elementow = len(self.zawartosc_torebki) def dodaj(self,element): ''' dodaj pojedynczy element do listy zwiększa licznik ilości pozycji ''' self.ilosc_elementow += 1 self.zawartosc_torebki.append(element) def pokaz(self): ''' listuje zawartość naszej listy / torebki ''' print('Zawartość torebki o nazwie: '+ self.nazwa_torebki) print('Ilość elementów: '+ str(self.ilosc_elementow)) for elem in self.zawartosc_torebki: print('Element: '+ elem) # definicja klasy z polem, które jest widoczne w klasie, a nie tylko w obiekcie class Torebka2(object): ''' Tego opisu i tak nie widzimy ''' liczba_torebek = 0 def __init__(self, zawartosc, nazwa='Torebeczka'): ''' Tu __init__ - co podajemy na starcie, czyli: elementy początkowe listy nazwę naszej torebki (Domyślnie: Torebeczka) ''' self.zawartosc_torebki = [] self.ilosc_elementow = 0 self.nazwa_torebki = nazwa for element in zawartosc: self.zawartosc_torebki.append(element) self.ilosc_elementow = len(self.zawartosc_torebki) Torebka2.liczba_torebek += 1 def dodaj(self,element): ''' dodaj pojedynczy element do listy zwiększa licznik ilości pozycji ''' self.ilosc_elementow += 1 self.zawartosc_torebki.append(element) def pokaz(self): ''' listuje zawartość naszej listy / torebki ''' print('Zawartość torebki o nazwie: '+ self.nazwa_torebki) print('Ilość elementów: '+ str(self.ilosc_elementow)) for elem in self.zawartosc_torebki: print('Element: '+ elem)
262a6b1b9251c93c17287efe9f58bb9ee4cbc353
xxxhol1c/cs61a-su2021
/hw/hw02/hw02.py
6,235
4.03125
4
from operator import add, mul, sub square = lambda x: x * x identity = lambda x: x triple = lambda x: 3 * x increment = lambda x: x + 1 HW_SOURCE_FILE = __file__ def compose1(func1, func2): """Return a function f, such that f(x) = func1(func2(x)).""" def f(x): return func1(func2(x)) return f def make_repeater(func, n): """Return the function that computes the nth application of func. >>> add_three = make_repeater(increment, 3) >>> add_three(5) 8 >>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1 243 >>> make_repeater(square, 2)(5) # square(square(5)) 625 >>> make_repeater(square, 4)(5) # square(square(square(square(5)))) 152587890625 >>> make_repeater(square, 0)(5) # Yes, it makes sense to apply the function zero times! 5 """ "*** YOUR CODE HERE ***" def f(x): i = 1 res = x while i <= n: res = func(res) i += 1 return res return f def num_eights(pos): """Returns the number of times 8 appears as a digit of pos. >>> num_eights(3) 0 >>> num_eights(8) 1 >>> num_eights(88888888) 8 >>> num_eights(2638) 1 >>> num_eights(86380) 2 >>> num_eights(12345) 0 >>> from construct_check import check >>> # ban all assignment statements >>> check(HW_SOURCE_FILE, 'num_eights', ... ['Assign', 'AugAssign']) True """ "*** YOUR CODE HERE ***" if pos == 0: return 0 if pos % 10 == 8: return 1 + num_eights(pos//10) return num_eights(pos//10) def pingpong(n): """Return the nth element of the ping-pong sequence. >>> pingpong(8) 8 >>> pingpong(10) 6 >>> pingpong(15) 1 >>> pingpong(21) -1 >>> pingpong(22) -2 >>> pingpong(30) -2 >>> pingpong(68) 0 >>> pingpong(69) -1 >>> pingpong(80) 0 >>> pingpong(81) 1 >>> pingpong(82) 0 >>> pingpong(100) -6 >>> from construct_check import check >>> # ban assignment statements >>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign']) True """ "*** YOUR CODE HERE ***" def helper(res,step,index): if index == n: return res elif num_eights(index)>0 or index % 8 == 0: return helper(res-step,-step,index+1) else: return helper(res+step,step,index+1) return helper(1, 1, 1) def missing_digits(n): """Given a number a that is in sorted, increasing order, return the number of missing digits in n. A missing digit is a number between the first and last digit of a that is not in n. >>> missing_digits(1248) # 3, 5, 6, 7 4 >>> missing_digits(19) # 2, 3, 4, 5, 6, 7, 8 7 >>> missing_digits(1122) # No missing numbers 0 >>> missing_digits(123456) # No missing numbers 0 >>> missing_digits(3558) # 4, 6, 7 3 >>> missing_digits(35578) # 4, 6 2 >>> missing_digits(12456) # 3 1 >>> missing_digits(16789) # 2, 3, 4, 5 4 >>> missing_digits(4) # No missing numbers between 4 and 4 0 >>> from construct_check import check >>> # ban while or for loops >>> check(HW_SOURCE_FILE, 'missing_digits', ['While', 'For']) True """ "*** YOUR CODE HERE ***" def helper(rest,digit,count): if rest == 0: return count elif rest % 10 == digit -1 or rest % 10 == digit: return helper(rest//10, rest%10, count) else: return helper(rest, digit -1, count +1) return helper(n//10, n%10,0) def get_next_coin(coin): """Return the next coin. >>> get_next_coin(1) 5 >>> get_next_coin(5) 10 >>> get_next_coin(10) 25 >>> get_next_coin(2) # Other values return None """ if coin == 1: return 5 elif coin == 5: return 10 elif coin == 10: return 25 def count_coins(change): """Return the number of ways to make change using coins of value of 1, 5, 10, 25. >>> count_coins(15) 6 >>> count_coins(10) 4 >>> count_coins(20) 9 >>> count_coins(100) # How many ways to make change for a dollar? 242 >>> from construct_check import check >>> # ban iteration >>> check(HW_SOURCE_FILE, 'count_coins', ['While', 'For']) True """ "*** YOUR CODE HERE ***" def helper (change,coin): if coin == None: return 0 if change < 0: return 0 elif change == 0: return 1 else: return helper(change-coin,coin) + helper(change,get_next_coin(coin)) return helper(change, 1) def zero(f): return lambda x: x def successor(n): return lambda f: lambda x: f(n(f)(x)) def one(f): """Church numeral 1: same as successor(zero)""" "*** YOUR CODE HERE ***" return lambda f: lambda x: f(x) def two(f): """Church numeral 2: same as successor(successor(zero))""" "*** YOUR CODE HERE ***" return lambda f: lambda x: f((f(x))) three = successor(two) def church_to_int(n): """Convert the Church numeral n to a Python integer. >>> church_to_int(zero) 0 >>> church_to_int(one) 1 >>> church_to_int(two) 2 >>> church_to_int(three) 3 """ "*** YOUR CODE HERE ***" return n(lambda x: x+1)(0) def add_church(m, n): """Return the Church numeral for m + n, for Church numerals m and n. >>> church_to_int(add_church(two, three)) 5 """ "*** YOUR CODE HERE ***" return lambda f: lambda x: m(f)(n(f)(x)) def mul_church(m, n): """Return the Church numeral for m * n, for Church numerals m and n. >>> four = successor(three) >>> church_to_int(mul_church(two, three)) 6 >>> church_to_int(mul_church(three, four)) 12 """ "*** YOUR CODE HERE ***" return lambda f: m(n(f)) def pow_church(m, n): """Return the Church numeral m ** n, for Church numerals m and n. >>> church_to_int(pow_church(two, three)) 8 >>> church_to_int(pow_church(three, two)) 9 """ "*** YOUR CODE HERE ***" return n(m)
96cfe827966912ec376b5b30b5431cdce7ce8bdc
gbodeen/algorhythmix
/python/project-euler/PE050.py
1,973
3.71875
4
# -*- coding: utf-8 -*- """ The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes? """ from math import sqrt class PE050: def isPrime(self, n): if n < 2: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(sqrt(n)) + 1, 2): if n % i == 0: return False return True def nextPrime(self, n): if n < 2: return 2 if n == 2: return 3 n += 2 while not self.isPrime(n): n += 2 return n def primeSumOfConsecPrimes(self, max=100): primes = [] p = self.nextPrime(0) primeseq = [] while p < max: primes.append(p) L = 0 R = 1 while R > L and R <= len(primes): seqsum = sum(primes[L:R]) if seqsum == p: if (R - L > len(primeseq)): primeseq = primes[L:R] primesum = p break elif seqsum < p: R += 1 elif seqsum > p: L += 1 else: return -1 p = self.nextPrime(p) return primesum @staticmethod def main(): test = PE050() # p = 0 # for i in range(10): # p = test.nextPrime(p) # print(i, p) print(test.primeSumOfConsecPrimes(10)) # 5, 2: 3 L2 print(test.primeSumOfConsecPrimes(100)) # 41, 2: 13 L6 print(test.primeSumOfConsecPrimes(1000)) # 953, 7: 89 L21 print(test.primeSumOfConsecPrimes(10000)) # 9521, 3: 317 L65 # print(test.primeSumOfConsecPrimes(100000)) # 92951, 3: 1097 L183 # print(test.primeSumOfConsecPrimes(1000000)) # : primesum: 997651, first: 7, len: 543, last: 3931} PE050.main()
9f75514636a3f925dc9bfaa4cde83c0070b69578
LeKillbit/CTF_Writeups
/tenable/hackers_manifesto/solve.py
1,388
3.5
4
#!/usr/bin/env python3 data = open("hacker_manifesto.txt", "rb").read() def reset_chunk(c): ret = b"" ret += b"\x00" ret += b"\x00" ret += bytes([c[2]]) return ret def insert(chunks, idx, offset, length): ret = [] if length & 1 != 0: offset += 256 if (length >> 1) & 1 != 0: offset += 512 to_add = chunks[idx-offset:idx-offset+length//4] if to_add != b"": chunks = chunks[:idx] + to_add + [reset_chunk(chunks[idx])] + chunks[idx+1:] return chunks def chunking(data): chunks = [] for i in range(0, len(data), 3): chunks.append(bytes([data[i], data[i+1], data[i+2]])) return chunks def decoding_complete(chunks): for chunk in chunks: offset = chunk[0] length = chunk[1] char = chunk[2] if offset != 0 or length != 0: return False return True def decode(data): ret = b"" chunks = chunking(data) while not decoding_complete(chunks): for i in range(len(chunks)): offset = chunks[i][0] length = chunks[i][1] char = chunks[i][2] if offset != 0 or length != 0: chunks = insert(chunks, i, offset, length) ret = b"".join(chunks).replace(b"\x00\x00",b"") break return ret ret = decode(data) print(ret.decode())
f8158eb850b6cc95afcfceed63b7e034b7a48223
WILLIDIO/ExercicioPython
/exercicio9.py
423
3.921875
4
# -*- coding: utf-8 -*- print("Faça um Programa que leia um vetor A com 10 números inteiros,") print("calcule e mostre a soma dos quadrados dos elementos do vetor.") print() vetorA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] vetorB = [] print("Vetor A: ", vetorA) for i in vetorA: i = i ** 2 vetorB.append(i) print("Vetor B", vetorB) soma = 0 for i in vetorB: soma = soma + i print("Soma dos quadrados: ", soma)
a5b4cb7eedfa1b1ba9859199231060b755f9849a
bhavya152002/dice-project-python-
/with2dice.py
369
4
4
import random import time roll = "yes" while roll == "yes": print("rolling the dice----") time.sleep(1) dice1 = random.randint(1, 6) dice2 = random.randint(1, 6) print("the values are : ") print("Dice 1 = ",dice1,"\nDice 2 = ", dice2) choice = input("Do you want to roll the dice again? (y/n)") if choice.lower == "n": break
83ecf08838e13e9913f3e2702bcf3659e2301fae
akanksha007/CTCI
/linked_list/linked_list.py
1,069
4.03125
4
class Node: def __init__(self, data, address): self.data = data self.address = address def getNextNode(self): return self.address class LinkedList: def __init__(self, head = None): self.head = head def addNode(self, data): newNode = Node(data, self.head) self.head = newNode return True def printLinkList(self): current = self.head while current: print(current.data) current = current.getNextNode() def removeNode(self, data): current = self.head previous = None while current: if current.data == data: if previous: previous.address = current.address else: self.head = current.getNextNode() previous = current current = current.getNextNode() l = LinkedList() print(l.addNode(5)) print(l.addNode(10)) print(l.addNode(15)) print(l.addNode(20)) l.printLinkList() print(l.removeNode(15)) l.printLinkList()
873e37c5edf4accdbfb3fd0b524cfe7c6d58ed1d
Peytonlb/comp110-21f-workspace
/exercises/ex01/hype_machine.py
293
3.546875
4
"""Hype Machine: Series of Hype Messages.""" __author__ = "730309987" name: str = input("What is your name? ") print("You are going to have a great day " + str(name)) print(str(name) + ", you are going to crush it today!") print("You know it, " + str(name) + ", today will be the best day!")
61ac5e9699fb201bc53748f53d69e8c03626d059
enerhy/Udemy_Features
/Feature_Enigneering.py
32,225
3.78125
4
------FEATURE ENGINEERING STEPS ---1. Analyse variable types and values and characteristics # Data types - # make list of variables types data.dtypes # numerical: discrete vs continuous - SELECTION discrete = [var for var in data.columns if data[var].dtype!='O' and var!='survived' and data[var].nunique()<10] #OR ''''for var in numerical: if len(data[var].unique()) < 20 and var not in year_vars: print(var, ' values: ', data[var].unique()) discrete.append(var) print() print('There are {} discrete variables'.format(len(discrete)))'''' continuous = [var for var in data.columns if data[var].dtype!='O' and var!='survived' and var not in discrete] #OR '''numerical = [var for var in numerical if var not in discrete and var not in [ 'Id', 'SalePrice'] and var not in year_vars] print('There are {} numerical and continuous variables'.format(len(numerical)))''' # mixed mixed = ['cabin'] # categorical categorical = [var for var in data.columns if data[var].dtype=='O' and var not in mixed] # Missing Data data.isnull().mean() # Cardinality data[categorical+mixed].nunique() # Outliers data[continuous].boxplot(figsize=(10,4)) # outliers in discrete data[discrete].boxplot(figsize=(10,4)) # feature magnitude data.describe() # Separating mixed values data['cabin_num'] = data['cabin'].str.extract('(\d+)') # captures numerical part data['cabin_num'] = data['cabin_num'].astype('float') data['cabin_cat'] = data['cabin'].str[0] # captures the first letter # show dataframe data.head() # drop original mixed data.drop(['cabin'], axis=1, inplace=True) -----HERE SPLITTING IN TRAIN AND TEST # MIssing Data # numerical X_train.select_dtypes(exclude='O').isnull().mean() # categorical X_train.select_dtypes(include='O').isnull().mean() # Cardinality and rare labels # check cardinality again X_train[['cabin_cat', 'sex', 'embarked']].nunique() # check variable frequency var = 'cabin_cat' (X_train[var].value_counts() / len(X_train)).sort_values() # Variables Distribution X_train.select_dtypes(exclude='O').hist(bins=30, figsize=(8,8)) plt.show() ---2. BUILDING THE PIPLINE titanic_pipe = Pipeline([ # missing data imputation - section 4 ('imputer_num', mdi.ArbitraryNumberImputer(arbitrary_number=-1, variables=['age', 'fare', 'cabin_num'])), ('imputer_cat', mdi.CategoricalVariableImputer(variables=['embarked', 'cabin_cat'])), # categorical encoding - section 6 ('encoder_rare_label', ce.RareLabelCategoricalEncoder(tol=0.01, n_categories=6, variables=['cabin_cat'])), ('categorical_encoder', ce.OrdinalCategoricalEncoder(encoding_method='ordered', variables=['cabin_cat', 'sex', 'embarked'])), # Gradient Boosted machine ('gbm', GradientBoostingClassifier(random_state=0)) ]) # let's fit the pipeline and make predictions titanic_pipe.fit(X_train, y_train) X_train_preds = titanic_pipe.predict_proba(X_train)[:,1] X_test_preds = titanic_pipe.predict_proba(X_test)[:,1] # let's explore the importance of the features importance = pd.Series(titanic_pipe.named_steps['gbm'].feature_importances_) importance.index = data.drop('survived', axis=1).columns importance.sort_values(inplace=True, ascending=False) importance.plot.bar(figsize=(12,6)) --USING GRIDSEARCH IN THE PIPELINE param_grid = { # try different feature engineering parameters 'imputer_num__arbitrary_number': [-1, 99], 'encoder_rare_label__tol': [0.1, 0.2], 'categorical_encoder__encoding_method': ['ordered', 'arbitrary'], # try different gradient boosted tree model paramenters 'gbm__max_depth': [None, 1, 3], } # now we set up the grid search with cross-validation grid_search = GridSearchCV(titanic_pipe, param_grid, cv=5, iid=False, n_jobs=-1, scoring='roc_auc') # and now we train over all the possible combinations of the parameters above grid_search.fit(X_train, y_train) # and we print the best score over the train set print(("best roc-auc from grid search: %.3f" % grid_search.score(X_train, y_train))) # we can print the best estimator parameters like this grid_search.best_estimator_ # and find the best fit parameters like this grid_search.best_params_ # here we can see all the combinations evaluated during the gridsearch grid_search.cv_results_['params'] # and here the scores for each of one of the above combinations grid_search.cv_results_['mean_test_score'] print(("best linear regression from grid search: %.3f" % grid_search.score(X_test, y_test))) # Introducing nan values, where another sign indicates that data = data.replace('?', np.nan) # 2 values in one cell - splitting def get_first_cabin(row): try: return row.split()[0] except: return np.nan data['cabin'] = data['cabin'].apply(get_first_cabin) # Use only some columns of a dataset data = pd.read_csv('../loan.csv', usecols=use_cols).sample( 10000, random_state=44) -----# Date Time Variables data.dtypes # now let's parse the dates, currently coded as strings, into datetime format data['issue_dt'] = pd.to_datetime(data.issue_d) data['last_pymnt_dt'] = pd.to_datetime(data.last_pymnt_d) data[['issue_d', 'issue_dt', 'last_pymnt_d', 'last_pymnt_dt']].head() # Extracting week of year from date, varies from 1 to 52 data['issue_dt_week'] = data['issue_dt'].dt.week # Extracting month from date - 1 to 12 data['issue_dt_month'] = data['issue_dt'].dt.month # Extract quarter from date variable - 1 to 4 data['issue_dt_quarter'] = data['issue_dt'].dt.quarter # extract year data['issue_dt_year'] = data['issue_dt'].dt.year # we can extract the day in different formats # day of the week - name data['issue_dt_dayofweek'] = data['issue_dt'].dt.weekday_name # was the application done on the weekend? data['issue_dt_is_weekend'] = np.where(data['issue_dt_dayofweek'].isin(['Sunday', 'Saturday']), 1,0) # Extract the time elapsed data['issue_dt'] - data['last_pymnt_dt'] (data['last_pymnt_dt'] - data['issue_dt']).dt.days.head() # or the time difference to today (datetime.datetime.today() - data['issue_dt']).head() # calculate number of months passed between 2 dates data['months_passed'] = (data['last_pymnt_dt'] - data['issue_dt']) / np.timedelta64(1, 'M') data['months_passed'] = np.round(data['months_passed'],0) #Pivot into a DataFrame data.groupby(['issue_dt', 'grade'])['loan_amnt'].sum().unstack() ----MISSING DATA data.isnull().sum() data.isnull().mean() data.emp_length.value_counts() / len(data) #to find other sorts of indication for missing data (e.g ?) #Print features with missing values # examine percentage of missing values for col in numerical+year_vars: if X_train[col].isnull().mean() > 0: print(col, X_train[col].isnull().mean()) #List of features containing empty values missing_values = [var for var in df.columns if df[var].isnull().sum() > 0] # Building an indicator matrix for the train set missing_matrix_X_train = X_train[missing_values].isnull().astype(int).add_suffix('_indicator') # Check for Missing Data Not At Random (MNAR) - systematic missing data # creating a binary variable indicating whether a value is missing data['cabin_null'] = np.where(data['cabin'].isnull(), 1, 0) # evaluate % of missing data in the target classes data.groupby(['survived'])['cabin_null'].mean() # Dict with categories to change column valaues length_dict = {k: '0-10 years' for k in data.emp_length.unique()} length_dict['10+ years'] = '10+ years' length_dict['n/a'] = 'n/a' # Mapping data['emp_length_redefined'] = data.emp_length.map(length_dict # Subset of data whith no nan in a certain coulumn data.(subset=['emp_title']) employed = len(data.dropna(subset=['emp_title'])) # % of borrowers within each category data.dropna(subset=['emp_title']).groupby( ['emp_length_redefined'])['emp_length'].count().sort_values() / employe /-------------------------- ) ------- Imputation for Missing values # these are the objects we need to impute missing data # with sklearn from sklearn.impute import SimpleImputer from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline # first we need to make lists, indicating which features # will be imputed with each method numeric_features_mean = ['LotFrontage'] numeric_features_median = ['MasVnrArea', 'GarageYrBlt'] # Instantiating the imputers within a pipeline numeric_mean_imputer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='mean')), ]) numeric_median_imputer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ]) # Use ColumnTransformer # remainder = True to indicate that we want all columns at the end of the # transformation preprocessor = ColumnTransformer(transformers=[ ('mean_imputer', numeric_mean_imputer, numeric_features_mean), ('median_imputer', numeric_median_imputer, numeric_features_median) ], remainder='passthrough') # now we fit the preprocessor preprocessor.fit(X_train) # and now we can impute the data X_train = preprocessor.transform(X_train) # Transform into a DataFrame # IF we used all features in the transformer: X_train_droped_1 = pd.DataFrame(X_train_droped, columns=categorical_dropped+continuous+discrete) X_test_droped_1 = pd.DataFrame(X_test_droped, columns=categorical_dropped+continuous+discrete) # To set in the initial Order X_train_droped_2 = X_train_droped_1[columns_after_dropping] # If only some features were in the transformer: #get the reminding coulmbs: preprocessor.transformers_ #put them into a list and concatinate with the other columns remainder_cols = [cols_to_use[c] for c in [0, 1, 2, 3, 4, 5]] pd.DataFrame(X_train, columns = numeric_features_mean+numeric_features_median+remainder_cols).head() # and we can look at the parameters learnt like this: preprocessor.named_transformers_['mean_imputer'].named_steps['imputer'].statistics_ preprocessor.transformers ---------------CATEGORICAL VARIABLES------------ # Identification # plot number of categories per categorical variable data[categorical].nunique().plot.bar(figsize=(10,6)) plt.title('CARDINALITY: Number of categories in categorical variables') plt.xlabel('Categorical variables') plt.ylabel('Number of different categories') #Explore original relationship between categorical variables and target for var in ['Neighborhood', 'Exterior1st', 'Exterior2nd']: fig = plt.figure() fig = X_train.groupby([var])['SalePrice'].mean().plot() fig.set_title('Relationship between {} and SalePrice'.format(var)) fig.set_ylabel('Mean SalePrice') plt.show() -----ONE-HOT-Encoding # Trees do not perform well in datasets with big feature spaces. # Thus One-Hot-Encoding is not the best option for them #Scikit Learn - it transforms it into array without labels # we create and train the encoder encoder = OneHotEncoder(categories='auto', drop='first', # to return k-1, use drop=false to return k dummies sparse=False, handle_unknown='ignore') # helps deal with rare labels encoder.fit(X_train.fillna('Missing')) # With Get-Dumies: If the test set is not with the same categories - this will be a problem def get_OHE(df): df_OHE = pd.concat( [df[['pclass', 'age', 'sibsp', 'parch', 'fare']], pd.get_dummies(df[['sex', 'cabin', 'embarked']], drop_first=True)], axis=1) return df_OHE X_train_OHE = get_OHE(X_train) X_test_OHE = get_OHE(X_test) X_train_OHE.head() #One hot encoding with Feature-Engine ohe_enc = OneHotCategoricalEncoder( top_categories=None, # we can choose to encode only top categories and see them with ohe_enc.encoder_dict variables=['sex', 'embarked'], # we can select which variables to encode, or not include the argument to select all drop_last=True) # to return k-1, false to return k ohe_enc.fit(X_train) tmp = ohe_enc.transform(X_test) ohe_enc.variables # returns the variable that will be encoded -----Ordinal encoding is suitable for Tree based models # for integer encoding using sklearn from sklearn.preprocessing import LabelEncoder from collections import defaultdict d = defaultdict(LabelEncoder) # Encoding the variable train_transformed = X_train.apply(lambda x: d[x.name].fit_transform(x)) # # Using the dictionary to encode future data test_transformed = X_test.apply(lambda x: d[x.name].transform(x)) #OR to apply on a certain variables test_transformed = X_test[['variable_names']].apply(lambda x: d[x.name].transform(x)) # # Inverse the encoded tmp = train_transformed.apply(lambda x: d[x.name].inverse_transform(x)) tmp.head() --WITH Feature-Engine # for integer encoding using feature-engine from feature_engine.categorical_encoders import OrdinalCategoricalEncoder ordinal_enc = OrdinalCategoricalEncoder( encoding_method='arbitrary', variables=['Neighborhood', 'Exterior1st', 'Exterior2nd']) ordinal_enc.fit(X_train) # check the mapping ordinal_enc.encoder_dict_ ordinal_enc.variables X_train = ordinal_enc.transform(X_train) X_test = ordinal_enc.transform(X_test) --------Count/ Frequency encoding # suitable for Tree based models # - cannot handle new categories in the test set # - two categories will be replaced with the same number if appear equaly -------Ordered Integer Encoding # Suitable also for linear models # - cannot handle new categories def find_category_mappings(df, variable, target): # first we generate an ordered list with the labels ordered_labels = X_train.groupby([variable ])[target].mean().sort_values().index #---IF Y is already separated of X # ordered_labels=pd.concat((X_train_droped, y_train), axis=1).groupby([var # ])[target].mean().sort_values().index # return the dictionary with mappings return {k: i for i, k in enumerate(ordered_labels, 0)} def integer_encode(train, test, variable, ordinal_mapping): X_train[variable] = X_train[variable].map(ordinal_mapping) X_test[variable] = X_test[variable].map(ordinal_mapping) # and now we run a loop over the remaining categorical variables for variable in ['Exterior1st', 'Exterior2nd']: mappings = find_category_mappings(X_train, variable, 'SalePrice') integer_encode(X_train, X_test, variable, mappings) --# WITH Feature-Engine ordinal_enc = OrdinalCategoricalEncoder( # NOTE that we indicate ordered in the encoding_method, otherwise it assings numbers arbitrarily encoding_method='ordered', variables=['Neighborhood', 'Exterior1st', 'Exterior2nd']) ordinal_enc.fit(X_train, y_train) X_train = ordinal_enc.transform(X_train) X_test = ordinal_enc.transform(X_test) ordinal_enc.encoder_dict_ ordinal_enc.variables ----------Encoding with Mean-Encoding #Replacing categorical labels with this code and method will generate missing values #for categories present in the test set that were not seen in the training set. #Therefore it is extremely important to handle rare labels before-hand def find_category_mappings(df, variable, target): return df.groupby([variable])[target].mean().to_dict() def integer_encode(train, test, variable, ordinal_mapping): X_train[variable] = X_train[variable].map(ordinal_mapping) X_test[variable] = X_test[variable].map(ordinal_mapping) for variable in ['sex', 'embarked']: mappings = find_category_mappings(X_train, variable, 'survived') integer_encode(X_train, X_test, variable, mappings) -- #With Feature-Engine from feature_engine.categorical_encoders import MeanCategoricalEncoder mean_enc = MeanCategoricalEncoder( variables=['cabin', 'sex', 'embarked']) mean_enc.fit(X_train, y_train) X_train = mean_enc.transform(X_train) X_test = mean_enc.transform(X_test) mean_enc.encoder_dict_ mean_enc.variables - ---------Probability Ration Encoding # Only for binary classification problems #Replacing categorical labels with this code and method will generate missing values #for categories present in the test set that were not seen in the training set. #Therefore it is extremely important to handle rare labels before-hand ratio_enc = WoERatioCategoricalEncoder( encoding_method = 'ratio', variables=['cabin', 'sex', 'embarked']) ratio_enc.fit(X_train, y_train) X_train = ratio_enc.transform(X_train) X_test = ratio_enc.transform(X_test) --------------RARE LABELS--------- # Check for rare labels for col in cols: print(X_train .groupby(col)[col].count() / len(X_train)) # frequency print() #OR multi_cat_cols = [] for col in X_train.columns: if X_train[col].dtypes =='O': # if variable is categorical if X_train[col].nunique() > 10: # and has more than 10 categories multi_cat_cols.append(col) # add to the list print(X_train.groupby(col)[col].count()/ len(X_train)) # and print the percentage of observations within each category print() # Visualise Example total_houses = len(df) # for each categorical variable for col in categorical: # count the number of houses per category # and divide by total houses # aka percentage of houses per category temp_df = pd.Series(df[col].value_counts() / total_houses) # make plot with the above percentages fig = temp_df.sort_values(ascending=False).plot.bar() fig.set_xlabel(col) # add a line at 5 % to flag the threshold for rare categories fig.axhline(y=0.05, color='red') fig.set_ylabel('Percentage of houses') plt.show() # Checking non-visual for col in cols: print(X_train.groupby(col)[col].count() / len(X_train)) # frequency print() --Regrouping -# With Pandas def find_non_rare_labels(df, variable, tolerance): temp = df.groupby([variable])[variable].count() / len(df) non_rare = [x for x in temp.loc[temp>tolerance].index.values] return non_rare # non-rare Labels find_non_rare_labels(X_train, 'Neighborhood', 0.05) # rare labels [x for x in X_train['Neighborhood'].unique( ) if x not in find_non_rare_labels(X_train, 'Neighborhood', 0.05)] #### def rare_encoding(X_train, X_test, variable, tolerance): X_train = X_train.copy() X_test = X_test.copy() # find the most frequent category frequent_cat = find_non_rare_labels(X_train, variable, tolerance) # re-group rare labels X_train[variable] = np.where(X_train[variable].isin( frequent_cat), X_train[variable], 'Rare') X_test[variable] = np.where(X_test[variable].isin( frequent_cat), X_test[variable], 'Rare') return X_train, X_test # Transforming for variable in ['Neighborhood', 'Exterior1st', 'Exterior2nd']: X_train, X_test = rare_encoding(X_train, X_test, variable, 0.05) -# With Feature-Engine # Rare value encoder rare_encoder = RareLabelCategoricalEncoder( tol=0.05, # minimal percentage to be considered non-rare n_categories=4, # minimal number of categories the variable should have to re-cgroup rare categories variables=['Neighborhood', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'ExterQual', 'BsmtCond'] # variables to re-group ) ----OUTLIERS # let's make boxplots to visualise outliers in the continuous variables # and histograms to get an idea of the distribution for var in numerical: plt.figure(figsize=(6,4)) plt.subplot(1, 2, 1) fig = data.boxplot(column=var) fig.set_title('') fig.set_ylabel(var) plt.subplot(1, 2, 2) fig = data[var].hist(bins=20) fig.set_ylabel('Number of houses') fig.set_xlabel(var) plt.show() # OR # function to create histogram, Q-Q plot and # boxplot def diagnostic_plots(df, variable): # function takes a dataframe (df) and # the variable of interest as arguments # define figure size plt.figure(figsize=(16, 4)) # histogram plt.subplot(1, 3, 1) sns.distplot(df[variable], bins=30) plt.title('Histogram') # Q-Q plot plt.subplot(1, 3, 2) stats.probplot(df[variable], dist="norm", plot=pylab) plt.ylabel('RM quantiles') # boxplot plt.subplot(1, 3, 3) sns.boxplot(y=df[variable]) plt.title('Boxplot') plt.show() # outlies in discrete variables for var in discrete: (data.groupby(var)[var].count() / np.float(len(data))).plot.bar() plt.ylabel('Percentage of observations per label') plt.title(var) plt.show() #OUTLIERS DETECTION # function to find upper and lower boundaries for normally distributed variables def find_normal_boundaries(df, variable): # calculate the boundaries outside which sit the outliers # for a Gaussian distribution upper_boundary = df[variable].mean() + 3 * df[variable].std() lower_boundary = df[variable].mean() - 3 * df[variable].std() return upper_boundary, lower_boundary # For skewed variables def find_skewed_boundaries(df, variable, distance): # Let's calculate the boundaries outside which sit the outliers # for skewed distributions # distance passed as an argument, gives us the option to # estimate 1.5 times or 3 times the IQR to calculate # the boundaries. IQR = df[variable].quantile(0.75) - df[variable].quantile(0.25) lower_boundary = df[variable].quantile(0.25) - (IQR * distance) upper_boundary = df[variable].quantile(0.75) + (IQR * distance) return upper_boundary, lower_boundary upper_boundary, lower_boundary = find_skewed_boundaries(boston, 'LSTAT', 1.5) upper_boundary, lower_boundary # Capping Quantiles def find_boundaries(df, variable): # the boundaries are the quantiles lower_boundary = df[variable].quantile(0.05) upper_boundary = df[variable].quantile(0.95) return upper_boundary, lower_boundary # Printing the outliers for var in df[continuous]: # define figure size print('For feature: ' + str(var)) print('total: {}'.format(len(df))) upper_boundary, lower_boundary = find_skewed_boundaries(df, var, 1.5) print('over the upper bound: {}'.format( round(len(df[df[var] > upper_boundary])/len(df), 2))) print() print('under the lower bound: {}'.format( round(len(df[df[var] < lower_boundary])/len(df), 2))) # CAPPING oston['RM']= np.where(boston['RM'] > RM_upper_limit, RM_upper_limit, np.where(boston['RM'] < RM_lower_limit, RM_lower_limit, boston['RM'])) #My function for var in df[continuous]: # define figure size print('For feature: ' + str(var)) print('total: {}'.format(len(df))) upper_boundary, lower_boundary = find_skewed_boundaries(df, var, 1.5) print('over the upper bound: {}'.format( round(len(df[df[var] > upper_boundary])/len(df), 2))) print() print('under the lower bound: {}'.format( round(len(df[df[var] < lower_boundary])/len(df), 2))) df[var]= np.where(df[var] > upper_boundary, upper_boundary, np.where(df[var] < lower_boundary, lower_boundary, df[var])) ---# Transforming for variable in ['Neighborhood', 'Exterior1st', 'Exterior2nd']: X_train, X_test = rare_encoding(X_train, X_test, variable, 0.05) ---With Feature-Engine from feature_engine.categorical_encoders import RareLabelCategoricalEncoder # Rare value encoder rare_encoder = RareLabelCategoricalEncoder( tol=0.05, # minimal percentage to be considered non-rare n_categories=4, # minimal number of categories the variable should have to re-cgroup rare categories variables=['Neighborhood', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'ExterQual', 'BsmtCond'] # variables to re-group ) rare_encoder.fit(X_train) X_train = rare_encoder.transform(X_train) X_test = rare_encoder.transform(X_test) rare_encoder.variables # the encoder_dict_ is a dictionary of variable: frequent labels pair rare_encoder.encoder_dict_ ----------DISCRETISATION--------- ----Equal width discretisation # with Scikit Learn from sklearn.preprocessing import KBinsDiscretizer disc = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform') disc.fit(X_train[['age', 'fare']]) train_t = disc.transform(X_train[['age', 'fare']]) train_t = pd.DataFrame(train_t, columns = ['age', 'fare']) test_t = disc.transform(X_test[['age', 'fare']]) test_t = pd.DataFrame(test_t, columns = ['age', 'fare']) #Visualisation t1 = train_t.groupby(['age'])['age'].count() / len(train_t) t2 = test_t.groupby(['age'])['age'].count() / len(test_t) tmp = pd.concat([t1, t2], axis=1) tmp.columns = ['train', 'test'] tmp.plot.bar() plt.xticks(rotation=0) plt.ylabel('Number of observations per bin') ##### ---#with Feature-Engine disc = EqualWidthDiscretiser(bins=10, variables = ['age', 'fare']) disc.fit(X_train) train_t = disc.transform(X_train) test_t = disc.transform(X_test) -----Equal-Frequencz discrtisation --#with Feature-Engine disc = EqualFrequencyDiscretiser(q=10, variables = ['age', 'fare']) disc.fit(X_train) train_t = disc.transform(X_train) test_t = disc.transform(X_test) disc.binner_dict_ --#witg Scikit Learn disc = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='quantile') disc.fit(X_train[['age', 'fare']]) train_t = disc.transform(X_train[['age', 'fare']]) train_t = pd.DataFrame(train_t, columns = ['age', 'fare']) disc.bin_edges_ ----K-means discretisation # - outliers may influence the centroid # good to combine with categorical encoding from sklearn.preprocessing import KBinsDiscretizer disc = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='kmeans') disc.fit(X_train[['age', 'fare']]) train_t = disc.transform(X_train[['age', 'fare']]) train_t = pd.DataFrame(train_t, columns = ['age', 'fare']) train_t.head() disc.bin_edges_ ----Monotonic Encoding with discretisation # set up the equal frequency discretiser # to encode variables we need them returned as objects for feature-engine disc = EqualFrequencyDiscretiser( q=10, variables=['age', 'fare'], return_object=True) # find the intervals disc.fit(X_train) # transform train and text train_t = disc.transform(X_train) test_t = disc.transform(X_test) #Ordinal encoding enc = OrdinalCategoricalEncoder(encoding_method = 'ordered') enc.fit(train_t, y_train) train_t = enc.transform(train_t) test_t = enc.transform(test_t) -----Descision Tree for discretisation # - potentially leads to overfittng the feature --#With ScikitLearn tree_model = DecisionTreeClassifier(max_depth=3) tree_model.fit(X_train['age'].to_frame(), y_train) X_train['Age_tree'] = tree_model.predict_proba(X_train['age'].to_frame())[:,1] X_train['Age_tree'].unique() # let's see the Age limits buckets generated by the tree # by capturing the minimum and maximum age per each probability bucket, # we get an idea of the bucket cut-offs pd.concat( [X_train.groupby(['Age_tree'])['age'].min(), X_train.groupby(['Age_tree'])['age'].max()], axis=1) X_test['Age_tree'] = tree_model.predict_proba(X_test['age'].to_frame())[:,1] # monotonic relationship with target pd.concat([X_test, y_test], axis=1).groupby(['Age_tree'])['survived'].mean().plot() plt.title('Monotonic relationship between discretised Age and target') plt.ylabel('Survived') #Testing out different parameters # Build trees of different depths, and calculate the roc-auc of each tree # choose the depth that generates the best roc-auc score_ls = [] # here we store the roc auc score_std_ls = [] # here we store the standard deviation of the roc_auc for tree_depth in [1, 2, 3, 4]: # call the model tree_model = DecisionTreeClassifier(max_depth=tree_depth) # train the model using 3 fold cross validation scores = cross_val_score( tree_model, X_train['age'].to_frame(), y_train, cv=3, scoring='roc_auc') # save the parameters score_ls.append(np.mean(scores)) score_std_ls.append(np.std(scores)) # capture the parameters in a dataframe temp = pd.concat([pd.Series([1, 2, 3, 4]), pd.Series( score_ls), pd.Series(score_std_ls)], axis=1) temp.columns = ['depth', 'roc_auc_mean', 'roc_auc_std'] temp ---#With Feature-Engine treeDisc = DecisionTreeDiscretiser(cv=10, scoring='accuracy', variables=['age', 'fare'], regression=False, param_grid={'max_depth': [1, 2, 3], 'min_samples_leaf':[10,4]}) treeDisc.fit(X_train, y_train) # we can inspect the best params treeDisc.binner_dict_['age'].best_params_ treeDisc.scores_dict_['age'] # and the score treeDisc.scores_dict_['fare'] train_t = treeDisc.transform(X_train) test_t = treeDisc.transform(X_test) ------Scalling 1. Standardisation # - sensitive to outliers 2. Mean Normalisation # - sensitive to outliers 3. MinMaxScaller # Mean and Variance varies - not set ------MIXES VARIABLES # Numeric and categorical 1. Values are eigther numbers or strings # extract numerical part data['open_il_24m_numerical'] = pd.to_numeric(data["open_il_24m"], errors='coerce', downcast='integer') # extract categorical part data['open_il_24m_categorical'] = np.where(data['open_il_24m_numerical'].isnull(), data['open_il_24m'], np.nan) 2: the observations of the variable contain numbers and strings # let's extract the numerical and categorical part for cabin data['cabin_num'] = data['cabin'].str.extract('(\d+)') # captures numerical part data['cabin_cat'] = data['cabin'].str[0] # captures the first letter OR # extract the last bit of ticket as number data['ticket_num'] = data['ticket'].apply(lambda s: s.split()[-1]) data['ticket_num'] = pd.to_numeric(data['ticket_num'], errors='coerce', downcast='integer') # extract the first part of ticket as category data['ticket_cat'] = data['ticket'].apply(lambda s: s.split()[0]) data['ticket_cat'] = np.where(data['ticket_cat'].str.isdigit(), np.nan, data['ticket_cat']) # Capture variables that contains certain Characters / Letters # list of variables that contain year information year_vars = [var for var in numerical if 'Yr' in var or 'Year' in var] # function to calculate elapsed time def elapsed_years(df, var): # capture difference between year variable and # year the house was sold df[var] = df['YrSold'] - df[var] return df for var in ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt']: X_train = elapsed_years(X_train, var) X_test = elapsed_years(X_test, var) -------Logaritimic Transformation from sklearn.preprocessing import FunctionTransformer, PowerTransformer import scipy.stats as stats # Diagnostic # plot the histograms to have a quick look at the variable distribution # histogram and Q-Q plots def diagnostic_plots(df, variable): # function to plot a histogram and a Q-Q plot # side by side, for a certain variable plt.figure(figsize=(15,6)) plt.subplot(1, 2, 1) df[variable].hist(bins=30) plt.subplot(1, 2, 2) stats.probplot(df[variable], dist="norm", plot=plt) plt.show() #Then: # create a log transformer transformer = FunctionTransformer(np.log, validate=True) continuous_positive = [] for var in continuous_noId: if X_train[var].min()>0: if var not a = X_train[var].min() continuous_positive.append(var) print(continuous_positive) X_train_loged = transformer.transform(X_train[continuous_positive]) X_test_loged = transformer.transform(X_test[continuous_positive]) X_train_loged = pd.DataFrame(X_train_loged, columns=continuous_positive) X_test_loged = pd.DataFrame(X_test_loged, columns=continuous_positive) X_train.drop(columns=continuous_positive, inplace=True) #And for X_test as well X_train = pd.concat((X_train, X_train_loged), axis=1) X_test = pd.concat((X_test, X_test_loged), axis=1)
c8e59885ff7db47dbeeaca811f004baf823c1d57
ArisQ/learn-python
/37_collections.py
616
3.828125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import namedtuple, deque, defaultdict, OrderedDict, Counter Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(Point) print(p) print(p.x) print(p.y) q = deque(['a', 'b', 'c']) print(q) q.pop() q.popleft() q.append('x') q.appendleft('y') print(q) dd = defaultdict(lambda: 'N/A') dd['key1'] = 'abc' print(dd) print(dd['key1']) print(dd['key2']) od = OrderedDict() od['z'] = 1 od['y'] = 2 od['x'] = 3 print(od) print(od.keys()) for k, v in od.items(): print(k, v) c = Counter() for ch in 'programming': c[ch] = c[ch] + 1 print(c)
22167717430fd40100e859cd14ae752ab689730d
chenenfeng/lt
/35. Search Insert Position.py
1,229
3.953125
4
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. """ # my program seems low efficient, a lot of if determine which position the target should insert class Solution: def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if nums[0] > target: return 0 for i in range(len(nums)): if nums[i] == target: return i if i == len(nums)-1: return i+1 if nums[i] < target: if nums[i+1] > target: return i+1 # look at this one, share a high efficient solve way # https://leetcode.com/problems/search-insert-position/discuss/165424/Super-simple-Python-20ms-100 """ my thought is imprisoned.. I should have think once I found the first one bigger than target, then insert target who cares the previous one, it definetly smaller than target because I just find the first bigger one, just insert if no found, just insert target to the last one """
c2ca1cfa85d26dfb6fa4ca0518fbcbe951d1ccdf
decretist/Delta
/burrows/burrows.py
3,932
3.5
4
#!/usr/local/bin/python3 # Paul Evans (10evans@cua.edu) # 11-14 March 2020 import itertools import math import statistics import sys sys.path.append('..') import utility as u def main(): ''' Assemble a large corpus made up of texts written by an arbitrary number of authors; let’s say that number of authors is x. ''' test = 'cases' # only have to change this one line authors = ['cases', 'laws', 'marriage', 'other', 'penance', 'second'] authors.remove(test) corpus = [] for author in authors: corpus += u.tokenize('./corpus/' + author + '.txt') ''' Find the n most frequent words in the corpus to use as features. ''' mfws = list(u.frequencies(corpus).keys())[:30] ''' For each of these n features, calculate the share of each of the x authors’ subcorpora represented by this feature, as a percentage of the total number of words. ''' corp_f_dict = {} empty = dict.fromkeys(mfws, 0) for author in authors: corp_f_dict[author] = empty.copy() subcorpus = u.tokenize('./corpus/' + author + '.txt') subcorpus_frequencies = u.frequencies(subcorpus) for word in mfws: corp_f_dict[author][word] = (subcorpus_frequencies.get(word, 0) / len(subcorpus)) * 1000 u.write_csv(corp_f_dict, './subcorpus_frequencies.csv') ''' Then, calculate the mean and the standard deviation of these x values and use them as the offical mean and standard deviation for this feature over the whole corpus. In other words, we will be using a mean of means instead of calculating a single value representing the share of the entire corpus represented by each word. ''' means = empty.copy() stdevs = empty.copy() for word in mfws: corp_f_list = [] for author in authors: corp_f_list.append(corp_f_dict[author][word]) means[word] = statistics.mean(corp_f_list) stdevs[word] = statistics.stdev(corp_f_list) ''' For each of the n features and x subcorpora, calculate a z-score describing how far away from the corpus norm the usage of this particular feature in this particular subcorpus happens to be. To do this, subtract the "mean of means" for the feature from the feature’s frequency in the subcorpus and divide the result by the feature’s standard deviation. ''' corp_z_dict = {} for author in authors: corp_z_dict[author] = empty.copy() for word in mfws: corp_z_dict[author][word] = (corp_f_dict[author][word] - means[word]) / stdevs[word] ''' Then, calculate the same z-scores for each feature in the text for which we want to determine authorship. ''' test_tokens = [] test_tokens = u.tokenize('./corpus/' + test + '.txt') test_frequencies = u.frequencies(test_tokens) test_f_dict = test_z_dict = empty.copy() for word in mfws: test_f_dict[word] = (test_frequencies.get(word, 0) / len(test_tokens)) * 1000 # can collapse this into one loop test_z_dict[word] = (test_f_dict[word] - means[word]) / stdevs[word] print(test_z_dict) ''' Finally, calculate a delta score comparing the anonymous paper with each candidate’s subcorpus. To do this, take the average of the absolute values of the differences between the z-scores for each feature between the anonymous paper and the candidate’s subcorpus. (Read that twice!) This gives equal weight to each feature, no matter how often the words occur in the texts; otherwise, the top 3 or 4 features would overwhelm everything else. ''' for author in authors: sum = 0 for word in mfws: sum += math.fabs(corp_z_dict[author][word] - test_z_dict[word]) delta = sum / len(mfws) print(test + "-" + author + " delta: " + str(delta)) if __name__ == '__main__': main()
9b206a858162edeecd4ce5586bd466b0dca61b90
ZihengZZH/LeetCode
/py/ZigZagConversion.py
948
4.34375
4
''' The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". ''' def convert(s, numRows): if numRows == 1 or numRows >= len(s): return s L = [''] * numRows index, step = 0, 1 for x in s: L[index] += x if index == 0: step = 1 elif index == numRows -1: step = -1 index += step return ''.join(L) if __name__ == "__main__": input_str = "QWERTYUIOPASDFGHJKL" input_num = 4 output_str = convert(input_str,input_num) print("OUTPUT STRING IS",output_str)
c9fdaa54540f9911ef73b982f819972dea6b18a7
amisha1garg/Arrays_In_Python
/Replace0swith5.py
745
4.09375
4
# You are given an integer N. You need to convert all zeroes of N to 5. # # Example 1: # # Input: # N = 1004 # Output: 1554 # Explanation: There are two zeroes in 1004 # on replacing all zeroes with "5", the new # number will be "1554". # Function should return an integer value def convertFive(n): # Code here y = [int(x) for x in str(n)] for i in range(len(y)): if y[i] == 0: y[i] = 5 s = [str(j) for j in y] # Join list items using join() n = int("".join(s)) return n # { # Driver Code Starts # Your code goes here if __name__ == '__main__': t = int(input()) for i in range(t): print(convertFive(int(input().strip()))) # } Driver Code Ends
1fb21d9d0f5fe307ee60102926576d67846ce91e
FelipeRodri03/Trabajos-algoritmos-y-programaci-n
/Taller de estructuras de control/Ejercicio9.py
490
3.71875
4
""" Entradas a-->int-->Monto de la compra Salidas b-->int-->Valor final de la compra """ a=int(input()) #caja negra if (a<50000): b="El valor de la compra es "+str(a) elif (a>50000 and a<100000): b="El valor de la compra es "+str(a-(a*0.05)) elif (a>=100000 and a<700000): b="El valor de la compra es "+str(a-(a*0.11)) elif (a>=700000 and a<1500000): b="EL valor de la compra es "+str(a-(a*0.18)) elif (a>=1500000): b="El valor de la compra es "+str(a-(a*0.25)) print(b)
7cce5f8b4cbad6fd7492391f5fde04a21e28f965
951237/TIL
/TIL_2021/일상/210402_백준_10809_정답.py
276
3.921875
4
# 입력받은 단어에 사용된 알파벳의 사용여부 및 위치 출력하기 word = input() alphabet = list(range(97,123)) # 아스키코드 숫자 범위 for i in alphabet: print(word.find(char(x))) # char() : 숫자를 문자로 , ord() : 문자를 숫자로
22b1fd3a48fc4b8cace7aeeb5b5a2ba57c129283
pagotarane/program_for_reffer
/Python/python/L1/p10.py
232
4.21875
4
#wapp to check if the given year is leap or not year = int(input("Enter year ")) b1 = (year%100==0) and (year%400==0) b2 = (year%100!=0) and (year%4==0) if b1 or b2 : print("It is leap year") else : print("It is not leap year")
7a60e7e8eef8f59bc2d780e09be9980c7981e3d7
athiq-ahmed/Python
/numbers.py
5,262
4.03125
4
var1 = 10 var2 = 20 del var1, var2 #Python supports four different numerical types − # Integers - They are often called just integers or ints, are positive or negative whole numbers with no decimal point. # Long - Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L. # Float - Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250). # complex - are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). #int long float complex #10 51924361L 0.0 3.14j #100 -0x19323L 15.20 45.j #-0x260 -052318172735L -32.54e100 3e+26J #Number type conversion a =10 type(a) b = float(a) type(b) c = complex(a) type(c) #Mathematical functions import math a = -100.52 b = abs(a) print ("abs(-45): ", abs(-45)) print ("abs(100.12): ", abs(100.12)) #print ("abs(119L): ", abs(119L)) #ceil - This method returns smallest integer not less than x. c = math.ceil(a) print ("math.ceil(-45.17): ", math.ceil(-45.17)) print ("math.ceil(100.12): ", math.ceil(100.12)) print ("math.ceil(100.72): ", math.ceil(100.72)) #print ("math.ceil(119L): ", math.ceil(119L)) print ("math.ceil(math.pi): ", math.ceil(math.pi)) #cmp( x, y ) - This method returns -1 if x < y, returns 0 if x == y and 1 if x > y def cmp(a,b): if a < b: return (-1) elif (a > b): return (1) elif (a ==b): return 0 print ("cmp (10,20) is: ", cmp(10,20)) print ("cmp(80, 100): ", cmp(80, 100)) print ("cmp(180, 100): ", cmp(180, 100)) print ("cmp(-80, 100): ", cmp(-80, 100)) print ("cmp(80, -100): ", cmp(80, -100)) #exp a= math.exp(10*2) print ("math.exp(-45.17): ", math.exp(-45.17)) print ("math.exp(100.12): ", math.exp(100.12)) print ("math.exp(100.72): ", math.exp(100.72)) #print ("math.exp(119L): ", math.exp(119L)) print ("math.exp(math.pi): ", math.exp(math.pi)) #fabs - This method returns absolute value of x a = math.fabs(-10.43) print ("math.fabs(-45.17): ", math.fabs(-45.17)) print ("math.fabs(100.12): ", math.fabs(100.12)) print ("math.fabs(100.72): ", math.fabs(100.72)) #print ("math.fabs(119L): ", math.fabs(119L)) print ("math.fabs(math.pi): ", math.fabs(math.pi)) #floor - This method returns largest integer not greater than x. a = math.floor(19.99) print ("math.floor(-45.17): ", math.floor(-45.17)) print ("math.floor(100.12): ", math.floor(100.12)) print ("math.floor(100.72): ", math.floor(100.72)) #print ("math.floor(119L): ", math.floor(119L)) print ("math.floor(math.pi): ", math.floor(math.pi)) #log - This method returns natural logarithm of x, for x > 0. a = math.log(10) #print ("math.log(-45.17): ", math.log(-45.17)) print ("math.log(100.12): ", math.log(100.12)) print ("math.log(100.72): ", math.log(100.72)) #print ("math.log(119L): ", math.log(119L)) print ("math.log(math.pi): ", math.log(math.pi)) #sqrt a = math.sqrt(10) #print ("math.sqrt(-45.17): ", math.sqrt(-45.17)) print ("math.sqrt(100.12): ", math.sqrt(100.12)) print ("math.sqrt(100.72): ", math.sqrt(100.72)) #print ("math.sqrt(119L): ", math.sqrt(119L)) print ("math.sqrt(math.pi): ", math.sqrt(math.pi)) #Random number functions #choice(seq) - The method choice() returns a random item from a list, tuple, or string. import random print("choice[1,2,4,5,10]: ",random.choice([1,2,4,5,10])) print("Python is good: ",random.choice("Python is good")) #randrange() - The method randrange() returns a randomly selected element from range(start, stop, step). #randrange ([start,] stop [,step]) print("random.randrange(10,20,1): ",random.randrange(10,20,1)) #random - The method random() returns a random float r, such that 0 is less than or equal to r and r is less than 1. print("random: ",random.random()) #seed - The method seed() sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. random.seed(10) print("",random.random()) #shuffle - This method returns reshuffled list. list = [1,3,4,6] random.shuffle(list) print("random list is: ", list) #uniform - The method uniform() returns a random float r, such that x is less than or equal to r and r is less than y print("The random numbers are: ",random.uniform(1,2)) #Trignometric functions #sin - This method returns a numeric value between -1 and 1, which represents the sine of the parameter x. print("sin(3) is: ",math.sin(10)) #hypot - The method hypot() return the Euclidean norm, sqrt(x*x + y*y) print("math.hypot(10,20) is: ",math.hypot(1,2)) #cos - The method cos() returns the cosine of x radians print("math.cos(10): ",math.cos(10)) #tan - The method tan() returns the tangent of x radians print("math.tan(10): ",math.tan(10)) #degress - The method degrees() converts angle x from radians to degrees print("math.degrees(10): ",math.degrees(10)) #radians - The method radians() converts angle x from degrees to radians print("math.radians(10): ",math.radians(10))
4e66b24b0c7cd23369f80aa62018b2310b5d33da
maddy-dolly/Python_Tutorial
/Advance_Python/formate.py
817
3.765625
4
person = {'name':'Madhu Acharya', 'age':23} setence = 'My name is ' + person['name'] + ' and i am ' + str(person['age']) + ' year old' setence_1 = 'My name is {0} and I am {1} year old.'.format(person['name'],person['age']) setence_2 = 'My name is {0[name]} and I am {1[age]} year old.'.format(person,person) setence_3 = 'My name is {0[name]} and I am {0[age]} year old.'.format(person) print(setence_3) #access attribute from the class class Person: def __init__(self,name,age): self.name = name self.age = age def my_fun(self): if self.age > 18: return True else: return False p1 = Person('maddy',15) print(p1.my_fun()) obj = Person('Jack','33') setence_4 = 'My name is {0.name} and I am {0.age} year old.'.format(obj) print(setence_4)
85fa3c64fdfccbfeaae21dd943c068d0de022754
grbalmeida/hello-python
/programming-logic/repeating-structures/count-to-5.py
86
3.921875
4
number = 0 while number < 5: print(number) number = number + 1 print('Ended!')
7e73c0a3b07675bca0b2639c75a8f8576e983b8f
Mr-wr/python
/study_python/python基础/Demo_11生成器.py
1,428
3.921875
4
#!/usr/bin/env python3 #告诉linux system this is execute procedure #windows 会忽略这个 # -*- coding: utf-8 -*- #告诉python解析器是按照utf-8编码的 #------------------------------生成器 #在python中一遍循环一遍计算的机制就称作为生成器 #在python中只要把】改成)就是了但是不用用平时的print用next来打印 # g = (x*x for x in range(1,10)) # '''for x in g: # print(x)''' #赋值语句 # def fib(max): # n, a, b = 0, 0, 1 # while n < max: # print(b) # a, b = b, a + b # n = n + 1 # return 'done' #a,b = (b,a+b) #------------------------------yield #凡是定义了yield就不是一个普通函数了而是一个generator #定义了yield的方法遇到了yield就返回跟return一样 #会返回yield后面的数 # n = 0 # def testyield(max,n): # L = [1] # while n < max: # yield L # L=[1]+[L[i]+L[i+1]for i in range(len(L)-1)]+[1] # n = n+1 # for t in testyield(10,n): # print(t) # def tyield(a): # while a < 3: # yield a # a = a+1 # return 'ok' # def fib(max): # n, a, b = 0, 0, 1 # while n < max: # yield b # a, b = b, a + b # n = n + 1 # return 'done' # # c = fib(3) # def odd(): # print('step 1') # yield 1 # print('step 2') # yield(3) # print('step 3') # yield(5) # o = odd() # next(o) print('ok')
fabdd7050818f130862b576bce425c67bfb77e17
MrHamdulay/csc3-capstone
/examples/data/Assignment_8/bndtat003/question3.py
723
4.375
4
#Program to encrypt a program with the next set of characters in the alphabet #Matthew Bandama #BNDTAT003 #07-May-2014 def encrypt(string): if len(string) == 0: return() else: letter = ord(string[0]) + 1 next_letter = chr(letter) if string[0] == ' ': next_letter = ' ' elif string[0].isupper() == True: next_letter = string[0] elif string[0] == '.': next_letter = '.' elif string[0] == 'z': next_letter = 'a' print(next_letter,end ='') string = string[1:] encrypt(string) def main(): print('Enter a message:') string = input() print('Encrypted message:') encrypt(string) print() if __name__=='__main__': main()
ef9154f033b7a659033d41b5dad80cc79e03f317
mikel-codes/python_scripts
/MTs_py/mtsleep.py
1,136
3.546875
4
import thread import re from time import ctime, sleep loop_st = [5, 2] def loop(nloops, nsecs, lock): print "loop",nloops , " started .>", re._compile('\d\d:\d\d:\d\d', 0).search(ctime()).group() sleep(nsecs) print "loop",nloops , " ended .>" , re._compile('\d\d:\d\d:\d\d', 0).search(ctime()).group() lock.release() def main(): print "This is the main process as the heavyweigth process" print "started at ", re._compile('\d\d:\d\d:\d\d', 0).search(ctime()).group() locks = [] loops = range(len(loop_st)) # >> [0,1] for i in loops: """ its like lock saying its now offically a lock device""" lock = thread.allocate_lock() # this create the padlock lock.acquire() # this locks the padlock locks.append(lock) # :browse confirm wa pass for i in loops: thread.start_new_thread(loop, (i, loops[i], locks[i])) for i in loops: if locks[i].locked(): pass pass print "end ", re._compile('\d\d:\d\d:\d\d', 0).search(ctime()).group() pass if __name__ == '__main__': main()
4dcc095c32665370daa5431befa26c49386d9a17
Ideaboy/python_projects
/TetrisGame/gamewall.py
2,901
3.65625
4
#!/usr/bin/python # -*- coding:utf-8 -*- # @Time : 2019-6-17 22:14:13 # @Author : WUGE # @Email : # @Copyright: from settings import * from gamedisplay import * class GameWall(object): """游戏区墙体类。功能:记住落到底部的方块组成的“墙体”""" def __init__(self, screen): """游戏开始,有20*10 个格子为‘-’表示,墙为空""" self.screen = screen self.area = [] line = [WALL_BLANK_LABEL] * COLUMN_NUM for i in range(LINE_NUM): self.area.append(line[:]) def print(self): """打印 20*10 的二维矩阵 self.area 元素,便于调试""" print(len(self.area), "rows", len(self.area[0]), "colums") for line in self.area: print(line) def add_to_wall(self, piece): """把方块 piece 砌到墙体""" shape_turn = PIECES[piece.shape][piece.turn_times] for r in range(len(shape_turn)): for c in range(len(shape_turn[0])): if shape_turn[r][c] == 'O': self.set_cell(piece.y + r, piece.x + c, piece.shape) def set_cell(self, r, c, shape_label): """把第 r 行 c 列的格子打上方块标记,表示此格子已占据""" self.area[r][c] = shape_label def is_wall(self, r, c): return self.area[r][c] != WALL_BLANK_LABEL def eliminate_line(self): """消除行,如果一行没有空白单位格子,就消掉该行,返回得分""" # 需要消除的几行 lines_eliminated = [] for r in range(LINE_NUM): if self.is_full(r): lines_eliminated.append(r) # 消行,更新墙体矩阵 for r in lines_eliminated: self.copy_down(r) # 确保最上面一层下层效果如预期——清空 for c in range(COLUMN_NUM): self.area[0][c] = WALL_BLANK_LABEL # 根据消除的行数,计算得分 eliminate_num = len(lines_eliminated) assert(eliminate_num <= 4 and eliminate_num >= 0) if eliminate_num < 3: score = eliminate_num * 10 elif eliminate_num == 3: score = 50 else: score = 100 return score def is_full(self, r): """判断下标为 r 的一行满了没""" for c in range(COLUMN_NUM): if self.area[r][c] == WALL_BLANK_LABEL: return False return True def copy_down(self, row): """把 r 行上面的各行下降一层""" for r in range(row, 0, -1): for c in range(COLUMN_NUM): self.area[r][c] = self.area[r - 1][c] def clear(self): """清除墙,为重开游戏做准备""" for i in range(COLUMN_NUM): for j in range(LINE_NUM): self.area[j][i] = WALL_BLANK_LABEL
439101c6488325d0d8b2e498b8193e67634a41b3
OK19/Python-Notes
/ttl.py
156
3.671875
4
''' import turtle bob = turtle.Turtle() bob.position() (0.00, 242.00) bob.circle(113) turtle.mainloop() ''' def drawRing(t, ring): ring = circle(113)
c9fed3ef2fadadaee07a36333c25eb6f8c540641
Ho0ost/UvA_inleiding_prog
/module 2/randomgen.py
176
3.671875
4
import random def random_range(a,b): return a +(b-a)*random.random() minimum = -5 maximum = 5 for i in range(10): x = random_range(minimum, maximum) print(x)
1b1030308d7e9282a032566d60e51b1f12e45895
981377660LMT/algorithm-study
/21_位运算/格雷码/1238. 循环码排列.py
437
3.96875
4
from typing import List # 给你两个整数 n 和 start。你的任务是返回任意 (0,1,2,,...,2^n-1) 的排列 p class Solution: def circularPermutation(self, n: int, start: int) -> List[int]: return [start ^ i ^ (i >> 1) for i in range(2 ** n)] print(Solution().circularPermutation(n=3, start=2)) # 输出:[2,6,7,5,4,0,1,3] # 解释:这个排列的二进制表示是 (010,110,111,101,100,000,001,011)
b1501784cad274af8abb9fc85e8e50a2cb841d11
xiao2912008572/Appium
/测试代码/列表.py
653
3.75
4
# Author:Xiaojingyuan # list = [23,45,23,23 ,67,45,88,67] # dict = {} # # count = 0 # for i in range(len(list)): # for j in range(i+1,len(list)): # if list[i] == list[j]: # dict[list[i]] = count # print(list[i]) # print(dict) # # # # # mylist = [1,2,2,2,2,3,3,3,4,4,4,4] # myset = set(mylist) #myset是另外一个列表,里面的内容是mylist里面的无重复 项 # for item in myset: # print("the %d has found %d" %(item,mylist.count(item))) # # # from collections import Counter # mylist = [1,2,2,2,2,3,3,3,4,4,4,4] # a = Counter(mylist) # print(a) # # # # # # list1 = list # # print(list1)
5af6317cfc6b5415fae0459bd3512661ff1a7b16
nizbit/protonlabs
/645Project/test.py
6,197
3.515625
4
import tkFileDialog def extract(text, sub1, sub2): """ extract a substring from text between first occurances of substrings sub1 and sub2 """ #Needs to be fixed temp = text.split(sub1, 1)[-1].split(sub2, 1)[0] temp = temp.strip() return temp.split("\n") def storeInDict(text, dict): temp = [] for line in text: line = line.strip() words = line.split(' ') key = words[0] value = words[1] dict[key] = int(value) temp.append(words) return temp def LD(item, memory, regs): loop = 'loop:' for i in item: print i if i == 'LD': if item[0].lower() == loop: dest = item[2] source = item[3] else: dest = item[1] source = item[2] result = source.translate(None, ')').split('(') loc = int(result[0]) + regs[result[1]] memValue = memory[str(loc)] #memValue = memory[str(0)] regs[dest] = memValue def DADD(item, memory, regs): loop = 'loop:' for i in item: if i == 'DADD': if item[0].lower() == loop: dest = item[2] source1 = regs[item[3]] source2 = regs[item[4]] else: dest = item[1] source1 = regs[item[2]] source2 = regs[item[3]] #print source1, source2 answer = source1 + source2 #print answer regs[dest] = answer def DADDI(item, memory, regs): loop = 'loop:' for i in item: if i == 'DADDI': if item[0].lower() == loop: dest = item[2] source1 = regs[item[3]] source2 = item[4] else: dest = item[1] source1 = regs[item[2]] source2 = item[3] source2 = source2.translate(None, '#') answer = source1 + int(source2) #print answer regs[dest] = answer def SD(item, memory, regs): loop = 'loop:' for i in item: if i == 'SD': if item[0].lower() == loop: temp = item[2] addr = temp.translate(None, ')').split('(') dest = int(addr[0]) + regs[addr[1]] source = regs[item[3]] memory[dest] = source else: temp = item[1] addr = temp.translate(None, ')').split('(') dest = int(addr[0]) + regs[addr[1]] source = regs[item[2]] memory[dest] = source def BNEZ(item, memory, regs): for i in item: if i == "BNEZ": cmp = regs[item[1]] if cmp == 0: return False else: return True file = tkFileDialog.askopenfile(title="Open input data file", mode='r', filetypes=[("all formats", "*")]) regs = {} for x in range(32): key = 'R' + str(x) regs[key] = 0 memory = {} for x in range(0, 996, 8): memory[str(x)] = 0 text = file.read() reg = extract(text, 'REGISTERS', 'MEMORY') mem = extract(text, 'MEMORY', 'CODE') code = extract(text, 'CODE', 'EOF') reg = storeInDict(reg, regs) mem = storeInDict(mem, memory) op = [] for element in code: line = element.strip() newline = line.translate(None, ',') word = newline.split() op.append(word) x=0 while x < 3: for op[x] in op: print op[x][0] x += 1 IO = [] pc = 0 spot = 0 loop = 'loop:' index = 1 numLoop = 0 func = {'LD':LD, 'SD':SD, 'DADD':DADD, 'DADDI':DADDI, 'BNEZ':BNEZ} while index < (len(op)): print 'top' for item in op: print 'pc',pc print 'index',index-1 #IO.append(op[index-1]) if item[0] == 'LD': print 'ld' if index > (len(op)): break IO.append(op[index-1]) LD(item, memory, regs) pc += 1 if item[0] == 'SD': print 'sd' if index > (len(op)): break IO.append(op[index-1]) SD(item, memory, regs) pc += 1 if item[0].lower() == loop: print 'loop' if index > (len(op)): break IO.append(op[index-1]) varstring = item[1] func[varstring](item, memory, regs) spot = pc pc += 1 if item[0] == 'DADD': print 'dadd' if index > (len(op)): break IO.append(op[index-1]) DADD(item, memory, regs) pc += 1 if item[0] == 'DADDI': print 'daddi' if index > (len(op)): break IO.append(op[index-1]) DADDI(item, memory, regs) pc += 1 if item[0] == 'BNEZ': print 'bnez' if index > (len(op)): break IO.append(op[index-1]) temp = BNEZ(item, memory, regs) print 'temp',temp if temp == False: """ last change is below- delete pass and remove comment to revert """ #index = pc pass if temp == True: pc = spot index = pc index += 1 print 'bottom' print 'pc', pc print 'spot', spot print IO print regs file.close() """ LD(['LD', 'R2', '0(R1)'], memory, regs) DADD(['DADD', 'R4', 'R2', 'R3'], memory, regs) SD(['SD', '0(R1)', 'R4'], memory, regs) DADDI(['DADDI', 'R1', 'R1', '#-8'], memory, regs) BNEZ(['BNEZ', 'R1', 'Loop'], memory, regs) DADD(['DADD', 'R2', 'R2', 'R4'], memory, regs) """
2a843e5b03aad6d518469ec22ae74ce2823fa9d3
anatshk/SheCodes
/Exercises/lecture_9/lecture_9_roman_to_int.py
1,065
3.796875
4
def romanToInt(self, s): """ Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. :type s: str :rtype: int """ mapping = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } ret_val = 0 if len(s) == 1: assert s in mapping, 'Unknown Roman numeral {}'.format(s) return mapping[s] while len(s): if len(s) == 1: ret_val += mapping[s] s = [] else: curr_letter, next_letter = s[0:2] if mapping[curr_letter] < mapping[next_letter]: ret_val += mapping[next_letter] - mapping[curr_letter] s = s[2:] else: ret_val += mapping[curr_letter] s = s[1:] return ret_val # # debug # assert romanToInt('I') == 1 # assert romanToInt('LIV') == 54 # assert romanToInt('XCIX') == 99 # assert romanToInt('CIII') == 103 # assert romanToInt('M') == 1000
3c112db14262791e4149047360fcb099fd3065da
qs8607a/Algorithm-45
/SortAlgorithm/MergeSort.py
641
4.28125
4
# Introduction to Algorithm - Chapter 2: Getting Started # MERGE_SORT def merge(left, right): res = []; i = 0; j = 0; while i < len(left) and j < len(right): if left[i] <= right[j]: res.append(left[i]); i = i + 1; else: res.append(right[j]); j = j + 1; res += left[i:]; res += right[j:]; return res; def mergeSort(arr): """ sort array using a merge sort algorithm """ if len(arr) <= 1: return; middle = int(len(arr)/2); left = mergeSort(arr[:middle]); right = mergeSort(arr[middle:]); merge(left, right);
a53d1f56294c7bdd720490a2ea54ecf5e57b8740
LuizFernandoS/PythonCursoIntensivo
/Capitulo03_IntroducaoListas/03_06DinerGuestsBigger.py
2,270
4.09375
4
"""3.6 – Mais convidados: Você acabou de encontrar uma mesa de jantar maior, portanto agora tem mais espaço disponível. Pense em mais três convidados para o jantar. • Comece com seu programa do Exercício 3.4 ou do Exercício 3.5. Acrescente uma instrução print no final de seu programa informando às pessoas que você encontrou uma mesa de jantar maior. • Utilize insert() para adicionar um novo convidado no início de sua lista. • Utilize insert() para adicionar um novo convidado no meio de sua lista. • Utilize append() para adicionar um novo convidado no final de sua lista. • Exiba um novo conjunto de mensagens de convite, uma para cada pessoa que está em sua lista.""" #pg81 guests=['José', 'João', 'Pedro', 'Tiago'] message = "Gostaria de jantar comigo, " + guests[0].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[1].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[2].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[3].title() + "?" print(message) print(guests[0].title() + ' não poderá comparecer!') #se usar "remove()", a posição da lista é deletada! guests[0]='João Paulo Libélula' message = "Gostaria de jantar comigo, " + guests[0].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[1].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[2].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[3].title() + "?" print(message) print('Encontrei uma mesa maior, suas frangas!') guests.insert(0, 'Mateus') guests.insert(3, 'Tomé') guests.append('Simão') message = "Gostaria de jantar comigo, " + guests[0].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[1].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[2].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[3].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[4].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[5].title() + "?" print(message) message = "Gostaria de jantar comigo, " + guests[6].title() + "?" print(message)
32e80281f3f90765e59236dd5f6975168f0f1411
mattmc96/python_notes
/main.py
569
4.1875
4
# 1 - Create a program that asks the user to enter their name and their age. Print out a message addressed # to them that tells them the year that they will turn 100 years old. # Request input from user name = str(input('Enter your name: ')) age = int(input('Enter your age in years: ')) # Request an additional number and print output this number of times number = int(input('Please enter an additional number: ')) # Evaluate input year = (100 - age) + 2017 # Output print(('Dear Mr/Ms ' + name + ', you will turn 100 years old on ' + str(year) + '\n') * number)
0b69c504b2f15c83b97964893feb8d3ebbba14b9
yparam98/leetcode-exercises
/rectangle_area_ii.py
879
3.765625
4
#!/usr/bin/python3 from typing import List class Solution: def rectangleArea(self, rectangles: List[List[int]]) -> int: total_area: int = 0 for rectangle in rectangles: base: int = rectangle[2]-rectangle[0] height: int = rectangle[3]-rectangle[1] area: int = base*height print('base: {0}, height: {1}, area: {2}'.format(base, height, area)) total_area += area return total_area def main(): solution = Solution() rectangles: List[int] = [] num_rects: int = int(input('how many rectangles? ')) for i in range(num_rects): rectangle: List[int] = [] for val in input('x1 y1 x2 y2: ').split(' '): rectangle.append(int(val)) rectangles.append(rectangle) print(solution.rectangleArea(rectangles)) main()
52893f66b264c98b56c04ae08f94c7885afeff4f
AidenJauffret/COGS18-FINAL-PROJECT
/final_project.py
3,674
3.84375
4
import pickle import webbrowser #global dictionary song_list = {} """ This class assigns a song URL to a chosen name. """ class URLAssignment(): global song_list """ This function creates a dictionary of songs and their names. """ def song_assign(self, song_url, assigned_name): song_list.update({assigned_name: song_url}) self.save_song() """ This function saves the dictionary to a file. """ def save_song(self): with open('song_list.pkl', 'wb') as f: pickle.dump(song_list, f, pickle.HIGHEST_PROTOCOL) """ This class removes songs. """ class RemoveSong(): global song_list """ This function removes a song, and makes sure that an inputted name matches. """ def song_delete(self, song_name): if song_name not in song_list.keys(): print("Invalid selection") print() return del song_list[song_name] """ This class plays the specified song. """ class PlaySong(): global song_list """ This function takes in url, brings the user to a webbrowser and makes sure that an inputted name matches. """ def name_identifier(self, assigned_name): song_list = self.load_song() if assigned_name not in song_list.keys(): print("Invalid selection") print() return webbrowser.open(song_list[assigned_name]) """ This function prints out list of songs before selecting one. """ def load_song(self): with open('song_list.pkl', 'rb') as f: return pickle.load(f) """ These variables instantiate the classes into objects. """ url_assignment = URLAssignment() play_song = PlaySong() remove_song = RemoveSong() """ This code block tests to see if a list exists, and if not, creates an empty one. """ try: song_list = play_song.load_song() except: song_list = {} url_assignment.save_song() #while loop that runs through the options until users quits while True: #shows user their choices to either save or play a song choice = input('Save song? (press 1)' + '\n' + 'Play song? (press 2)' + '\n' + 'Delete song? (press 3)' + '\n' + 'QUIT (press 4)' + '\n') #if user selects option 1, they are told to input a song and name if choice == '1': url = input('Enter URL: ') song_name = input('Enter song name: ') print() url_assignment.song_assign(url, song_name) """ Test #1: checks to make sure a url is properly added """ assert song_list[song_name] == url #if user selects option 2, they are told to input a song to play elif choice == '2': song_list = play_song.load_song() print("\nSaved songs: ") for ind in song_list.keys(): print (ind) print() song_name = input('Enter song to play: ') print() play_song.name_identifier(song_name) #if user selects option3, they are told to input a song to delete elif choice == '3': print("\nSaved songs: ") for ind in song_list.keys(): print (ind) print() song_name = input('Enter song to delete: ') remove_song.song_delete(song_name) url_assignment.save_song() """ Test #2: makes sure the correct song is deleted """ assert song_name not in song_list #if user selects option 4, the program shuts down elif choice == '4': break else: print("Invalid selection") print()
9d8b3e702a5f8258ea3c3c2039b5f68ca3bb25c6
grigor-stoyanov/PythonAdvanced
/comprehension/flatten_list.py
101
3.515625
4
line = input().split(*'|') flat = [num for ele in reversed(line) for num in ele.split()] print(*flat)
8a494da75b13047517588ef85cbafab832eac3e5
d4rkr00t/leet-code
/python/leet/987-vertical-order-traversal-of-a-binary-tree.py
713
3.859375
4
# Vertical Order Traversal of a Binary Tree # url: https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ # medium def verticalTraversal(root): # [1,2,3,4,5,6,7] if (not root): return [] tmp = {} def dfs(node, x=0, y=0): if (node): if (not x in tmp): tmp[x] = {} if (not y in tmp[x]): tmp[x][y] = [] tmp[x][y].append(node.val) dfs(node.left, x-1, y+1) dfs(node.right, x+1, y+1) dfs(root) res = [] for x in sorted(tmp): rep = [] for y in sorted(tmp[y]): rep.extend(sorted(tmp[x][y])) res.append(rep) return res
dfedf94fe6329d057d5931be38dc097d6a8a3abc
Taoge123/OptimizedLeetcode
/LeetcodeNew/python/LC_082.py
1,457
3.828125
4
""" Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: dummy = pre = ListNode(0) dummy.next = head while head and head.next: if head.val == head.next.val: while head and head.next and head.val == head.next.val: head = head.next head = head.next pre.next = head else: pre = pre.next head = head.next return dummy.next class Solution2: def deleteDuplicates(self, head): pre = dummy = ListNode(0) # construct a dummy node dummy.next = head cur = head while cur: if cur.next and cur.val == cur.next.val: # loop until cur point to the last duplicates while cur and cur.next and cur.val == cur.next.val: cur = cur.next pre.next = cur.next # propose the next for pre # this will be verified by next line else: pre = pre.next cur = cur.next return dummy.next
3d63f6d74bdf852fa40176f8c528c92c419c796d
gaya38/devpy
/Python/assignment/pes-python-assignments-1x.git/131.py
317
3.578125
4
a=[] for i in range(4): b=input("Enter a value:") a.append(b) a.append(6) print "Large number among the five values is:" for l in range(len(a)-1): if (a[l]>a[l+1]): temp=a[l] a[l]=a[l+1] a[l+1]=temp else: continue print a[-1]
41128adcb41ff09632b167725a258f387ee7437c
fghjklvmbn/practice-python
/양수 음수 구별기.py
229
3.8125
4
number = input("숫자를 입력하십시오: ") number = int(number) if number < 0: print("음수입니다.") if number > 0: print("양수입니다.") if number == 0: print("음수도 양수도 아닌 0 입니다.")
bca34a1fd55212fe4bf920638893c8b8e017b989
Uva4/mi_primer_programa
/spaces_dots.py
403
3.640625
4
user_sentence = input('Escribe una frase: ') space = ' ' dot = '.' comma = ',' n_space = 0 n_dots = 0 n_commas = 0 for letra in user_sentence: if letra in space: n_space += 1 elif letra in dot: n_dots += 1 elif letra in comma: n_commas += 1 print('Espacios = {}'.format(n_space)) print('Puntos = {}'.format(n_dots)) print('Comas = {}'.format(n_commas))
8166fa37568c99cdd5411b3fd5ebe29e5dad7363
YashKesarwani/Python_Games
/LotterySimulation.py
777
3.78125
4
import random import matplotlib.pyplot as plt account=0 x=[] y=[] for i in range(365): x.append(i+1) bet=random.randint(1,10) #bet=int(input("Your bet from 1 to 10")) lucky_draw=random.randint(1,10) #print("Bet=",bet) #print("Lucky draw= ",lucky_draw) if bet==lucky_draw: account=account+900-100 else: account=account-100 y.append(account) #print("Amount in account= ",account) print("Amount in account= ",account) plt.plot(x,y) plt.show() #infinity can be assogned to a variable in to python using float("inf") #There is a poem in python which can be read by just writing import this #we can print string stored in a variable x, n times using print(x*n) #You can check memory usage of variable x using sys.getsizeof(x)