blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
18f59e3b0c82c5793bf4a3da409e5c291b4b2012
johnnzz/foundations_python
/module8/lab8-1.py
241
3.640625
4
class person(): firstname = None lastname = None def to_string(self): return self.firstname + " " + self.lastname myguy = person() myguy.firstname = "fred" myguy.lastname = "jones" print(myguy.to_string())
af769b9f0efdf2748187576df4bf3e0e279b4cb4
pgmz/Coding_Test
/Questions/Stacks_and_Queues/Queue_Via_Stacks_python.py
657
3.828125
4
class MyQueue(): def __init__(self): self.s_order = [] self.s_norder = [] def pushToQueue(self, data): while len(self.s_norder)!=0: self.s_order.append(self.s_norder.pop()) self.s_order.append(data) def popFromQueue(self): while len(self.s_order)!=0: self.s_norder.append(self.s_order.pop()) return self.s_norder.pop() newQueue = MyQueue() newQueue.pushToQueue(5) print(newQueue.popFromQueue()) newQueue.pushToQueue(1) newQueue.pushToQueue(2) newQueue.pushToQueue(3) print(newQueue.popFromQueue()) print(newQueue.popFromQueue()) print(newQueue.popFromQueue())
f95eb8b45c4e84c6729f36869ae8fbe1864085e0
gyurel/SoftUni-Basics-and-Fundamentals
/exercise_funktions/odd_and_even_sum.py
318
3.96875
4
def odd_and_even_sum(input_str): odd_sum = [] even_sum = [] even_sum += [int(x) for x in input_str if int(x) % 2 == 0] odd_sum += [int(x) for x in input_str if int(x) % 2 == 1] return f"Odd sum = {sum(odd_sum)}, Even sum = {sum(even_sum)}" input_str = input() print(odd_and_even_sum(input_str))
8372dcd91d1da4ecd5d934b03f86ae23e090a144
andchrlambda/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/buddymove_holidayiq.py
1,285
3.984375
4
import os import sqlite3 import pandas as pd """Creating an SQLite database with queries.""" df = pd.read_csv('buddymove_holidayiq.csv') print(df.head) """Checking for null values.""" nulls = df.isnull().sum().sum() print("There are", nulls, "null values.") CONN = sqlite3.connect('buddymove_holidayiq.db') cursor = CONN.cursor() delete_table = "DROP TABLE IF EXISTS buddy" cursor.execute(delete_table) df.to_sql('buddy', con = CONN, index=True) query = 'SELECT COUNT(Sports) FROM buddy;' rows = cursor.execute(query).fetchall() print ("There are" , rows, "rows.") query2 ='SELECT COUNT(User) FROM buddy WHERE Nature > 100 AND Shopping > 100;' user_count = cursor.execute(query2).fetchall() print("There are", user_count, "users who have reviewed at least 100 in the nature and shopping categories") cat_list = ['Sports', 'Religious', 'Nature', 'Theatre', 'Shopping', 'Picnic'] def mean_review(cat_list): score_list = [] for i in cat_list: query = 'SELECT AVG (' + (i) + ') FROM buddy' score = cursor.execute(query).fetchall() score = str(score).strip('()[],') print("The average for", i, "is" , score) score_list.append(score) return score_list mean_review(cat_list)
91629e1a521ef239aed56df2d97c823c7ae6c11d
sunchitsharma/mini_sql_db
/filereader.py
532
4.03125
4
import csv def filereader(name): try: # OPENING THE FILE file_desc = open (name+".csv" ,'r' ) # READING THE CSV FILE csvread = csv.reader(file_desc) answer=[] # TABLE TO BE RETURNED for row_i in csvread: answer.append(row_i) return answer # ANSWER AS LIST IN A LIST : ROW-WISE except: "Table not found Error!!" ################## TEST CODE #################### # print filereader('table1') #################################################
fe743110239b4c71b841b7c87018b301e783cd95
oceanbei333/leetcode
/73.矩阵置零.py
1,794
3.65625
4
# # @lc app=leetcode.cn id=73 lang=python3 # # [73] 矩阵置零 # # @lc code=start from typing import List class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ if not matrix: return rows = len(matrix) cols = len(matrix[0]) row_flag = [False]*rows col_flag = [False]*cols for row in range(rows): for col in range(cols): if not matrix[row][col]: row_flag[row] = True col_flag[col] = True for row in range(rows): for col in range(cols): if row_flag[row] or col_flag[col]: matrix[row][col] = 0 def setZeroes(self, matrix: List[List[int]]) -> None: if not matrix: return rows = len(matrix) cols = len(matrix[0]) first_row_zero = False first_col_zero = False for row in range(rows): for col in range(cols): if not matrix[row][col]: if not row: first_row_zero = True if not col: first_col_zero = True if row and col: matrix[0][col] = 0 matrix[row][0] = 0 for row in range(1, rows): for col in range(1, cols): if not matrix[0][col] or not matrix[row][0]: matrix[row][col] = 0 if first_row_zero: for col in range(cols): matrix[0][col] = 0 if first_col_zero: for row in range(rows): matrix[row][0] = 0 # @lc code=end
aa1efdf80fb2e7fe0c9231a25f599012e13d067f
tobanteAudio/pyDSP
/dsp/parameter.py
1,390
3.640625
4
'''Parameter classes ''' import abc class AudioParameter: '''Base class for all parameter types ''' def __init__(self, identifier: str, name: str): self._identifier = identifier self._name = name @property def identifier(self) -> str: '''Returns the parameter id ''' return self._identifier @property def name(self) -> str: '''Returns the parameter display name ''' return self._name @property @abc.abstractmethod def value(self): '''Returns the current value ''' @property @abc.abstractmethod def default_value(self): '''Returns the default value ''' class AudioParameterBool(AudioParameter): '''Parameter of type bool ''' def __init__(self, identifier: str, name: str, default_val: bool): super().__init__(identifier, name) self._value = default_val self._default_value = default_val @property def value(self) -> bool: '''Returns the current value ''' return self._value @value.setter def value(self, newValue: bool) -> None: '''Sets the parameter to True or False ''' self._value = newValue @property def default_value(self) -> bool: '''Returns the default value ''' return self._default_value
d495062d9eaec2aa4021df6b66d6c409914bf412
sarastrasner/python-projects
/turtleCrossing/main.py
1,004
3.703125
4
import time from turtle import Screen from player import Player from car_manager import CarManager from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.tracer(0) screen.title("Turtle Crossing") screen.listen() # TODO 1. Create a turtle player that starts at the bottom of the screen and listens for the "Up" keypress to move # the turtle north. player = Player() screen.onkey(player.move, "Up") car_manager = CarManager() scoreboard = Scoreboard() game_is_on = True while game_is_on: time.sleep(0.1) screen.update() car_manager.make_a_car() car_manager.move_cars() # TODO detect collision with cars for car in car_manager.all_cars: if car.distance(player) < 20: game_is_on = False scoreboard.game_over() # TODO detect a successful crossing if player.is_at_finish_line(): player.reset_position() car_manager.level_up() scoreboard.increase_level() screen.exitonclick()
0b5784d6d1a04bda2235f4537a2afef6341a0f74
sonukrishna/MITx-6.00.1x
/week4/oddtuple.py
167
3.859375
4
def oddTuple(tup): rtup = () for i in range(len(tup)): if i%2 == 0: rtup += (tup[i],) return rtup print oddTuple(('I', 'am', 'a', 'test', 'tuple'))
29c1ca6c3211f21f965b8b4a5914295374bac730
shivamsharma0227/Turtle-Race
/main.py
964
3.53125
4
from trackdown import * from random import randint #first turtle mika = Turtle() mika.color("red") mika.shape("turtle") mika.penup() mika.goto(-175,110) mika.pendown() mika.write("mika(1)") for turn in range(10): mika.right(36) #second turtle bob = Turtle() bob.color("purple") bob.shape("turtle") bob.penup() bob.goto(-175,80) bob.pendown() bob.write("bob(2)") for turn in range(10): bob.left(36) #third turtle zira = Turtle() zira.color("yellow") zira.shape("turtle") zira.penup() zira.goto(-175,50) zira.pendown() zira.write("Zira(3)") for turn in range(10): zira.right(36) #fourth turtle cuba = Turtle() cuba.color("blue") cuba.shape("turtle") cuba.penup() cuba.goto(-175,20) cuba.pendown() cuba.write("Cuba(4)") for turn in range(10): cuba.left(36) for race in range(110): mika.forward(randint(1,4)) bob.forward(randint(1,4)) zira.forward(randint(1,4)) cuba.forward(randint(1,4))
00c56e03aa36d90a6b458c7cef8f856ae1bd5dca
z-aitkourdas/colliding-blocks
/pi.py
3,563
3.796875
4
import pygame import math NUM_OF_DIGITS = int(input("Enter the number of digits you want to compute: ")) # Set the number of digits WIDTH, HEIGHT = 1280, 720 # Setting the windows dimensions WHITE = (255,255,255) # Set the RGB color of WHITE GRAY = (190,190,190) # Set the RGB color of GRAY RED = (200,0,0) # Set the RGB color of RED BLUE = (0, 128, 255) # Set the RGB color of BLUE # Create the blok class class Block(object): # Initialize the block dimenssions def __init__(self, size, XY, mass, velocity): self.x = XY[0] self.y = XY[1] self.mass = mass self.v = velocity self.size = size # Determine wheter a collision happen or not def collision(self, other_block): return not (self.x + self.size < other_block.x or self.x > other_block.x + other_block.size) # Calculate the new velocity def NewVelocity(self, other_block): sumM = self.mass + other_block.mass newV = (self.mass - other_block.mass)/sumM * self.v newV += (2 * other_block.mass/ sumM) * other_block.v return newV # Check wheter if a block collide with the wall or not def collide_wall(self): if self.x <= 0: self.v *= -1 return True # Update the new velocity def update(self): self.x += self.v # Draw the two blocks def draw(self, windows, other_block): if self.x < other_block.size: pygame.draw.rect(windows, RED, [other_block.size, self.y , self.size, self.size]) pygame.draw.rect(windows, BLUE, [0, other_block.y , other_block.size, other_block.size]) else: pygame.draw.rect(windows, RED, [self.x, self.y , self.size, self.size]) pygame.draw.rect(windows, BLUE, [other_block.x, other_block.y , other_block.size, other_block.size]) # Calculating the frames per second def update_fps(): fps = str(int(clock.get_fps())) fps_text = font.render(fps, 1, pygame.Color("coral")) return fps_text # Redraw the blocks def redraw(): windows.fill(WHITE) pygame.draw.rect(windows, GRAY, [0 , 0, 1280, 600]) windows.blit(update_fps(), (10,0)) big_block.draw(windows, small_block) font = pygame.font.SysFont(None, 50) text = font.render("Number of collisions : " + str(count), True, (0,0,0)) windows.blit(text, [50, 650]) clock.tick(120) pygame.display.update() # Initialize pygame pygame.init() # Collision sound clack_sound = pygame.mixer.Sound("clack.wav") # Set the time step time_step = 10**(NUM_OF_DIGITS-1) power = math.pow(100, NUM_OF_DIGITS-1) windows = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() font = pygame.font.SysFont('Fira mono', 22) big_block = Block(60*NUM_OF_DIGITS, (320,600-60*NUM_OF_DIGITS), power, -1/time_step) small_block = Block(60, (100, 600-60), 1, 0) count = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() for i in range(time_step): if(small_block.collision(big_block)): clack_sound.play() count+=1 v1 = small_block.NewVelocity(big_block) v2 = big_block.NewVelocity(small_block) big_block.v = v2 small_block.v = v1 if small_block.collide_wall(): clack_sound.play() count+=1 big_block.update() small_block.update() redraw() pygame.quit()
09f2cbcdcc47e1b3c55bad0aa2f968c2784a3ce8
Supermac30/CTF-Stuff
/Mystery Twister/Autokey_Cipher/Autokey Decode.py
328
4.0625
4
""" This script decodes words with the AutoKey Cipher """ ciphertext = input("input ciphertext ") key = input("input key ") plaintext = "" for i in range(len(ciphertext)): plaintext += chr((ord(ciphertext[i]) - ord(key[i]))%26 + ord("A")) key += plaintext[i] print("Your decoded String is:",plaintext)
2f6a5cedb77f528aa533b66003ed3c238654f293
shrivastava-himanshu/Python-Programs
/prime_generator.py
494
3.984375
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 6 09:26:59 2018 @author: shrivh1 """ def prime_generator(n): #list primes from 1 to n for i in range(1,n,1): if prime_check(i): print(i) prime_generator(200) def prime_check(n): flag = 0 if n > 2 and n % 2 == 0: flag = 1 for i in range(3,n//2,2): if n % i == 0: flag = 1 if flag == 0: return True else: return False
c722fba16963f7cd3628e51f432bcf13357c4024
ClementeCortile/Basic_Software_Engineering
/1_Structure_and_Modules/main.py
1,297
3.84375
4
#The program will run from this main file ( C style!) #Read every comment from top to bottom #Try running the file from the terminal with | python3 main.py | command #Python modules are imported from import sys #print(sys.path) #Importing modules import os import numpy as np os.getcwd() #...but we can import our own custom modules that are stored in the same directory/folder # The comment below is a copy of the code contained in test.py and test_2 # test.py has two functions: #################################### """ #test.py def hello_world(): print("Hello World") print("Module_Executed") def hi_world(): print("Hi World") print("Module_Executed") ################################## """ # test_2.py has just one function: """ #test_2 #Relative import def hello_world_2(): print("I am hello world 2!") """ import test # is an absolute custom import import test_2 #BEWARE: eager execution (i#is a relative import !!!!!!!!! #in-line execution) will not work with relative imports #Testing if the main is executing print("executing main - all imports are correct") test.hello_world() #absolute import's functions need to be called as methods on the name of the module test.hi_world() test_2.hello_world_2() #relative imports's functions can just be executed!
5a801c4a2ce042b2d5bab7a578fc32074bb8d28f
roseperrone/interview-questions
/combinations.py
479
4.03125
4
''' Print all combinatiosn of a string. Input: 'ros' Output: set(['', 'rs', 'ors', 'o', 's', 'r', 'os', 'or']) ''' def combinations(string): if len(string) == 1: return set([string, '']) result = set() for i in range(len(string)): for comb in combinations(string[:i] + string[(i+1):]): result.add(''.join(sorted(comb))) result.add(''.join(sorted(comb + string[i]))) return result print str(combinations('ros'))
b5f304542810c64d9a35a076c8cbb0f84ace8e9f
slakkam/problems
/src/HackerRank/JourneyToMoon.py
1,824
3.578125
4
class Vertex: def __init__(self,data): self.data = data self.visited = False self.adjVertices = [] class Tree: def __init__(self): self.vertexDic = {} self.numVertices = 0 def addVertex(self,data): newNode = Vertex(data) self.vertexDic[data] = newNode self.numVertices += 1 def addEdge(self,fromV,toV): self.vertexDic[fromV].adjVertices.append(self.vertexDic[toV]) # for directed tree, following line is not required self.vertexDic[toV].adjVertices.append(self.vertexDic[fromV]) def printTree(self): for value in self.vertexDic.values(): print(value.data) if __name__ == '__main__': n,m = [int(i) for i in input().split()] T = Tree() for i in range(n): T.addVertex(i) for i in range(m): edge = [int(i) for i in input().split()] fromV,toV = edge[0], edge[1] T.addEdge(fromV,toV) #T.printTree() def DFS(T): componentsVertexCount = [] for vertex in T.vertexDic.values(): if not vertex.visited: # count: no of vertices in each traversal componentsVertexCount.append(dfsTraversal(T,vertex,count=[0])) return componentsVertexCount def dfsTraversal(T,vertex,count): vertex.visited = True count[0] += 1 if len(vertex.adjVertices) != 0: for nbr in vertex.adjVertices: if not nbr.visited: dfsTraversal(T,nbr,count) return count[0] ans = 0 componentsVertexCount = DFS(T) # print(componentsVertexCount) nC2 = n*(n-1)/2 x = 0 for ele in componentsVertexCount: x += ele*(ele-1)/2 ans = int(nC2-x) print(ans)
9c8ea510e8c73f2ab6ecc1797b6cc48857875257
siddhant283/Python
/Generators/gen.py
356
3.765625
4
def generator_function(num): for i in range(num): yield i g = generator_function(1000) next(g) next(g) next(g) print(next(g)) # for item in generator_function(1000): # print(item) # def make_list(num): # result=[] # for i in range(num): # result.append(i*2) # return result # my_list = make_list(100)
b4535183618e11f291e607676dbbc21fb7d0cd71
Deepmalya-Sarkar/Programming-With-Python
/argskwargs.py
239
3.953125
4
def printing(*args): print("Printing") for i in args: print(i) def inputing(): li=[] print("enter 5 numbers") for i in range(5): li.append(int(input())) return li myli=inputing() printing(*myli)
8bdc4d1399a7963716e76df7ce499dbd0b188ae0
ywl123ywl/vip10test
/面向对象/初始化属性.py
580
3.828125
4
class washer(): def __init__(self,width,height,brand): self.width = width self.height = height self.brand = brand def wash(self): print(f'haier洗衣机的宽度是{self.width}') print(f'haier洗衣机的高度是{self.height}') print(f'haier洗衣机的品牌度是{self.brand}') def __str__(self): return f'测试{haier.brand}' def __del__(self): print('我被删除了') haier = washer(200,600,'西门子') haier.wash() haier1 = washer(100,900,'haier') haier1.wash() print(haier) del haier
7aeff1eb445ba3f0c9ea930ad602a11154554ea5
oksanabodnar69/Python-Projects
/Convert.py
984
3.703125
4
import json import csv import os.path import argparse def convert_csv_to_json(csvfilepath, jsonfilepath): if os.path.isfile(csvfilepath): with open(csvfilepath,'r') as csvfile: data={} reader = csv.DictReader(csvfile, delimiter=',') for rows in reader: if rows['password']: rows['password'] = None id = rows['user_id'] data[id] = rows with open(jsonfilepath,'w') as jsonfile: jsonfile.write(json.dumps(data,indent=4)) else: print("File not found") if __name__ == "__main__": parser = argparse.ArgumentParser(description='Please provide file path for CSV and JSON files') parser.add_argument('csv',help='provide a path to csv file') parser.add_argument('json',help='provide a path to JSON file') my_namespace = parser.parse_args() convert_csv_to_json(my_namespace.csv, my_namespace.json)
5881c0e644e59b91db3c3854e8bf05fc364e05f8
zplante/University-Assignments
/CS143/asg2/asg2_prt1.py
5,182
4
4
import argparse, re, nltk # https://docs.python.org/3/howto/regex.html # https://docs.python.org/3/library/re.html # https://www.debuggex.com/ def get_words(pos_sent): """ Given a part-of-speech tagged sentence, return a sentence including each token separated by whitespace. As an interim step you need to fill word_list with the words of the sentence. :param pos_sent: [string] The POS tagged stentence :return: """ # add the words of the sentence to this list in sequential order. word_list = [] word_pattern= r"(?P<word>.*?)\/(?P<pos>.*?)( |$)" for re_match in re.finditer(word_pattern, pos_sent): word = str(re_match.group('word')) word_list.append(word) # Write a regular expression that matches only the # words of each word/pos-tag in the sentence. # END OF YOUR CODE retval = " ".join(word_list) if len(word_list) > 0 else None return retval def get_pos_tags(pos_sent): return set(re.findall(r'\S+/(\S+)', pos_sent)) def get_noun_phrase(pos_sent): """ Find all simple noun phrases in pos_sent. A simple noun phrase is a single optional determiner followed by zero or more adjectives ending in one or more nouns. This function should return a list of noun phrases without tags. :param pos_sent: [string] :return: noun_phrases: [list] """ noun_phrases = [] noun_pattern = r"(\S+\/DT )?(\S+\/JJ )*(\S+\/NN[PS''] )*(\S+\/NN)" noun_phrases = re.findall(noun_pattern, pos_sent) temp = [] for list in noun_phrases: phrase = "" for word in list: phrase += word temp.append(phrase) noun_phrases = temp temp2 = [] for phrase in noun_phrases: temp2.append(get_words(phrase)) noun_phrases=temp2 # END OF YOUR CODE return noun_phrases def read_stories(fname): stories = [] with open(fname, 'r') as pos_file: story = [] for line in pos_file: if line.strip(): story.append(line) else: stories.append("".join(story)) story = [] return stories def most_freq_noun_phrase(pos_sent_fname, verbose=True): """ :param pos_sent_fname: :return: """ story_phrases = {} story_id = 1 for story in read_stories(pos_sent_fname): most_common = [] noun_phrases = get_noun_phrase(story) i =0 for phrase in noun_phrases: noun_phrases[i]=phrase.casefold() i+=1 most_common = nltk.FreqDist(noun_phrases).most_common(3) # do stuff with the story # end your code if verbose: print("The most freq NP in document[" + str(story_id) + "]: " + str(most_common)) story_phrases[story_id] = most_common story_id += 1 return story_phrases def test_get_words(): """ Tests get_words(). Do not modify this function. :return: """ print("\nTesting get_words() ...") pos_sent = 'All/DT animals/NNS are/VBP equal/JJ ,/, but/CC some/DT ' \ 'animals/NNS are/VBP more/RBR equal/JJ than/IN others/NNS ./.' print(pos_sent) retval = str(get_words(pos_sent)) print("retval:", retval) gold = "All animals are equal , but some animals are more equal than others ." assert retval == gold, "test Fail:\n {} != {}".format(retval, gold) print("Pass") def test_get_noun_phrases(): """ Tests get_noun_phrases(). Do not modify this function. :return: """ print("\nTesting get_noun_phrases() ...") pos_sent = 'All/DT animals/NNS are/VBP equal/JJ ,/, but/CC some/DT ' \ 'animals/NNS are/VBP more/RBR equal/JJ than/IN others/NNS ./.' print("input:", pos_sent) retval = str(get_noun_phrase(pos_sent)) print("retval:", retval) gold = "['All animals', 'some animals', 'others']" assert retval == gold, "test Fail:\n {} != {}".format(retval, gold) print("Pass") def test_most_freq_noun_phrase(infile="fables-pos.txt"): """ Tests get_noun_phrases(). Do not modify this function. :return: """ print("\nTesting most_freq_noun_phrase() ...") import os if os.path.exists(infile): noun_phrase = most_freq_noun_phrase(infile, False) gold = "[('the donkey', 6), ('the mule', 3), ('load', 2)]" retval = str(noun_phrase[7]) print("gold:\t", gold) print("retval:\t", retval) assert retval == gold, "test Fail:\n {} != {}".format(noun_phrase[7], gold) print("Pass") else: print("Test fail: path does not exist;", infile) def run_tests(): test_get_words() test_get_noun_phrases() test_most_freq_noun_phrase() if __name__ == '__main__': # comment this out if you dont want to run the tests run_tests() parser = argparse.ArgumentParser(description='Assignment 2') parser.add_argument('-i', dest="pos_sent_fname", default="fables-pos.txt", help='File name that contant the POS.') args = parser.parse_args() pos_sent_fname = args.pos_sent_fname most_freq_noun_phrase(pos_sent_fname)
cdd8c8bd7cba0071a6e90c172806eff671e2f0c7
FlorianMerchieG1/PySoli
/Game/column.py
2,281
3.921875
4
from Game.card import * class Column: def __init__(self, number): # Number of remaining cards to draw self.nb_todraw = number+1 # List of cards of the column self.cards = [] def need_reveal(self): """ Checks if a new card needs to be revealed """ return (not self.cards) and (self.nb_todraw > 0) def is_empty(self): """ Checks if a column is fully empty. """ return (not self.cards) and (self.nb_todraw == 0) def same_color(self, card1, card2): """ Checks if two cards have the same color :param card1: (Card) first card :param card2: (Card) second card """ if (card1.color in REDS and card2.color in REDS): return True if (card1.color in BLACKS and card2.color in BLACKS): return True return False def can_add(self, card): """ Checks if a given card can be added to the column :param card: (Card) card to add """ if not self.cards: if card.rank == KING: return True else : return False top_card = self.cards[-1] if card.rank != top_card.rank-1: return False if self.same_color(top_card, card): return False return True def can_remove(self, number): """ Checks if a given number of cards can be removed from the column :param number: (int) the number of cards to remove """ return len(self.cards) >= number def add_cards(self, cards): """ Add a list of cards to the column :param cards: (list (Card)) the list of cards to add """ for card in cards: self.cards.append(card) def reveal_card(self, card): """ Reveals a new card in the column :param card: (Card) the card to reveal """ self.nb_todraw -= 1 self.add_cards([card]) def remove_cards(self, number): """ Removes a given number of cards from the column :param number: (int) the number of cards to remove """ cards = [] for i in range(number): cards.append(self.cards.pop()) cards.reverse() return cards
1b7a53d710aa01239f86eef1982d2ce700534e70
ccomings/hft-coding-challenges
/2018-11-07/gregori-combinations.py
311
3.671875
4
#!/usr/bin/env python import itertools def myfunc(lst): ret = [] arr = list(itertools.combinations(lst, 3)) for (x,y,z) in arr: if x+y+z == 0: ret.append((x,y,z)) return ret def main(): print myfunc([-1, 0, 1, 2, -1, -4]) if __name__ == '__main__': main()
c535cd2400a2b9518b2ee3238c3e2c802ef1d743
sixcy/python-belote
/cards.py
1,574
3.65625
4
from enum import Enum, unique from typing import List, Optional from utils import * from collections import namedtuple import random @unique class Color(Enum): CLUBS, DIAMONDS, HEARTS, SPADES = range(4) @unique class Rank(Enum): ACE, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING = range(8) class Card: def __init__(self, color: Color, rank: Rank) -> None: self.color = color self.rank = rank def __str__(self) -> str: return "(" + str(self.color) + ", " + str(self.rank) + ")" class ListCards: def __init__(self, cards: List[Card] = []) -> None: self.cards = cards.copy() def __str__(self) -> str: return list_str(self.cards) class Deck(ListCards): def __init__(self, cards: List[Card] = []) -> None: ListCards.__init__(self, cards) self.topcard : Optional[Card] = None def draw(self) -> Card: self.topcard = None return self.cards.pop() def shuffle(self) -> None: random.shuffle(self.cards) def reveal(self) -> None: self.topcard = self.cards[-1] def __str__(self) -> str: return "{ \ncards: " + ListCards.__str__(self) + ", \ntopcard: " + str(self.topcard) + "}" class Hand(ListCards): def __init__(self, cards: List[Card] = []) -> None: ListCards.__init__(self, cards) def add(self, card: Card) -> None: self.cards.append(card) class Trick(ListCards): pass if __name__ == "__main__": card = Card(Color.CLUBS, Rank.ACE) print(card) card2 = Card(Color.HEARTS, Rank.TEN) card3 = Card(Color.DIAMONDS, Rank.TEN) deck = Deck([card, card2, card3]) print(deck)
05704bbf852031873f9a266f5f353c1fdbe7835d
JT4life/PythonRevisePractice
/armstrongNum.py
743
4.09375
4
#number of n digits which are equal to sum of nth power of digits #E.G 22 so 2^2 = 4 2^2 =4, 4+4=8 8 does not equal 22 thus not armstrong userEnter = input("Enter digits separated by commas to check if armstrong number") #123 def arm(userEnter): split = userEnter.split(',') print(split) size = len(split) print(size) newList = [] toString = "" for i in split: powered = int(i)**size newList.append(powered) print(newList) totalSum = sum(newList) print(totalSum) for i in split: toString+=i if totalSum == int(toString): print(totalSum, " Armstrong number = ", toString) else: print(totalSum, " Not Armstrong number ", toString) arm(userEnter)
074d56ab90f4b359944fcb5f5d173109b50ec4a8
charles-debug/learning_record
/94-函数的返回值.py
239
3.578125
4
# 用户付钱,返回烟 def buy(): return '烟' goods = buy() print(goods) """ return作用: 1.返回函数返回值 2.return会退出当前函数,导致return 后面的代码(函数体内部)不执行 """
e1d14dcc0eb855e5747fac99cce257925a31c726
GondorFu/Lintcode
/626.矩阵重叠/Solution.py
641
3.9375
4
# Definition for a point. # class Point: # def __init__(self, a=0, b=0): # self.x = a # self.y = b class Solution: # @param {Point} l1 top-left coordinate of first rectangle # @param {Point} r1 bottom-right coordinate of first rectangle # @param {Point} l2 top-left coordinate of second rectangle # @param {Point} r2 bottom-right coordinate of second rectangle # @return {boolean} true if they are overlap or false def doOverlap(self, l1, r1, l2, r2): # Write your code here if l2.x > r1.x or r2.y > l1.y or r2.x < l1.x or l2.y < r1.y: return False return True
b512a08ed2b0d775965d18eb33200106aa862df9
yugandharachavan272/PythonExercise
/Day1/Exe3.py
981
4.25
4
# Print as it is print "I will now count my chickens:" # print string with numerical operations result, in numerical operation first 30/6 then addition i.e. 25+5 print "Hens", 25+30/6 # string with numerical operations 100 - 75%4 => 100 - 3 = 97 print "Roosters", 100 - 25 * 3 % 4 # print as it is it print "Now I will count eggs:" # First go for % then / i.e. 3+2+1-5 + 2 - 0 +6 = 7 print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 # print string print "Is it true that 3+2 < 5 - 7?" # 5 < -2 => False print 3+2 < 5 - 7 # string with result i.e What is 3 + 2 ? 5 print "What is 3 + 2 ?", 3 + 2 # string with result i.e What is 5 - 7? 2 print "What is 5 - 7?", 5 - 7 # string as it is print "Oh, that's why it's False." # string as it is print "How about some more." # True print "Is it greater?", 5 > -2 # Extra Credit # 1. Comments # 4. Floating point is a number with base 10 having 15 places decimal points i.e 1.234 print "Float", 3.2 + 2.1 + 1 - 5 + 4.3 % 2 - 1 / 4 + 6
4cd49ab4d1482795096f65d5768fe221f35dcdea
jpignata/adventofcode
/2015/02/solve.py
682
3.59375
4
import sys import operator from collections import namedtuple from functools import reduce Box = namedtuple("Box", ["l", "w", "h"]) def sides(box): return [box.l * box.w, box.w * box.h, box.h * box.l] def area(box): return reduce(lambda x, y: (2 * y) + x, sides(box), 0) def volume(box): return reduce(operator.mul, [box.l, box.w, box.h], 1) def perimeter(box): return sum(sorted([box.l, box.w, box.h])[0:2]) * 2 lines = sys.stdin.readlines() boxes = [Box(*map(int, line.strip().split("x"))) for line in lines] print("Part 1:", sum([area(box) + min(sides((box))) for box in boxes])) print("Part 2:", sum([volume(box) + perimeter(box) for box in boxes]))
6303e684e3fa6f87d3102dcbe5415b36bfb6f118
pzar97/Design-2
/QueueusingStacks.py
2,444
4.3125
4
""" Queue using Stacks """ """ Time Complexity: Push: O(1) Pop: Amortized O(1) Top: Amortized O(1) Empty: O(1) """ class MyQueue: def __init__(self): """ Initialize your data structure here. """ # 2 stacks:s1 and s2 self.s1 = [] self.s2 = [] def push(self, x: int) -> None: """ Push element x to the back of queue. """ # append x to s1 self.s1.append(x) def pop(self) -> int: """ Removes the element from in front of queue and returns that element. """ # check if the stack is empty or not if (self.empty()): return None # check if s2 stack is empty or not if (len(self.s2) is 0): # check if s1 stack is empty or not if (len(self.s1) is not 0): # if s1 is not empty and s2 is empty # move the elements from s1 to s2 while len(self.s1) is not 0: self.s2.append(self.s1.pop()) # then pop the last element appended to s2 stack return self.s2.pop() else: # return the last element in s2 if s2 is not empty return self.s2.pop() def peek(self) -> int: """ Get the front element. """ # check if the stack is empty or not if (self.empty()): return None # check if s2 stack is empty or not if (len(self.s2) is 0): # check if s1 stack is empty or not if (len(self.s1) is not 0): # if s1 is not empty and s2 is empty # move the elements from s1 to s2 while len(self.s1) is not 0: self.s2.append(self.s1.pop()) # then return the last element appended to s2 return self.s2[-1] else: # return the last element appended to s2 when s2 is not empty return self.s2[-1] def empty(self) -> bool: """ Returns whether the queue is empty. """ # check if both s1 and s2 stacks are empty or not if len(self.s1) == 0 and len(self.s2) == 0: return True return False # Your MyQueue object will be instantiated and called as such: # obj = MyQueue() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.peek() # param_4 = obj.empty()
5b5cb24c19407b0d5282575f57276e748b971c07
XuTan/PAT
/Advanced/1046.Shortest Distance.py
2,004
4
4
""" 1046. Shortest Distance (20) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN, Yue The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits. Input Specification: Each input file contains one test case. For each case, the first line contains an integer N (in [3, 105]), followed by N integer distances D1 D2 ... DN, where Di is the distance between the i-th and the (i+1)-st exits, and DN is between the N-th and the 1st exits. All the numbers in a line are separated by a space. The second line gives a positive integer M (<=104), with M lines follow, each contains a pair of exit numbers, provided that the exits are numbered from 1 to N. It is guaranteed that the total round trip distance is no more than 107. Output Specification: For each test case, print your results in M lines, each contains the shortest distance between the corresponding given pair of exits. Sample Input: 5 1 2 4 14 9 3 1 3 2 5 4 1 Sample Output: 3 10 7 """ # TIMEOUT # -*-encoding:utf-8-*- # if __name__ == "__main__": # Ns = input().split(" ") # M = int(input()) # pwd = [int(i) for i in Ns[1:]] # case = [] # for i in range(M): # ii = [int(num) for num in input().split(" ")] # case.append(ii) # for c in case: # low = min(c[0], c[1]) - 1 # high = max(c[0], c[1]) - 1 # p1 = sum(pwd[low:high]) # p2 = sum(pwd[:low]) + sum(pwd[high:]) # print(min(p1, p2)) # -*-encoding:utf-8-*- if __name__ == "__main__": inputNL = [int(_) for _ in input().split(" ")] N = inputNL[0] NL = inputNL[1:] SUM = sum(NL) M = int(input()) for i in range(M): C1, C2 = [int(_) for _ in input().split(" ")] if C2 < C1: tmp = C1 C1 = C2 C2 = tmp dis1 = sum(NL[C1 - 1:C2 - 1]) dis2 = SUM - dis1 print(min(dis1, dis2))
fec820da55e0e79da647992007f67746013aab65
rh01/py-leetcode
/042-TrappingRainWater.py
1,171
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : ShenHengheng # @File : 042-TrappingRainWater.py # @Desc : # @Site: : https://leetcode.com/problems/trapping-rain-water/ """ Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. Example: ======== Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 """ class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ if not height: return 0 idx_stack = [] res, current = 0, 0 while current < len(height): while len(idx_stack) != 0 and height[current] > height[idx_stack[-1]]: top = idx_stack[-1] idx_stack.pop() if len(idx_stack)==0: break distance = current - idx_stack[-1] - 1 bound = min(height[current], height[idx_stack[-1]] )- height[top] res += distance * bound idx_stack.append(current) current += 1 return res
22a734f6039120982db28286f905b0ade38dabc8
Scott-S-Lin/Python_Programming_ChineseBook
/ch2/func_multi_ret.py
802
3.984375
4
#filename: func_multi_ret.py #funcion: declare functions, receiving a variable number of arguments, using the * #function: return multi result from the function def multi_variable(var1, var2, *others): print ("var1: %s" % var1) print ("var2: %s" % var2) print ("others: %s" % list(others)) multi_variable(483.5,450.7,350,410,420,410,320) #2015 university examination for medical school def return_multi(score1, score2, score3): if score1 >=450.7: school_a="NTU medical ok" if score2 >=443.5 : school_b ="yangmin medical" if score3 >=442: school_c= "chenkung medical" return school_a,school_b,school_c print("\nmulti-return from the function") ret_school = return_multi(483.5,443.5,446) for i in ret_school: if i: print("\t",i)
0d8f63291de52d70d1d0961d8abc2c2984ec7307
aureliewouy/AirBnB_clone
/tests/test_models/test_amenity.py
1,523
3.5625
4
#!/usr/bin/python3 """ Unittest for the Amenity class that inherit from BaseModel """ import unittest from models.amenity import Amenity from models.base_model import BaseModel class TestAmenity(unittest.TestCase): """ Tests for the Amenity class """ def setUp(self): """ To define instructions that will be executed before each test """ self.my_amenity = Amenity() def test_instance(self): """ Test the instance of the class """ self.assertIsInstance(self.my_amenity, Amenity) def test_inheritence(self): """ Test if the class inherit from BaseModel """ self.assertTrue(issubclass(Amenity, BaseModel)) def test_attr(self): """ Test the attributes """ self.assertTrue(hasattr(self.my_amenity, 'id')) self.assertTrue(hasattr(self.my_amenity, 'created_at')) self.assertTrue(hasattr(self.my_amenity, 'updated_at')) self.assertTrue(hasattr(self.my_amenity, 'name')) def test_name_type(self): """ Test the type of the attribute name """ self.assertIsInstance(self.my_amenity.name, str) def test_set_name(self): """ Test to set the name """ self.my_amenity.name = "???" self.assertEqual(self.my_amenity.name, "???") def tearDown(self): """ To define instructions that will be executed after each test """ del self.my_amenity
3e90e1d87ea1df03eecd2d8139a962d0e8bb238c
sairampandiri/python
/perfect_square.py
253
3.765625
4
#Given two numbers N,M.Find their product and check whether it is a perfect square a,b=map(int,input().split()) n=a*b if(n==0): print("yes") else: for i in range(0,n): if i*i==n: print("yes") break else: print("no")
f88112a63199bf1a25dce10bf426119c0a79b717
CrappyAlgorithm/Airgonomic_Backend
/control/led_handler.py
492
3.515625
4
## @package control.led_handler # @author Sebastian Steinmeyer # Handles the functionallity to turn a led on and off. import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) ## Turn on a led. # @param gpio the gpoi pin which should turn on. def open_window(gpio): GPIO.setup(gpio, GPIO.OUT) GPIO.output(gpio, GPIO.HIGH) ## Turn off a led. # @param gpio the gpoi pin which should turn off. def close_window(gpio): GPIO.setup(gpio, GPIO.OUT) GPIO.output(gpio, GPIO.LOW)
4e8315a1740f2ac825666fd2d0810bdba46ccc78
sidv/Assignments
/Rajaprasad/Day12-assignments/addition_of_all_num.py
427
4.15625
4
num = "1,2,3,4,5,6,7,8,9" print("______________Addition of all numbers __________________") sum = 0 numbers = num[0::2] print("numbers are " ,numbers) for i in numbers: x = int(i) sum = sum+x print("The sum is " ,sum) print("_____________Addition of all even numbers______________") even = num[2::4] print("the even numbers are" , even) sum = 0 for i in even: x = int(i) sum = sum+x print("The even sum is " , sum)
b64c689b772489d7e2891f7e1427858af57df1d4
ochaib/decision-tree-learning
/tree.py
1,164
3.765625
4
class TreeNode: treeNode = {} def __init__(self, value, attr=None, left=None, right=None): self.value = value self.attr = attr self.left = left self.right = right self.count = 0 def TreeNode(self): return {self.attr, self.value, self.left, self.right} def add_left_child(self, child): self.left = child def add_right_child(self, child): self.right = child @property def is_leaf(self): return (self.left is None) & (self.right is None) # Called on root tree node. def get_leaf_nodes(self): leaf_nodes = [] self._collect_leaf_nodes(self, leaf_nodes) return leaf_nodes def _collect_leaf_nodes(self, node, leaf_nodes): if node is not None: if node.is_leaf: leaf_nodes.append(node) self._collect_leaf_nodes(node.left, leaf_nodes) self._collect_leaf_nodes(node.right, leaf_nodes) def __str__(self): s = f"{self.attr} > {self.value}" if not self.is_leaf: s += f"\nL: {self.left}" s += f"\nR: {self.right}" return s
c740799f39f186ec0c03cb86bee4d3dde00c45b1
JerryHu1994/LeetCode-Practice
/Solutions/436-Find-Right-Interval/python.py
1,096
3.640625
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def findRightInterval(self, intervals): """ :type intervals: List[Interval] :rtype: List[int] """ index = {} for i, v in enumerate(intervals): index[v.start] = i sorted_int = sorted(intervals, key = lambda x: [x.start, x.end]) # sort by start l = len(sorted_int) ret = [] for i in intervals start, end = i.start, i.end left, right = 0, l-1 mid = (left + right)/2 # do binary search while left < right: if sorted_int[mid].start >= end: right = mid else: left = mid+1 mid = (left + right)/2 if mid == l-1 and sorted_int[mid].start < end: ret.append(-1) else: ret.append(index[sorted_int[mid].start]) return ret
a5620b62a3d865e10a0580dfac2c268c6675a952
skgitbrain/python
/lesson_6/Task_4_L6.py
1,510
4.0625
4
class Car: def __init__(self, name, color, speed, is_police=False): self.name = name self.color = color self.speed = speed self.is_police = is_police def go(self): print(f"Машина марки {self.name} поехала") def stop(self): print(f"Машина марки {self.name} остановилась") def turn(self, direction): self.direction = direction print(f"Машина марки {self.name} повернула {self.direction}") def show_speed(self): print(f"Скорость машины марки {self.name} составляет {self.speed}") class TownCar(Car): def __init__(self, name, color, speed, is_police): super().__init__(name, color, speed, is_police) def show_speed(self): if self.speed > 60: print(f"Машина марки {self.name} {self.color} цвета превысила допустимую скорость в 60 км/ч") class SportCar(Car): pass class WorkCar(Car): def __init__(self, name, color, speed, is_police): super().__init__(name, color, speed, is_police) def show_speed(self): if self.speed > 60: print(f"Машина марки {self.name} {self.color} цвета превысила допустимую скорость в 40 км/ч") class PoliceCar(Car): pass r = PoliceCar("bmw", "black", 70, True) r.go() r.stop() r.turn("Направо") r.show_speed()
ec6d81715d5dfefbe64189a56720c7265dc05d18
manojnaidu15498/mnset4
/p1.py
97
3.671875
4
s=input() char=0 word=1 for i in s: if(i==' '): continue char=char+1 print(char)
c6e17e3dcc83712b5f4773526d8f765c34f7dc7e
KeleiAzz/LeetCode
/Facebook/onsite/AddOperator.py
449
3.609375
4
# cache = {} def addOperator(nums, target): ''' Seems work, how to optimize? :param nums: :param target: :return: ''' if int(nums) == target or int(nums) == -target: return True for i in range(1, len(nums)): subnum = int(nums[:i]) if addOperator(nums[i:], target - subnum) or addOperator(nums[i:], target + subnum): return True return False print addOperator('43868643', 52)
ffd82004930ce855863fb34fc777360d98c12e61
bimri/learning-python
/chapter_7/slicing.py
474
3.9375
4
S = 'hello' print(S[::-1]) # Reversing items ''' With a negative stride, the meanings of the first two bounds are essentially reversed. ''' s = 'abcedfg' print(s[5:1:-1]) # Bounds roles differ '''slicing is equivalent to indexing with a slice object''' print('spam'[1:3]) # slicing syntax print('spam'[slice(1, 3)]) # Slice objs with inx syntax + object print('spam'[::-1]) print('spam'[slice(None, None, -1)])
2b01ae394ad42fbcd55168d20f1e7936bcb031f6
snowcity1231/python_learning
/variable/variable.py
579
3.703125
4
# -*- coding:utf8 -*- # Python变量类型 counter = 100 # 一个整型数 miles = 999.99 # 一个浮点数 name = "Maxsu" # 一个字符串 site_url = "http://www.google.com" # 一个字符串 print(counter) print(miles) print(name) print(site_url) # 多重赋值 print("---------多重赋值-------------") a = b = c = 1 aa = bb = cc = "Tom" print(a) print(b) print(c) print(aa + "," + bb + "," + cc) # 标准数据类型 # 1.数字 # 2.字符串 # 3.列表 # 4.元组 # 5.字典 print("-----------Python数字-----------") var1 = 20 var2 = 40 print(var1) print(var2)
a908c84a6522088980403e222d03b8399431ef91
IshanDindorkar/machine_learning
/taming_big_data_apache_spark/src/most-popular-superhero.py
1,350
3.703125
4
# Summary of codebase # max() - find out row with maximum key value, lookup() - search for a specific key in RDD from pyspark import SparkConf, SparkContext def count_occurences(line): fields = line.split() return (fields[0], len(fields) - 1) def get_superhero_details(line): fields = line.split("\"") return(int(fields[0]), fields[1].encode("utf-8")) conf = SparkConf().setMaster("local").setAppName("Most Popular Super Hero") spark_context = SparkContext(conf = conf) # Loading marvel graph file marvel_graph = spark_context.textFile("file:///C:/my_workspace/taming_big_data_apache_spark/data/Marvel-Graph.txt") occurences_rdd = marvel_graph.map(count_occurences) # Aggregating total occurrences of superheros occurences_aggregated_rdd = occurences_rdd.reduceByKey(lambda x,y: x + y) occurences_flipped_rdd = occurences_aggregated_rdd.map(lambda x: (x[1], x[0])) # Finding out superhero who made maximum appearance max_occurence = occurences_flipped_rdd.max() print(max_occurence) # Loading details of superheros marvel_superheros = spark_context.textFile("file:///C:/my_workspace/taming_big_data_apache_spark/data/Marvel-Names.txt") marvel_superheros_rdd = marvel_superheros.map(get_superhero_details) most_popular_superhero = str(marvel_superheros_rdd.lookup(int(max_occurence[1]))[0]) print(most_popular_superhero)
57f6f3c3d9b3f5636b9d55486ee9beb3f3674716
joselynzhao/Python-data-structure-and-algorithm
/leecode/20060401.py
1,485
3.703125
4
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:zhaojing17@foxmail.com @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:20060401.py @TIME:2020/6/4 20:48 @DES: 回文数 : 已解除,但时间超出限制,需要动态规划 ''' def longestPalindrome( s: str) -> str: # 先考虑极端情况 lens = len(s) if lens == 1: return s[0] if lens == 0: return '' if lens == 2: if s[0] == s[1]: return s else: return s[0] max_len, max_char = 1, s[0] for i in range(lens - 1): for j in range(i+2, lens+1): curr_s = s[i:j] if len(curr_s) == 2: if curr_s[0] == curr_s[1]: if max_len < 2: max_len = 2 max_char = curr_s else: huiwen = ishuiwen(curr_s) if huiwen == 0: continue elif huiwen == -1: return "huiwen==-1,error" else: if huiwen > max_len: max_len = huiwen max_char = curr_s return max_char def ishuiwen(s): lens = len(s) if lens >= 2: for i in range(int(lens / 2)): if s[i] == s[lens - 1 - i]: continue else: return 0 # 不是回文数 return lens return -1 # error print(longestPalindrome("abb"))
56b763228051633b678ef7b8d7049c5bcd60a05a
itsolutionscorp/AutoStyle-Clustering
/intervention/results/control_120722_1449534232_525_11.08.py
232
3.84375
4
def num_common_letters(goal_word, guess): count = 0 used = list() for letter in goal_word: if letter in guess and letter not in used: count += 1 used += letter return count
ece8a6ae9affacb618703981a4fb364642ef0fcc
chasezimmy/fun
/python/sum_of_left_leaves.py
735
4.15625
4
""" Find the sum of all left leaves in a given binary tree. Example: 5 / \ 3 7 / \ / .2 4 .6 sum: 8 (2+6) """ class Node: def __init__(self, val): self.val = val self.left = None self.right = None def sum_of_leaves(root): sum_of_leaves.sum = 0 def __(root, is_left=False): if not root: return if is_left and not root.left and not root.right: sum_of_leaves.sum += root.val __(root.left, True) __(root.right) __(root) return sum_of_leaves.sum root = Node(5) root.left = Node(3) root.left.left = Node(2) root.left.right = Node(4) root.right = Node(7) root.right.left = Node(6) print(sum_of_leaves(root))
bb1bf54096d780204fe882811d5ea2f54a6de3fe
Ankur-v-2004/Class-12-ch-1-python-basics
/prog_list_opertn.py
411
4.125
4
#Program to show the outputs based on entered list. my_list = ['p','r','o','b','e'] # Output: p print(my_list[0]) # Output: o print(my_list[2]) # Output: e print(my_list[4]) # Error! Only integer can be used for indexing # my_list[4.0] # Nested List n_list = ["Happy", [2,0,1,5]] # Nested indexing # Output: a print(n_list[0][1],n_list[0][2],n_list[0][3]) # Output: 5 print(n_list[1][3])
f1d6eca058cea46fde250faa411a3369a7e072e5
NiCrook/Edabit_Exercises
/60-69/61.py
700
3.828125
4
# https://edabit.com/challenge/baBNZFCozmjNhbp9Q # Create a function that takes a number (step) as an argument # and returns the amount of boxes in that step of the sequence. # Step 0: Start with 0 # Step 1: Add 3 # Step 2: Subtract 1 # Repeat Step 1 & 2 ... def box_seq(steps: int) -> int: steps_taken = 0 boxes = 0 while steps_taken != steps + 1: if steps_taken == 0: steps_taken += 1 elif steps_taken % 2 != 0: steps_taken += 1 boxes += 3 elif steps_taken % 2 == 0: steps_taken += 1 boxes -= 1 return boxes print(box_seq(0)) print(box_seq(1)) print(box_seq(2)) print(box_seq(3))
83069810a496224e7e546e6388b3e78fbfa4316f
pratik-1999/Solved-Problems
/has_pair.py
833
3.859375
4
def has_pair(array, req_sum): array.sort() low, high = 0, len(array)-1 while low<high: ar_high = array[high] ar_low = array[low] cur_sum = ar_high+ar_low if cur_sum == req_sum: return (ar_low, ar_high) elif cur_sum>req_sum: high -= 1 elif cur_sum<req_sum: low += 1 return False def has_pair2(array, req_sum): comps = {} all_pairs = [] for num in array: complement = req_sum-num keys = comps.keys() values = comps.values() if num not in keys: if num in values: all_pairs.append((num, complement)) comps[num] = complement return all_pairs if __name__=="__main__": a = [1,5,8,6,3,45,9,7] print(has_pair2(a, 9))
4110b8629b2c7b32dd8fcc51510dee5b8852fa6f
antongoy/DL
/Assignment1/src/layers.py
9,070
3.609375
4
#!/usr/bin/python # -*- coding: utf-8 -*- # Implementation of layers used within neural networks from __future__ import print_function from __future__ import division import numpy as np class BaseLayer(object): def get_params_number(self): """ :return num_params: number of parameters used in layer """ raise NotImplementedError('This function must be implemented within child class!') def get_weights(self): """ :return w: current layer weights as a numpy one-dimensional vector """ raise NotImplementedError('This function must be implemented within child class!') def set_weights(self, w): """ Takes weights as a one-dimensional numpy vector and assign them to layer parameters in convenient shape, e.g. matrix shape for fully-connected layer :param w: layer weights as a numpy one-dimensional vector """ raise NotImplementedError('This function must be implemented within child class!') def set_direction(self, p): """ Takes direction vector as a one-dimensional numpy vector and assign it to layer parameters direction vector in convenient shape, e.g. matrix shape for fully-connected layer :param p: layer parameters direction vector, numpy vector """ raise NotImplementedError('This function must be implemented within child class!') def forward(self, inputs): """ Forward propagation for layer. Intermediate results are saved within layer parameters. :param inputs: input batch, numpy matrix of size num_inputs x num_objects :return outputs: layer activations, numpy matrix of size num_outputs x num_objects """ raise NotImplementedError('This function must be implemented within child class!') def backward(self, derivs): """ Backward propagation for layer. Intermediate results are saved within layer parameters. :param derivs: loss derivatives w.r.t. layer outputs, numpy matrix of size num_outputs x num_objects :return input_derivs: loss derivatives w.r.t. layer inputs, numpy matrix of size num_inputs x num_objects :return w_derivs: loss derivatives w.r.t. layer parameters, numpy vector of length num_params """ raise NotImplementedError('This function must be implemented within child class!') def Rp_forward(self, Rp_inputs): """ Rp forward propagation for layer. Intermediate results are saved within layer parameters. :param Rp_inputs: Rp input batch, numpy matrix of size num_inputs x num_objects :return Rp_outputs: Rp layer activations, numpy matrix of size num_outputs x num_objects """ raise NotImplementedError('This function must be implemented within child class!') def Rp_backward(self, Rp_derivs): """ Rp backward propagation for layer. :param Rp_derivs: loss Rp derivatives w.r.t. layer outputs, numpy matrix of size num_outputs x num_objects :return input_Rp_derivs: loss Rp derivatives w.r.t. layer inputs, numpy matrix of size num_inputs x num_objects :return w_Rp_derivs: loss Rp derivatives w.r.t. layer parameters, numpy vector of length num_params """ raise NotImplementedError('This function must be implemented within child class!') def get_activations(self): """ :return outputs: activations computed in forward pass, numpy matrix of size num_outputs x num_objects """ raise NotImplementedError('This function must be implemented within child class!') class FCLayer(BaseLayer): def __init__(self, shape, afun, use_bias=False): """ :param shape: layer shape, a tuple (num_inputs, num_outputs) :param afun: layer activation function, instance of BaseActivationFunction :param use_bias: flag for using bias parameters """ self.shape = shape self.num_inputs = shape[0] self.num_outputs = shape[1] self.activation_func = afun self.use_bias = use_bias def get_params_number(self): num_params = self.num_outputs * self.num_inputs if self.use_bias: num_params += self.num_outputs return num_params def get_weights(self): return np.ravel(self.W) def set_weights(self, w): num_params = self.get_params_number() if w.shape[0] != num_params: raise ValueError('Invalid number of the layer parameters') if self.use_bias: self.W = w.reshape((self.num_outputs, self.num_inputs + 1)) else: self.W = w.reshape((self.num_outputs, self.num_inputs)) def set_direction(self, p): num_params = self.get_params_number() if p.shape[0] != num_params: raise ValueError('Invalid number of the layer parameters') if self.use_bias: self.P = p.reshape((self.num_outputs, self.num_inputs + 1)) else: self.P = p.reshape((self.num_outputs, self.num_inputs)) def forward(self, inputs): if inputs.shape[0] != self.num_inputs: raise ValueError('Size of the batch does not correspond to size of the layer') # W --> (num_outputs x num_inputs), b --> (num_outputs x 1) # logits --> (num_outputs x num_objects) # inputs --> (num_inputs x num_objects) if self.use_bias: self.inputs = np.vstack((inputs, np.ones(inputs.shape[1]))) else: self.inputs = inputs self.logits = np.dot(self.W, self.inputs) return self.activation_func.val(self.logits) def backward(self, derivs): if derivs.shape[0] != self.num_outputs: raise ValueError('Size of the derivatives does not correspond to output size of the layer') # derivs --> (num_outputs x num_objects) self.derivs = derivs self.derivs_wrt_logits = self.derivs * self.activation_func.deriv(self.logits) self.derivs_wrt_inputs = np.dot(self.W.T, self.derivs_wrt_logits) if self.use_bias: self.derivs_wrt_inputs = self.derivs_wrt_inputs[:-1, :] self.derivs_wrt_W = np.dot(self.derivs_wrt_logits, self.inputs.T) / self.inputs.shape[1] return self.derivs_wrt_inputs, np.ravel(self.derivs_wrt_W) def Rp_forward(self, Rp_inputs): if Rp_inputs.shape[0] != self.num_inputs: raise ValueError('Size of `Rp_inputs` does not correspond to the number of layer inputs') # Rp_inputs --> (num_inputs x num_objects) if self.use_bias: self.Rp_inputs = np.vstack((Rp_inputs, np.zeros(Rp_inputs.shape[1]))) else: self.Rp_inputs = Rp_inputs self.Rp_logits = np.dot(self.W, self.Rp_inputs) + np.dot(self.P, self.inputs) return self.activation_func.deriv(self.logits) * self.Rp_logits def Rp_backward(self, Rp_derivs): if Rp_derivs.shape[0] != self.num_outputs: raise ValueError('Size of `Rp_outputs` does not correspond to the number of layer outputs') Rp_derivs_wrt_logits = Rp_derivs * self.activation_func.deriv(self.logits) + \ self.derivs * self.activation_func.second_deriv(self.logits) * self.Rp_logits Rp_derivs_wrt_inputs = np.dot(self.P.T, self.derivs_wrt_logits) + np.dot(self.W.T, Rp_derivs_wrt_logits) if self.use_bias: Rp_derivs_wrt_inputs = Rp_derivs_wrt_inputs[:-1, :] Rp_derivs_wrt_W = np.dot(Rp_derivs_wrt_logits, self.inputs.T) + np.dot(self.derivs_wrt_logits, self.Rp_inputs.T) Rp_derivs_wrt_W /= self.inputs.shape[1] return Rp_derivs_wrt_inputs, np.ravel(Rp_derivs_wrt_W) def get_activations(self): return self.activation_func.val(self.logits) if __name__ == '__main__': from activations import SigmoidActivationFunction print('>>> Testing basic functionality...') num_inputs = 1000 num_outputs = 100 num_objects = 50 layer = FCLayer(shape=(num_inputs, num_outputs), afun=SigmoidActivationFunction(), use_bias=True) layer.set_weights(np.random.normal(size=(num_inputs + 1) * num_outputs)) layer.set_direction(np.random.normal(size=(num_inputs + 1) * num_outputs)) batch = np.random.normal(size=(num_inputs, num_objects)) outputs = layer.forward(batch) derivs_wrt_outputs = np.random.normal(size=(num_outputs, num_objects)) derivs_wrt_inputs, derivs_wrt_weights = layer.backward(derivs_wrt_outputs) Rp_inputs = np.random.normal(size=(num_inputs, num_objects)) Rp_ouputs = layer.Rp_forward(Rp_inputs) Rp_derivs_wrt_outputs = np.random.normal(size=(num_outputs, num_objects)) Rp_derivs_wrt_inputs, Rp_derivs_wrt_weights = layer.Rp_backward(Rp_derivs_wrt_outputs)
6b0959289acfc6646e08d175f185d3c138a284ef
anurao5/Python-coding-practice
/Class_AgeComparison.py
707
3.828125
4
class Person: def __init__(self,initialAge): #Initialize the age if initialAge < 0: self.initialAge = 0 print("Age is not valid, setting age to 0") else: self.initialAge = initialAge def amIOld(self): #Check the person's age if self.initialAge < 13: print("You are young") elif self.initialAge in range(13, 19): print("You are a teenager") else: print("You are old") def yearPasses(self): #Increment age by 1 if a year passes self.initialAge = self.initialAge + 1 person1 = Person(20) person1.amIOld() person1.yearPasses()
70a0c31ed587a831ab31b7e554cca516b45283dd
MrSyee/algorithm_practice
/dp/pelindrome_partioning_4.py
1,701
3.828125
4
""" 1745. Palindrome Partitioning IV (Hard) https://leetcode.com/problems/palindrome-partitioning-iv/ Given a string s, return true if it is possible to split the string s into three non-empty palindromic substrings. Otherwise, return false.​​​​​ A string is said to be palindrome if it the same string when reversed. Example 1: Input: s = "abcbdd" Output: true Explanation: "abcbdd" = "a" + "bcb" + "dd", and all three substrings are palindromes. Example 2: Input: s = "bcbddxy" Output: false Explanation: s cannot be split into 3 palindromes. Constraints: 3 <= s.length <= 2000 s​​​​​​ consists only of lowercase English letters. """ # T_C: O(N^2) # S_C: O(N^2) class Solution: def checkPartitioning(self, s: str) -> bool: # O(N). len(s)^2 만큼의 배열 생성 is_palindrome = [] for _ in range(len(s)): is_palindrome.append([False for _ in range(len(s))]) # O(N). len 1, 2 pelindrome 여부 체크 for i in range(len(s)): is_palindrome[i][i] = True if i < len(s)- 1 and s[i] == s[i+1]: is_palindrome[i][i+1] = True # O(N^2). len >= 3 pelindrome 여부 체크 for i in range(2, len(s)): for j in range(len(s) - i): if s[j] == s[j+i] and is_palindrome[j+1][j+i-1]: is_palindrome[j][j+i] = True # O(N^2). 문자열 분리 위치 찾기 for i in range(0, len(s)-2): for j in range(1, len(s) - 1): if is_palindrome[0][i] and is_palindrome[i+1][j] and is_palindrome[j+1][len(s)-1]: return True return False
64f6c99cfd8b73e42ec700fb6d5edec6baa4a38f
jnizama/practicePython
/DecimalToBinary.py
528
3.9375
4
binaryNumber = [] def convertToBinary(iNumber:int): resto = round(iNumber%2); binaryNumber.append(resto) iNumber = int(iNumber/2) if(iNumber > 1): convertToBinary(iNumber) else: binaryNumber.append(iNumber) #for x in range(iNumber, 0,-1): # print(x) binaryNumber.reverse() print("Conversion Decimal to Binary") iNumber = input("Enter the number") TheNumber = int(iNumber) convertToBinary(TheNumber) print(binaryNumber); #print(str(int(5/2)));
068fe21cac258d1c697fd5cb508a2cc7ecbefa95
samadabbagh/sama-mft
/mft-first-section/five-section.py
207
4.1875
4
number = int(input("enter your number number")) i = 0 number_final = 0 while i < number : i = i+1 number_final = number_final +(1 /i**2) print(number_final) pi =( 6 * number_final)**0.5 print(pi)
3d125a3db25023a22e37dd3b833e19ad1cad43af
caynan/ProgrammingContests
/checkio/count_inversions.py
1,050
4.125
4
def sort_count(arr): l = len(arr) if l > 1: mid = l // 2 l_half, l_count = sort_count(arr[:mid]) r_half, r_count = sort_count(arr[mid:]) sorted_arr, m_count = merge_count(l_half, r_half) return sorted_arr, (l_count + r_count + m_count) else: return arr, 0 def merge_count(l_half, r_half): count = 0 merged = [] while l_half and r_half: if l_half[0] <= r_half[0]: merged.append(l_half.pop(0)) else: merged.append(r_half.pop(0)) count += len(l_half) merged += l_half + r_half return merged, count def count_inversion(arr): return sort_count(list(arr))[1] if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3, "Example" assert count_inversion((0, 1, 2, 3)) == 0, "Sorted" assert count_inversion((99, -99)) == 1, "Two numbers" assert count_inversion((5, 3, 2, 1, 0)) == 10, "Reversed"
64518f20dd75f350441e8f8fb488a20e6041aad9
recyan19/num_to_words
/nums_to_words_v1.py
2,020
3.609375
4
#!/usr/bin/python3 import re import inflect def solve(s): p = inflect.engine() nums = '01234567890' signs = '+-*/= ' allowed_chars = nums + signs verbose_signs = {'+': 'plus', '-': 'minus', '*': 'multiple by', '/': 'divide by', '=': 'equals'} if any(i not in allowed_chars for i in s): return "invalid input" if '=' not in s or not any(i in '+-*/' for i in s): return "invalid input" s = s.strip() s = ''.join(s.split()) result = '' tmp = '' for i, v in enumerate(s): if v in nums: tmp += v if i == len(s) - 1: result += p.number_to_words(tmp) else: try: result += p.number_to_words(tmp) + ' ' + verbose_signs[v] + ' ' except IndexError: result += verbose_signs[v] + ' ' else: tmp = '' is_result_true = eval(s.replace('=', '==')) #return result, s, True if is_result_true else False return result class TestClass: def test_simple(self): eq = '3 + 7 = 10' assert solve(eq) == 'three plus seven equals ten' def test_minus_or_plus_first(self): eq1 = '-73 + 70= -3' eq2 = '+73 + 70= -3' assert solve(eq1) == 'minus seventy-three plus seventy equals minus three' assert solve(eq2) == 'plus seventy-three plus seventy equals minus three' def test_multiple_values_before_and_after_equal_sign(self): eq = '12 - 6 = 18 / 3' assert solve(eq) == 'twelve minus six equals eighteen divide by three' def test_multiple_spaces(self): eq = '12 + 7= 19' assert solve(eq) == 'twelve plus seven equals nineteen' def test_invalid_input(self): eq1 = '12 + 2k = 45.' eq2 = '12 + 45 34' eq3 = '12 = 12' assert all(solve(e) == 'invalid input' for e in [eq1, eq2, eq3]) if __name__ == "__main__": equation = input("Enter the equation: ") print(solve(equation))
0553c03a0e68efcff2f06503a63343558e67f07e
na-liu/pythonExercise
/demo/demoTuple.py
919
4.0625
4
# tuple 表示 tup = () # 空元组 tup1 = (1, 2, 3, 4) tup2 = (1) # 括号中是单个元素时,括号会被认为是运算符号,表示整型 print('type(tup1):', type(tup1)) # type(tup1): <class 'tuple'> print('type(tup2):', type(tup2)) # type(tup1): <class 'int'> # 访问元组 print('tup1[0]:', tup1[0]) # tup1[0]: 1 print('tup1[-1]:', tup1[-1]) # tup1[-1]: 4 print('tup1[1:3]', tup1[1:3]) # tup1[1:3] (2, 3) # 修改元组,非法 # tup1[0] = 8 # 会提示你将tuple转化为list # 删除元组 del tup1 # print(tup1) # name 'tup1' is not defined del tup tup = (1, 2, 3, 4, 5, 6, 7, 8) # 运算符 print('长度:', len(tup)) # 8 print('拼接:', tup + (1, 2, 3)) # 拼接: (1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3) print('复制:', ('hi',) * 2) print('存在检验:', 'a' in ('a', 'b', 'c')) # 迭代 for x in (1, 2, 3): print(x, end='') # max min len tuple(list):将tuple转化为list
88f8fc6e5c3014142e5fa2bad468a779cb26bc88
wangxiao2663/learning
/my_learning_python/yield/yield.py
242
3.609375
4
def f(): print "Before first yield" yield 1 print "Before second yield" yield 2 print "After third yield" g = f() print "Before first next" g.next() print "Before second next" g.next() print "Before third yield" g.next()
898d0cd6746fadcca9e603bc8806449d7c2ffb80
ericchen12377/Leetcode-Algorithm-Python
/1stRound/Medium/286-Walls and Gates/DFS.py
953
3.59375
4
class Solution(object): def wallsAndGates(self, matrix): """ :type rooms: List[List[int]] :rtype: None Do not return anything, modify rooms in-place instead. """ wall = -1 gate = 0 empty = 2147483647 directions = [[-1,0], [0,1], [1,0], [0,-1]] def dfs(matrix, row, col, curStep): if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0]) or curStep > matrix[row][col]: return matrix[row][col] = curStep for i in range(len(directions)): curDir = directions[i] dfs(matrix, row + curDir[0], col + curDir[1], curStep + 1) for row in range(len(matrix)): for col in range(len(matrix[0])): if matrix[row][col] == gate: dfs(matrix, row, col, 0)
91d278a8b16c3f22c70ebe829b8662088cb79f95
Maryville-SWDV-630/ip-1-kylekanderson
/Assignment.py
1,068
4.09375
4
# SWDV-630: Object-Oriented Coding # Kyle Anderson # Week 1 Assignment # Using Thonny, Visual Studio or command line interface expand on the Teams class defined as: class Teams: def __init__(self, members): self.__myTeam = members def __len__(self): return len(self.__myTeam) # 1) Add the __contains__ protocol and show whether or not 'Tim' and 'Sam' are part of our team. def __contains__(self, member): return member in self.__myTeam # 2) Add the __iter__ protocol and show how you can print each member of the classmates object. def __iter__(self): return iter(self.__myTeam) # 3) Determine if the class classmates implements the __len__ method. def hasLen(self): return hasattr(self, '__len__') def main(): classmates = Teams(['John', 'Steve', 'Tim']) print(len(classmates)) print(classmates.__contains__('Tim')) print(classmates.__contains__('Sam')) for classmate in classmates: print(classmate) print(classmates.hasLen()) main()
f3d9ee7eb3d99299457dc11aef9ec09c6435dce0
kathferreira/python-programming-data-science-numPy
/excercises/11_excercise_arange.py
321
4.0625
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 2 11:30:29 2021 @author: kferreip Excercise 11 Using numpy create a one dimensional array of all two-digit numbers and print this array to the console. Tip: Use the np.arange() function """ import numpy as np two_digit_arr = np.arange(10,100,1) print(two_digit_arr)
5c189c84739502959f1fb7a896ce4361364d4543
gosyang/leetcode
/Algorithms/tree/563.Binary_Tree_Tilt/binary_tree_tilt.py
1,815
3.640625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- ######################################################################## # # Copyright (c) 2017 gosyang. All Rights Reserved # ######################################################################## """ File: binary_tree_tilt.py Author: gosyang Date: 2017/05/25 10:24:38 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sumOfRoot(self, root): """ Sum val of root tree 这种solution 重复计算了 子树的和, 应该两个递归一起搞 :type root: TreeNode :rtype: int """ if root is None: return 0 return self.sumOfRoot(root.left) + self.sumOfRoot(root.right) + root.val def sumAndTilt(self, root): """ Sum val of root tree and tilt at same time :type root: TreeNode :rtype: int(sum), int(tilt) """ if root is None: return 0, 0 left_sum, left_tilt = self.sumAndTilt(root.left) right_sum, right_tilt = self.sumAndTilt(root.right) return left_sum + root.val + right_sum, abs(left_sum - right_sum) + left_tilt + right_tilt def findTilt(self, root): """ :type root: TreeNode :rtype: int """ # 用 sumOfRoot 递归, 耗时1000ms以上 # if root is None: # return 0 # return self.findTilt(root.left) + self.findTilt(root.right) \ # + abs(self.sumOfRoot(root.left) - self.sumOfRoot(root.right)) # 用一次递归 return self.sumAndTilt(root)[1]
459112c5ea9ceca9483053e0a25afd035705e923
vutran1412/CapstoneLab1
/camelCase.py
1,400
4.5
4
# Camel Casing Program # Author: Vu Tran # Function to turn a sentence user entered into a camel cased sentence def camel_case(user_string): # Initialize a new list new_list = [] # Initialize a new string new_sentence = "" # Splits the user sentence and saves the individual words into a list string_list = user_string.split() # Loop over the string_list and capitalize the entire word of every odd index for i in range(len(string_list)): # If index is even push everything to lower case if i % 2 == 0: # Append the newly lowered or all capped words into a list new_list.append(string_list[i].lower()) # Else make everything upper case else: new_list.append(string_list[i].upper()) # Iterate through the list and concatenate all the words to the new sentence for word in new_list: new_sentence += word # Return the new sentence return new_sentence def display_banner(): '''Display program name in a banner''' msg = 'AWESOME camelCaseGenerator PROGRAM' stars = '*' * len(msg) print('\n', stars, '\n', msg, '\n', stars, '\n') def main(): # Asks user to input a sentence user_input = input("Enter a sentence\n") # Function call and save to a new string joined_string = camel_case(user_input) # Output print(joined_string) main()
f7c83f90e6999d1a2a08029f4a0ce07495ca0662
GitZW/LeetCode
/leetcode/editor/cn/day_024.py
1,800
4.25
4
""" Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one. Example 1: Given tree [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 return true. Example 2: Given [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 return false. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/check-balance-lcci """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def get_depth(self, root): if not root: return 0 depth = max(self.get_depth(root.right), self.get_depth(root.left)) return depth + 1 def isBalanced(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True if not self.isBalanced(root.left): return False if not self.isBalanced(root.right): return False if abs(self.get_depth(root.right) - self.get_depth(root.left)) > 1: return False return True class Solution2: def IsBalanced_Solution(self, pRoot): if not pRoot: return True if self.DeepTree(pRoot) == -1: return False else: return True def DeepTree(self, pRoot): if not pRoot: return 0 left = self.DeepTree(pRoot.left) right = self.DeepTree(pRoot.right) if left == -1 or right == -1 or abs(left - right) > 1: return -1 return 1 + max(left, right)
b1a55f3689c10dce0ecac0c82d6a1e7472bfc31b
mikhalevv/Poisk_glasnykh
/Poisk_glasnykh final.py
247
3.5625
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 6 17:52:27 2018 @author: mihalev """ s = str(input()) y = list(s) z = s.count('a') + s.count('e') + s.count('i') + s.count('o') + s.count('u') + s.count('y') print('Number of vowels: ' + str(z))
10f2cc80d44941a24f64b4ad63e7cebe3bea7d99
fuburning/lstm_intent
/tensorgou/utils/txtutils.py
1,291
3.53125
4
""" """ import re, string import unicodedata def cleanline(txt): return txt.strip('\n') def to_lowercase(text): return text.lower().strip() def remove_all_punctuations(text): regex = re.compile('[%s]' % re.escape(string.punctuation)) text = regex.sub(' ', text).strip() return " ".join(text.split()).strip() def remove_basic_punctuations(text): text = text.replace('.','') text = text.replace(',','') text = text.replace('?','') text = text.replace('!','') text = text.replace(';','') text = text.replace('-',' ') return text.strip() def remove_spaced_single_punctuations(text): wds = text.split() return " ".join([w for w in wds if len(w)>1 or re.compile('[%s]' % re.escape(string.punctuation)).sub(' ', w).strip() != '']).strip() def space_out_punctuations(text): return re.sub(r"([\w\s]+|[^\w\s]+)\s*", r"\1 ", text).strip() def remove_numbers(text): return re.sub(r' \d+ ',' ', text).strip() def replace_numbers(text): return re.sub(r' \d+ ',' *#NUMBER#* ', text).strip() def replace_accents(text): text = text.decode('utf-8') text = unicodedata.normalize('NFD', text).encode('ascii', 'ignore') text = text.replace('-LRB-','(') text = text.replace('-RRB-',')') return text.strip()
4ea09a3b33528049580f83ac570841779fd1ca52
athiyamaanb/py_challenge
/scripts/play_tictactoe.py
1,528
3.9375
4
def check_complete(matrix): #complete_flag = False for row in matrix: first_element = row[0] if first_element != ' ': row_check = True for column in row: if first_element != column: row_check = False break if row_check: return True #if len(set(row)) == 1 and set(row) != ' ': # complete_flag = True #return complete_flag def print_current_state(matrix): for row in matrix: print('|'.join(row)) def insert_element(matrix, row, column, value): if matrix_board[row][column] == ' ': matrix[row][column] = value else: print('An element is already present in the given position!') return print_current_state(matrix) if __name__ == '__main__': matrix_board = [[' ',' ',' '],['0','0',' '], ['X','X','0']] print_current_state(matrix_board) player_sequence = ['p1','p1','p2'] played = [] print('Play Started.') for player in player_sequence: print('Player trying to play: ' + player) if len(played) >0 and played[-1] == player: print('Its not your turn!') pass else: print('Inserting element to the board...') insert_element(matrix_board, 1, 2,'0') played.append(player) print_current_state(matrix_board) if check_complete(matrix_board): print('Game Complete') else: print('Not Compelete')
11a67512fe2a34841fda57173b6ca56d1f7e1112
WashHolanda/Curso-Python
/exercicios_Prof/Semana 4/lista4-01.py
864
4.09375
4
''' 1) Faça um programa que leia o nome e nota da P1 de vários alunos guardando tudo em uma lista e no final mostre: a. Quantas alunos foram cadastradas b. O nome do aluno com maior nota c. O nome da pessoa menor nota d. O nota média da sala. ''' from operator import itemgetter op = ' ' p1 = [] aluno = {} média = 0 while op != 'N': aluno['nome'] = str(input('Nome: ')).title() aluno['nota'] = float(input('Nota 1: ')) média += aluno['nota'] p1.append(aluno.copy()) aluno.clear() op = str(input('Quer continuar [S/N]? ')).strip().upper()[0] print('-='*30) print(f'Foram cadastrados {len(p1)} alunos.') print(f'O aluno com a maior nota foi de {max(p1,key=itemgetter("nota"))["nome"]}') print(f'O aluno com a menor nota foi de {min(p1,key=itemgetter("nota"))["nome"]}') print(f'A nota média da sala foi {(média/len(p1)):.2f}')
13d44aa24b87dfc3abac3b05b92e2e7457e098e5
agomez0/python-challenge
/PyBank/main.py
2,027
3.953125
4
import os import csv csvpath = ('budget_data.csv') f = open("data.txt", "w") #Prints out to console and text file def outputPrint(text): f.write(text + "\n") print(text) with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #Skip the header row first csv_header = next(csvreader) profitlist = [] total = 0 previous_amt = 0 greatesti = 0 greatestd = 0 for row in csvreader: #Cast profit amount into an integer amount = int(row[1]) #Add up total profit for all months total = amount + total #Add profit from every month to a list profitlist.append(amount) #Change in profit current_change = amount - previous_amt #If the current change in profit is greater than the greatest increase so far then... if current_change > greatesti: #Current month becomes the one to hold the greatest increase greatesti = current_change gimonth = row[0] #If the current change in profit is less than the greatest decrease so far then... elif current_change < greatestd: #Current month becomes the one to hold the greatest decrease greatestd = current_change gdmonth = row[0] #stores profit amount of current row to find change in profit of the following month previous_amt = int(row[1]) #Subtracts the last profit value from the first avg_delta = profitlist[len(profitlist)-1] - profitlist[0] #Print to console and text file in an efficient way outputPrint("Financial Analysis") outputPrint("----------------------------") outputPrint(f"Total months: {len(profitlist)}") outputPrint(f"Total: ${total}") outputPrint(f"Average Change: ${round(avg_delta/(len(profitlist) - 1), 2)}") outputPrint(f"Greatest Increase in Profits: {gimonth} (${greatesti})") outputPrint(f"Greatest Decrease in Profits: {gdmonth} (${greatestd})")
4351c4da1ec4238f16b5699fe766094d97909784
Misael1998/generador-numeros-aleatorios
/main.py
1,548
3.71875
4
from cuadrado_medio import AleatorioMedio from congruencial import AleatorioCongruencial def main(): print('Numeros aleatorios\n') print('Seleccione el metodo de generacion de numeros alearorios') print('1.Cuadrado medio') print('2.Congruencial') metodo = int(input()) if metodo == 1: print('Selecciones los parametros para generar 50 numeros aleatorios') print('Semilla:') semilla = int(input()) print('Digitos significativos:') dgt = int(input()) alt = AleatorioMedio(semilla, dgt) s = [] for _ in range(50): s.append(alt.generar_numero_aleatorio()) print('Los numeros aleatorios generados son:') print(s) elif metodo == 2: print('Seleccione los parametros para generar 50 numeros aleatorios') print('Semilla:') semilla = int(input()) print('Multiplicador:') multiplicador = int(input()) print('Constante aditiva') constante_aditiva = int(input()) print('Modulo') modulo = int(input()) alt = AleatorioCongruencial(semilla, multiplicador, constante_aditiva, modulo) s = [] for _ in range(50): s.append(alt.generar_aleatorio()) cola, periodo = alt.obtener_cola_periodo() print('Los numeros aleatorios son:') print(s) print(f'La cola es: {cola} \nEl periodo es: {periodo}') else: print('La opcion seleccionada no es valida') if __name__ == "__main__": main()
5a97ae18e7319001e3eb66d4a7e55bc0f642fc48
xuefengCrown/Files_01_xuef
/all_xuef/程序员练级+Never/想研究的/python-further/metaclass1.py
2,426
4.96875
5
#http://blog.jobbole.com/21351/ #http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python """ Secondly, metaclasses are complicated. You may not want to use them for very simple class alterations. You can change classes by using two different techniques: ·monkey patching ·class decorators 99% of the time you need class alteration, you are better off using these. But 98% of the time, you don't need class alteration at all. """ ##basic """ In most languages, classes are just pieces of code that describe how to produce an object. Classes are objects too. Yes, objects. As soon as you use the keyword class, Python executes it and creates an OBJECT. The instruction >>> class ObjectCreator(object): ... pass ... creates in memory an object with the name "ObjectCreator". This object (the class) is itself capable of creating objects (the instances), and this is why it's a class. But still, it's an object, and therefore: ·you can assign it to a variable ·you can copy it ·you can add attributes to it ·you can pass it as a function parameter """ class A(): def f(self): pass print(dir(A)) ##Creating classes dynamically """ Since classes are objects, you can create them on the fly, like any object. Since classes are objects, they must be generated by something. When you use the class keyword, Python creates this object automatically. But as with most things in Python, it gives you a way to do it manually. """ ##What are metaclasses (finally) """ Metaclasses are the 'stuff' that creates classes. MyClass = MetaClass() my_object = MyClass() type is the built-in metaclass Python uses, but of course, you can create your own metaclass. """ ##The __metaclass__ attribute """ In Python 2, you can add a __metaclass__ attribute when you write a class (see next section for the Python 3 syntax): class Foo(object): __metaclass__ = something... [...] If you do so, Python will use the metaclass to create the class Foo. You write class Foo(object) first, but the class object Foo is not created in memory yet. Python will look for __metaclass__ in the class definition. If it finds it, it will use it to create the object class Foo. If it doesn't, it will use type to create the class. """ ##Metaclasses in Python 3 """ The syntax to set the metaclass has been changed in Python 3: class Foo(object, metaclass=something): """
b4794dd4ad3a0f2a418f001033b175972deae939
shenyubo1982/gittesting01
/PythonDemo08.py
6,412
3.734375
4
##07-05 学习笔记 ##装饰器 ##—————————————————————————————————— ## 2.1 无参数装饰器的实现 ##如果想为下述函数添加统计其执行时间的功能 import time def index(): time.sleep(3) print('1.Welcome to the index page') return 200 index() #函数原本的执行方式 ##遵循不修改被装饰器对象源代码的原则,我们想到的解决方案可能是这样↓ start_time = time.time() index() stop_time = time.time() print('1.run time is %s' % (stop_time - start_time)) ##考虑到还有可能要统计其他函数的执行时间,于是我们将其作成一个单独的工具 ##函数体需要外部传入被装饰的函数从而进行调用,我们可以使用参数的形式传入 def warapper(func): start_time = time.time() res = func() stop_time = time.time() print('2.run time is %s' % (stop_time - start_time)) return res ##但之后函数的调用方式都需要统一改成 warapper(index) #函数执行【与原本的执行方式放生了变化】 ##↑:由于调用方式都需要调整成warapper(index),不是原来的index()了。 ## 这样的操作,违反了不能修改被装饰对象调用方式的原则, ##于是我们换一种为函数体传值的方式,即将值【包给函数】,如下↓ def timer(func): def wrapper(): start_time = time.time() res = func() stop_time = time.time() print('3.run time is %s' % (stop_time - start_time)) return res return wrapper ##这样我们便可以在不修改被装饰函数源代码和调用方式的前提下为其加入统计时间的功能, ##只不过需要事先执行一次timer被装饰的函数传入,返回一个闭包函数wrapper ##重新赋值给变量名/函数名index,如下 index = timer(index) #装饰:将被装饰的函数进行装饰 ## (↑因为装饰器 timer(index)返回的是函数对象wrapper,这条语句相当于index=wrapper index() ##函数执行【没有改变函数的执行方式】, ## (此时,执行了index()就相当于执行wrapper() ##timer就是一个装饰器,他一个普通的函数,它把执行真正业务逻辑的函数func包裹在其中个, ##看起来像index被timer装饰了一样,timer返回的也是一个函数,这个函数的名字叫wrapper。 ##在这个例子中,函数进入和退出时,被称为一个横切面,这种编程方式称为面向切面的编程。 ##至此,我们便实现了一个无参装饰器timer,可以在不修改被装饰对象index源代码和 ##调用方式的前提下为其加上新功能。但我们忽略了若被装饰的函数是一个有参函数, ##便会抛出异常 ##引出带参数的装饰器 ##如果按照如下操作会报错 def home(name): time.sleep(5) print('2.welecom to the home page',name) #home=timer(home) #home('egon') ##抛异常的原因是,home('egon')调用的其实是wrapper('egon'),而函数wrapper没有参数 ##wrapper函数接收的参数其实是给最原始func用的,为了能满足被装饰函数参数的所有情况, ##使用*args+**kwargs组合(见4.3小节),于是修正装饰器timer2如下 def timer(func): def wrapper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) stop_time= time.time() print('4.run time is %s' %(stop_time-start_time)) return res return wrapper ##此时我们就可以用timer2来装饰带参数或不带参数的函数了,但是为了简洁而优雅地使用装饰器 ##python提供了专门的装饰器语法来取代 index=timer2(index)的形式,需要在被装饰对象的正上方 ##单独一行添加@timer2,当解释器解释到@timer2时,就会调用timer2函数,并且把它正下方 ##的函数名当做实参传入,然后将返回的结果重新赋值给原函数名 @timer # index = timer(index) def index(): time.sleep(3) print('3.Welcom to the index page') return 200 @timer # index = timer(index) 如果有多个修饰器可以叠加多个 def home(name): time.sleep(5) print('4.Welcom to the home page',name) #index() #home() ##2.2 有参数的装饰器的实现 ##了解无参数装饰器的实现原理后,我们可以再实现一个用来为被装饰对象添加认证功能的装饰器, ##实现的基本形式如下: def deco(func): def wrapper(*args,**kwargs): #编写基于文件的认证,认证通过则执行res=func(*args,**kwargs) #并返回res return True return wrapper ##如果我们想提供多种不同的认证方式以供选择,单从wrapper函数的实现角度改写如下: def deco(func): def wrapper(*args,**kwargs): if driver == 'file': # 编写基于文件的认证,认证通过则执行res=func(*args,**kwargs) # 并返回res return True elif driver =='mysql': # 编写基于文件的认证,认证通过则执行res=func(*args,**kwargs) # 并返回res return True return wrapper ##以上wrapper函数需要一个参数driver,而函数deco与wrapper的参数都有其特定的功能, ##不能用来接收其他类别的参数,可以从deco的外部再包一层函数auth,用来专门接收额外的参数, ##这样变保证了auth函数内无论多少层都可以引用到 def auth(driver): def deco(func): def wrapper(*args, **kwargs): if driver == 'file': # 编写基于文件的认证,认证通过则执行res=func(*args,**kwargs) # 并返回res print('dirver=file') return True elif driver == 'mysql': print('driver=mysql') return True # 编写基于文件的认证,认证通过则执行res=func(*args,**kwargs) # 并返回res return wrapper return deco ##此时,我们就实现了一个带参数的装饰器,使用方法如下: ##先调用auth_type(driver=file),得到@deco,deco是一个闭包函数 ##包含了对外部作用域名字driver的引用, ##@deco的语法意义与无参数装饰器一样 @auth(driver='file') def index(): pass @auth(driver='mysql') def home(): pass index=deco(index) home=deco(home) ##-------new example
c0ac397b9d7ec7b7eba8cad4c99e789adad4a1d8
Touchfl0w/python_practices
/basic_grammer/functional_programming/f2.py
451
4.0625
4
#闭包 = 函数 + 环境变量 a = 3 def func_pre(): #环境变量 a = 1 #函数 def func1(x): y = a + x print(y) #最后一定要返回这个闭包后的函数 return func1 f = func_pre() f(2) #发散一下,环境变量初始值可变的闭包 def func_pre1(a): #环境变量实际上为参数中的a #函数 def func2(x): y = a + x print(y) #最后一定要返回这个闭包后的函数 return func2 f = func_pre1(10) f(2)
5b6e9d55beb5fd5f8e1fdc490fe0429d914a1871
itcsoft/itcpython
/python/day14/dict_1.py
1,522
3.953125
4
# Наши Аккаунты в банках accounts = [ { "name": 'Demir Bank', "balance": 500000.00, "valuta": "KGS", "password": 1994 }, { "name": 'Optima Bank', "balance": 9654321, "valuta": "RUS", "password": 1995 }, { "name": 'KICB', "balance": 978423.15, "valuta": "USD", "password": 1996 }, { "name": 'Dos-Credo Bank', "balance": 75542.65, "valuta": "EUR", "password": 1997 } ] # Курс валют curs = { "EUR": 101.65, "USD": 84.80, "RUS": 1.23, "KZT": 0.010 } print('Мои аккаунты в банках:') for index in range(len(accounts)): print(index + 1, accounts[index]['name']) aindex = int(input('Выберите Аккаунт: ')) if aindex < 5 and aindex >= 1: rindex = aindex - 1 print(accounts[rindex]['name']) pin = int( input('Банкка тиешелуу PIN кодунузду териниз: ') ) if pin == accounts[rindex]['password']: print( 'Добро пожаловать в', accounts[rindex]['name'] ) print( 'Ваш баланс: ', accounts[rindex]['balance'] ) else: print('Ваш PIN не правильно!!!') else: print('Андай аккаунтум жоккоо((')
ffa006e0ef696614131d098e19c2542efa9474fa
alanaalfeche/python-sandbox
/leetcode/blind_75/problem21.py
1,660
3.90625
4
'''Problem 76: Minimum Window Substring https://leetcode.com/problems/minimum-window-substring/ Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). ''' from collections import Counter def min_windows(s, t): '''This algorithm uses sliding window to find the minimum substring in which all characters in T is satisfied. It starts by creating a hashmap for string T and initializing a missing variable to store the number of missing characters. Starting at index 0, we let r traverse through the list, checking if current char is found in the hashmap and decrementing missing if it is found. When we find all the missing character, we go inside the nested while loop to move l as close to r without incrementing missing. We also set the best start and end indices inside this while loop which we ultimately return as the minimum substring. ''' need = Counter(t) missing = len(t) l, r, i, j = 0, 0, 0, 0 while r < len(s): if need[s[r]] > 0: # subtract if char in s satisfy a char in t missing -= 1 need[s[r]] -= 1 r += 1 while missing == 0: # contract l until we find start missing a char in t if j == 0 or r - l < j - i: i, j = l, r need[s[l]] += 1 if need[s[l]] > 0: # if char in t is found then break out from the while loop missing += 1 l += 1 # contract l until a missing char is found return s[i:j] s = "ADOBECODEBANC" t = "ABC" expected = "BANC" actual = min_windows(s, t) print(actual == expected)
bd35fb19ad0effaa6d11cb61abd24504d7e7753f
himanshuJ01/python-course
/Python course/loops.py
107
3.6875
4
numbers = [1,2,3,4,5,6,44,55,88,123] for a in numbers: print(a) i=1 while i<6: print(i) i +=1
3ab28f777a5c4c3799d9451ca7cfd971337b0c76
cwang0129/algos
/ctci/chapter_03/minStack.py
573
3.96875
4
class minStack: def __init__(self): self.stack = [] self.min = [] def push(self, value): self.stack.append(value) if len(self.min) == 0 or value < self.min[-1]: self.min.append(value) def pop(self): val = self.stack.pop() if val == self.min[-1]: self.min.pop() def get_min(self): if len(self.min) == 0: return None else: return self.min[-1] if __name__ == '__main__': s1 = minStack() s1.push(3) s1.push(2) print(s1.get_min()) # return 2 s1.push(1) print(s1.get_min()) # return 1 s1.pop() print(s1.get_min()) # return 2
72ccf773210cc9a979ab3f33269ac2fdc5042f8b
erocconi/AoC2020
/d2-bfpv.py
1,310
3.65625
4
#!/usr/bin/env python3 import sys class Password(object): def __init__(self, s): policy, self.password = s.strip().split(': ') policy_range, self.policy_char = policy.split(' ') self.policy_range = [int(x) for x in policy_range.split('-')] def evaluate(self): matches = self.password.count(self.policy_char) if ((matches >= self.policy_range[0]) and (matches <= self.policy_range[1])): return True else: return False def evaluate_stupid(self): try: # -1 instead of +1 c1 = self.password[self.policy_range[0]-1] except: c1 = None try: # -1 instead of +1 c2 = self.password[self.policy_range[1]-1] except: c2 = None chars = [c1, c2] matches = [x == self.policy_char for x in chars] return sum(matches) == 1 def __repr__(self): policy = '-'.join(map(str, self.policy_range)) return f'Password<"{policy} {self.policy_char}: {self.password}">' def main(): with open("./input/d2.txt") as f: passwords = [Password(x) for x in f] matching_passwords = [p for p in passwords if p.evaluate()] print('part 1 solution:') print(len(matching_passwords)) stupid = [p.evaluate_stupid() for p in passwords] print('part 2 solution:') print(sum(stupid)) if __name__ == '__main__': main()
8cbcab7daf01a2f4b7305a521726b3a2d3a148fc
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4472/codes/1764_674.py
604
3.890625
4
# Nome: Nathaly Barbosa Leite # Curso: Estatística # Matrícula: 21954721 from numpy import * vetor = array(eval(input("Informe o conjunto de numeros: "))) #vetor = (vetor) # Quantidade de elementos do vetor print(size(vetor)) # Primeiro elemento do vetor print(vetor[0]) # Ultimo elemento do vetor print(vetor[-1]) # Maior elemento do vetor print(max(vetor)) # Menor elemento do vetor print(min(vetor)) # Soma dos elementos do vetor print(sum(vetor)) # Media aritmetica dos elementos do vetor, com até duas casas decimais de precisão. print(round(sum(vetor) / size(vetor),2)) #print (round(mean(vetor)))
4ad8e6c83c09be43dd274473cdba24041f29b6c4
lingkaching/Data-Structure
/mygraph.py
4,198
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 20 15:33:27 2017 @author: KACHING """ from myqueue import Queue from mypriorityqueue1 import PriorityQueue import numpy as np import pdb class Vertex: def __init__(self,key): self.id=key self.connectedTo={} def addNeighbour(self,nbr,weight=0): self.connectedTo[nbr]=weight def getConnections(self): return self.connectedTo.keys() def getId(self): return self.id def getWeight(self,nbr): return self.connectedTo[nbr] class Graph: def __init__(self): self.vertList={} self.numVertices=0 def addVertex(self,key): self.numVertices+=1 newVertex=Vertex(key) self.vertList[key]=newVertex def getVertex(self,v): if v in self.vertList: return self.vertList[v] else: return None def getVertices(self): return self.vertList.values() def addEdge(self,m,n,weight=0): if m not in self.vertList: self.addVertex[m] if n not in self.vertList: self.addVertex[n] self.vertList[m].addNeighbour(self.vertList[n],weight) def InitGraph(): G=Graph() for v in ['s','t','x','y','z']: G.addVertex(v) G.addEdge('s','t',10) G.addEdge('s','y',5) G.addEdge('t','y',2) G.addEdge('t','x',1) G.addEdge('x','z',4) G.addEdge('y','t',3) G.addEdge('y','x',9) G.addEdge('y','z',2) G.addEdge('z','x',6) G.addEdge('z','s',7) #============================================================================== # for v in G.vertList.values(): # for w in v.getConnections(): # print("( %s , %s , %s )" % (v.getId(), w.getId(), v.getWeight(w))) #============================================================================== return G def BFS(G,s): for u in G.getVertices(): if u!=s: u.color='white' u.d=np.inf u.pre=None s.color='gray' s.d=0 s.pre=None Q=Queue() Q.Enqueue(s) while not Q.IsEmpty(): u=Q.Dequeue() for v in u.getConnections(): if v.color=='white': v.color='gray' v.d=u.d+1 v.pre=u Q.Enqueue(v) u.color='black' def PrintPath(G,s,v): if v==s: print(s.getId()) elif v.pre==None: print('no path from %s to %s' % (s.getId(),v.getId())) else: PrintPath(G,s,v.pre) print(v.getId()) def DFS(G): for u in G.getVertices(): u.color='white' u.pre=None for u in G.getVertices(): if u.color=='white': DFS_VISIT(G,u) def DFS_VISIT(G,u): global time time+=1 u.d=time u.color='gray' for v in u.getConnections(): if v.color=='white': v.pre=u DFS_VISIT(G,v) u.color='black' time+=1 u.f=time print('%s %s' % (u.f,u.getId())) def Dijkstra(G,s): InitialiseSingleSource(G,s) S=[] PQ=PriorityQueue() items=[ (v.d, v) for v in G.getVertices()] PQ.BuildHeap(items) while not PQ.IsEmpty(): u=PQ.DeleteMin()[1] S.append(u) for v in u.getConnections(): Relax(u,v,u.getWeight(v)) def InitialiseSingleSource(G,s): for v in G.getVertices(): v.d=np.inf v.pre=None s.d=0 def Relax(u,v,w_uv): if v.d>u.d+w_uv: v.d=u.d+w_uv v.pre=u def main(): G=InitGraph() #============================================================================== # BFS(G,G.getVertex('s')) # PrintPath(G,G.getVertex('s'),G.getVertex('y')) #============================================================================== #============================================================================== # DFS(G) #============================================================================== Dijkstra(G,G.getVertex('s')) PrintPath(G,G.getVertex('s'),G.getVertex('z')) if __name__=='__main__': time=0 main()
40118e0cab40b0812258360ba8d89e1a6a5c2d35
SevenFive/AutomatePython
/AutoPY3while.py
382
4
4
#while loop + break (to prevent inf loop) password = '' while True: print('Please enter password: ') password = input() if password == 'swordfish': break print('Access granted') # while + continue (to skip once) i = 0 while i <= 10: i = i + 1 print('i = ' + str(i)) if i == 3: continue print('Loop is finished without executing at i=3')
9d40da52a6432472b10f05ffc700b08d47c718ba
Desperado1/mini-projects
/practice problems(Data Structures)/InsertionSort.py
227
4.09375
4
def insertionSort(array): # Write your code here. n = len(array) for i in range(1, n): j = i - 1 key = array[i] while j >= 0 and key < array[j]: array[j+1] = array[j] j -= 1 array[j + 1] = key return array
b587e629d211aa9754c1a789ee8bd1221f94ad50
CBS-UNHCR-Collaboration/Text-classifiers-project-git
/data-cleaning/non_utf_char_remover.py
2,107
3.875
4
import os """ 2017-06-02: Raghava This code will find all non-utf8 encoding characters. It will read each line and character by character to see if the char is and prints the char position """ source_filepath = '/Users/raghava/data-analytics Dropbox/Raghava Rao Mukkamala/cbs-research/student-supervision/Master-students/progress/Yousef-Adrin/text-classification-02/training-data/BinaryModels_model4_cleaned.csv' source_filepath = '/Users/raghava/data-analytics Dropbox/Raghava Rao Mukkamala/' \ 'cbs-research/misc+archieve/new/volkwagen.csv' def getFileExtension(filepath): """ This function returns the filename without the extension. """ return os.path.splitext(os.path.basename(filepath))[1] def getFilenameWithoutExtension(filepath): """ This function returns the filename without the extension. """ return os.path.splitext(os.path.basename(filepath))[0] # get the folder path dirPath = os.path.dirname(source_filepath) filename_no_extension = getFilenameWithoutExtension(source_filepath) fileExtension = getFileExtension(source_filepath) target_filepath = dirPath + '/' + filename_no_extension + '_cleaned' + fileExtension non_utf_8_char_count = 0 with open (source_filepath,"r",encoding="utf-8") as fileReader, \ open(target_filepath, 'w', encoding="utf-8") as fileWriter: while True: c = fileReader.read(1) if not c: break elif (ord(c) > 256): non_utf_8_char_count = non_utf_8_char_count + 1 print('invalid char: ' + c) else: fileWriter.write(c) fileReader.close() fileWriter.close() print('Done cleaning the file! Non Utf-8 characters found: ' + str(non_utf_8_char_count)) # lines = [] # lineindex = 0 # charindex = 0 # with open (source_filepath,"r",encoding="utf-8") as f: # lines = f.readlines() # for line in lines: # lineindex = lineindex + 1 # charindex = 0 # for c in line: # charindex = charindex + 1 # if(ord(c) > 256): # print('invalid char at ln: ' + str(lineindex) + ' ch index: ' + str(charindex) + ', ord value:' + str(ord(c)) + ' character: ' + c)
09e9862b1a184e7faffde27fda51721c2491f9e9
sqlalchemy/sqlalchemy
/examples/vertical/__init__.py
1,045
3.59375
4
""" Illustrates "vertical table" mappings. A "vertical table" refers to a technique where individual attributes of an object are stored as distinct rows in a table. The "vertical table" technique is used to persist objects which can have a varied set of attributes, at the expense of simple query control and brevity. It is commonly found in content/document management systems in order to represent user-created structures flexibly. Two variants on the approach are given. In the second, each row references a "datatype" which contains information about the type of information stored in the attribute, such as integer, string, or date. Example:: shrew = Animal(u'shrew') shrew[u'cuteness'] = 5 shrew[u'weasel-like'] = False shrew[u'poisonous'] = True session.add(shrew) session.flush() q = (session.query(Animal). filter(Animal.facts.any( and_(AnimalFact.key == u'weasel-like', AnimalFact.value == True)))) print('weasel-like animals', q.all()) .. autosource:: """
54160af36a62680ccb9efd612315594e3891399d
OmitNomis/BitAdder
/binaryConverter.py
426
4.0625
4
def decimalToBinary(decimalNo): bit = [] #list to store the converted decimal into binary for i in range (8): #running loop 8 times in order to convert the number into 8 bits remainder = decimalNo%2 #finding remainder bit.append(remainder) #adding remainder to list decimalNo = decimalNo//2 #floor division to move to the next calculation return bit #return the list
4d977a76ae0a3235694ca1777bf8e5491a416352
AndrewwCD/homework_2
/homework_2.py
861
4.0625
4
#Use decorator to estimate pi to n number of decimal places import math def get_pi_n(func): def inner(n): print("Pi estimated to n number of decimal places: ") return func(n) return inner @get_pi_n def get_pi(n): pi = round(math.pi,n) return pi print(get_pi(3)) #Use lambda to split a given data list into several small sections import numpy as np split_list = lambda list1, sections: [list(i) for i in (np.array_split(list1,sections))] print(split_list([1,2,3,4,"5","6","7","8"],4)) #Use lambda to perform some simple statistics on a list of values list_stats = lambda list1: { "mean" : np.mean(list1), "min" : np.min(list1), "max" : np.max(list1) } print(list_stats([1,2,3,4,5,6,7,8,9]))
833131f89a19612946284285bb91a845b438b793
anhuafeng123/python
/吃鸡鸡.py
367
3.515625
4
def panduan(accont,passwd): if len(account) <= 8 and len(passwd) <= 6: print("登录成功") else: print("登录失败") biaoti = "不会吃鸡" print(biaoti.center(60,"*")) def denglujiemian(): account = input("请输入账号:") passwd = input("请输入密码:") panduan(account,passwd) denglijiemian()
7ad43c9cce9cef67e994baaae4bb0d65ec8090f4
faportillo/SatelliteSim
/geometry.py
14,251
3.9375
4
import math import numpy as np ''' Space mission geometry. Angles computed in radians ''' def spherical_to_cart(r, theta, phi): """ Convert spherical, or polar, coordinates to cartesian :param r: Magnitude of vector :param theta: Inclination Angle :param phi: Azimuth Angle :return: 3D points """ if theta != 0 and phi != 0: print("Inclination and azimuth") x = r * np.sin(theta) * np.cos(phi) y = r * np.sin(theta) * np.sin(phi) z = r * np.cos(theta) elif phi == 0 and theta != 0: print("Inclination with no azimuth") x = r * np.cos(theta) y = 0 z = r * np.sin(theta) else: print("Azimuth with no inclination, or no azimuth and no inclination") x = r * np.cos(phi) y = r * np.sin(phi) z = 0 return x, y, z def cart_to_vpython(v): return v[1], v[2], v[0] def get_distance(vec1, vec2): d = np.sqrt((vec1[0] - vec2[0]) ** 2 + (vec1[1] - vec2[1]) ** 2 + (vec1[2] - vec2[2]) ** 2) return d def spherical_to_vector(az, el): """ NOTE: Might be deprecated Convert azimuth and elevation to unit vector coordinates (on the unit sphere with the craft in the center) :param az: azimuth - the angular distance from the north or south point of the horizon to the point at which a vertical circle passing through the object intersects the horizon. :param el: elevation - arc length distance above or below the equator :return: unit vector coordinates """ x = math.cos(az) * math.cos(el) y = math.sin(az) * math.cos(el) z = math.sin(el) return x, y, z def vector_to_spherical(x, y, z): """ Convert unit vector coordinates to azimuth and elevation :param x: x point on unit sphere :param y: y point on unit sphere :param z: z point on unit sphere :return: azimuth and elevation """ az = math.atan2(y, x) el = math.asin(z) return az, el def angular_radius_spherical_earth(altitude, radius_e): """ Angular radius of the spherical Earth as seen from the spacecraft (SMAD pg. 111) :param altitude: Altitude of spacecraft :param radius_e: spherical earth radius :return: rho - the angular radius of the spherical earth as seen from spacecraft (radians) """ if radius_e is None: radius_e = 6378 return math.asin(radius_e / (radius_e + altitude)) def angular_radius_center_earth(altitude, radius_e): """ Angular radius measured at the center of the Earth of the region seen by the spacecraft (SMAD pg. 111) :param altitude: Altitude of spacecraft :param radius_e: spherical earth radius :return: lambda_0 - the angular radius measured at the center of Earth of the region seen by craft (radians) """ if radius_e is None: radius_e = 6378 return math.acos(radius_e / (radius_e + altitude)) def distance_horizon(radius_e, altitude=None, lambda_0=None): """ Distance of the spacecraft to the Earth's horizon (SMAD pg. 111) :param radius_e: spherical earth radius :param altitude: Altitude of spacecraft :param lambda_0: the angular radius measured at the center of Earth of the region seen by craft :return: D_max - Distance of the spacecraft to the Earth's horizon """ assert altitude is not None or lambda_0 is not None if radius_e is None: radius_e = 6378 if altitude is not None: return ((radius_e + altitude) ** 2 - (radius_e ** 2)) ** (1 / 2) else: return radius_e * math.tan(lambda_0) def spacecraft_to_earth_coords(altitude, radius_e, phi_e, nadir, long_ssp, lat_ssp): """ Compute coordinates on the Earth of the given subsatellite point at (long_ssp, lat_ssp) (SMAD pg. 114) and target direction (phi_e, nadir) :param altitude: Altitude of spacecraft :param radius_e: spherical earth radius :param phi_e: azimuth :param nadir: nadir angle, measured from spacecraft ssp (subsatellite point) to target :param long_ssp: longitude on Earth of ssp :param lat_ssp: latitude on Earth of ssp :return: longitude and latitutde of taget on the Earth, east-west direction from ssp """ if radius_e is None: radius_e = 6378 rho = angular_radius_spherical_earth(altitude, radius_e) eps = math.acos(math.sin(nadir) / math.sin(rho)) lambda_s = math.radians(90) - nadir - eps lat_p_prime = math.acos( math.cos(lambda_s) * math.sin(lat_ssp) + math.sin(lambda_s) * math.cos(lat_ssp) * math.cos(phi_e)) lat_p = math.radians(90) - lat_p_prime delta_l = math.acos( (math.cos(lambda_s) - math.sin(lat_ssp) * math.sin(lat_p)) / (math.cos(lat_ssp) * math.cos(lat_p))) long_p = delta_l + lat_p return long_p, lat_p # , 'west' if phi_e > math.radians(180) else 'east' def earth_to_spacecraft_coords(altitude, radius_e, long_ssp, lat_ssp, long_p, lat_p): """ :param altitude: :param radius_e: :param long_ssp: :param lat_ssp: :param long_p: :param lat_p: :return: """ if radius_e is None: radius_e = 6378 delta_l = abs(long_ssp - lat_ssp) rho = angular_radius_spherical_earth(altitude, radius_e) lambda_s = math.acos(math.sin(lat_ssp) * math.sin(lat_p) + math.cos(lat_ssp) * math.cos(lat_p) * math.cos(delta_l)) phi_e = math.acos( (math.sin(lat_p) - math.cos(lambda_s) * math.sin(lat_ssp)) / (math.sin(lambda_s) * math.cos(lat_ssp))) n = math.atan2(math.sin(rho) * math.sin(lambda_s), (1 - math.sin(rho) * math.cos(lambda_s))) return phi_e, n def subsatellite_coords_ascending(inclination, w, t, w_e=None): """ Latitude and longitude relative to the ascending node for satellite in circular orbit at inclination (SMAD pg. 116) :param inclination: orbital inclination of satellite :param w: angular velocity of satellite :param t: time since satellite crossed the equator northbound. :param w_e: angular rotation of planetary body. If none, then assume it's Earth :return: Subsatellite Longitude adn Latitiude """ if w_e is None: w_e = 0.000072921 # Rotation of the earth in rads/s lat_s = math.asin(math.sin(inclination) * math.sin(w * t)) long_s = math.atan(math.cos(inclination) * math.tan(w * t)) - (w_e * t) return long_s, lat_s def ground_track_velocity(period, radius_e=None): """ Ground track velocity (SMAD pg. 116) :param period: Orbital period in seconds :param radius_e: Spherical radius of planetary body. If None, assume it's Earth :return: velocity """ if radius_e is None: radius_e = 6378 velocity_ground_track = 2 * math.pi * radius_e / period assert velocity_ground_track <= 7.905 # km/s return velocity_ground_track def area_coverage_rate(period, l_outer=None, l_inner=None, look_one_dir=False, eps=None, rho=None): """ Width of swath coverage (SMAD pg. 116-117) :param period: Orbital period :param l_outer: Effective outer horizon from ground trace :param l_inner: Effective inner horizon from ground trace :param look_one_dir: Boolean to determine if looking exclusively in one direction (i.e. both horizons on one size of the ground trace) :param eps: Elevation angle :param rho: Angular radius of earth :return: ACR - Area Coverage Rate """ if eps is not None and rho is not None: assert l_outer is None and l_inner is None acr = (4 * math.pi / period) * math.cos(eps + math.asin(math.cos(eps) * math.sin(rho))) elif l_outer is not None and l_inner is not None: assert eps is None and rho is None if l_outer == l_inner: acr = (4 * math.pi / period) * math.sin(l_outer) else: acr = 2 * math.pi * ((math.sin(l_outer) + math.sin(l_inner)) if look_one_dir is False else ( math.sin(l_outer) + math.sin(l_inner))) else: raise Exception( "Invalid equation parameters. Either 'l_outer' and 'l_inner'" \ " need valid values or 'eps' and 'rho' need valid values") return acr def get_max_angles_and_max_range(rho, radius_e=None, eps_min=math.radians(5)): """ Given value eps_min (typically 5 deg) and angular radius of planet w.r.t Satellite, calculate max planet central angle (l_max), max nadir angle, n_max, measured at sat from nadir to ground station, and max range D_max, which the Sat will still be in view. (SMAD pg. 119) :param eps_min: Minimum value of spacecraft elevation (note: like azimuth and elevation, not altitude) :param rho: Angular radius of planet w.r.t satellite given by radius_e / (radius_e + H) :param radius_e: Spherical radius of planetary body :return: l_max, n_max, D_max """ if radius_e is None: radius_e = 6378 sin_n_max = math.sin(rho) * math.cos(eps_min) # get n_max by math.asin(sin_n) l_max = math.radians(90) - eps_min - math.asin(sin_n_max) D_max = radius_e * (math.sin(l_max) / sin_n_max) return l_max, math.asin(sin_n_max), D_max def inst_orbit_pole(inclination, L_node): """ Calculate instantaneous orbit pole - the pole of the orbit plane at the time of the observation given the inclination of the orbit and the Longitude (L_node) of the ascending node. (SMAD pg. 119) :param inclination: Orbital inclination :param L_node: Longitude of the ascending node :return: Longitude and Latitude of the instantaneous orbit pole """ lat_pole = math.radians(90) - inclination long_pole = L_node - math.radians(90) return long_pole, lat_pole def calc_lambda_min(long_pole, lat_pole, long_gs, lat_gs): """ Calculate the minimum planetary central angle between the satellite's ground track and the gound station (lambda_min) (SMAD pg. 120) :param long_pole: Longitude of the instantaneous orbit pole :param lat_pole: Latitude of the instantaneous orbit pole :param long_gs: Longitude of the ground station :param lat_gs: Latitude of the ground station :return: sine of lambda_min """ sin_l_min = math.sin(lat_pole) * math.sin(lat_gs) + math.cos(lat_pole) * math.cos(long_gs) * math.cos( long_gs - long_pole) return sin_l_min def get_angles_and_range_closest_approach(long_pole, lat_pole, long_gs, lat_gs, rho, radius_e): l_min = calc_lambda_min(long_pole, lat_pole, long_gs, lat_gs) n_min = math.atan((math.sin(rho) * l_min) / (1 - math.sin(rho) * math.cos(math.asin(l_min)))) eps_max = math.radians(90) - math.asin(l_min) - n_min d_min = radius_e * (l_min / math.sin(n_min)) return n_min, eps_max, d_min def max_angular_rate_sat_from_gs(d_min, v_sat, radius_e=None, altitude=None, period=None): """ Get the maximum angular rate of the satellite as seen from the ground station :param d_min: Minimum approach distance (SMAD pg. 120) :param v_sat: Velocity of the satellite :param radius_e: Radius of planetary body :param altitude: Height of the satellite :param period: Orbital period in minutes :return: Max angular rate """ if v_sat is not None: assert radius_e is None and altitude is None and period is None theta_max = v_sat / d_min elif radius_e is not None and altitude is not None and period is not None: assert v_sat is None theta_max = (2 * math.pi * (radius_e + altitude)) / (period * d_min) else: raise Exception( "Invalid equation parameters. Either 'v_sat' is not None or" \ " radius_e, altitude, and period are not None.") return theta_max def total_azimuth_range(lambda_min, lambda_max): """ Calculate the total azimuth range that the satellite covers as seen by the ground station :param lambda_min: minimum planetary central angle between the satellite's ground track and the gound station :param lambda_max: max planetary central angle between the satellite's ground track and the gound station :return: total azimuth range """ delta_phi = 2 * math.acos((math.tan(lambda_min)) / (math.tan(lambda_max))) return delta_phi def calc_total_time_in_view(period, lambda_min, lambda_max): """ Calculate the total time the satellite will be in view from the ground station (SMAD pg. 120) :param period: Orbital period :param lambda_min: minimum planetary central angle between the satellite's ground track and the ground station :param lambda_max: max planetary central angle between the satellite's ground track and the ground station :return: Total time in view (T) """ T = ((period / 180) * (1 / 0.0174533)) * math.acos((math.cos(lambda_max)) / (math.cos(lambda_min))) return T def calc_phi_center(lat_pole, lat_gs, lambda_min): """ Calculate azimuht at the center of the viewing arc at which the elevation angle is a maximum. :param lat_pole: Latitude of instantaneous orbit pole :param lat_gs: Latitude of ground station :param lambda_min: minimum planetary central angle between the satellite's ground track and the gound station :return: Phi center """ phi_pole = (math.sin(lat_pole) - math.sin(lambda_min) * math.sin(lat_gs)) / ( math.cos(lambda_min) * math.cos(lat_gs)) phi_center = math.radians(180) - phi_pole return phi_center def max_time_in_view(period, lambda_max): """ Maximum time in view that occurs when satellite passes overhead and lambda_min=0 :param period: Orbital period in minutes :param lambda_max: max planetary central angle between the satellite's ground track and the ground station :return: T_max """ T_max = period * (lambda_max / (math.radians(180))) return T_max
7a1cfe7884bdcc0711750c217ddbcec0ea7fee3d
gridl/Python-Procedures
/maxfunction.py
702
4.40625
4
#file: use max() to recursively find the largest element in a list #procedure # maxoflist #parameters # lst, a list #produces # maximum, a number #purpose # to use basic recursion to find the largest item in a list #preconditions # lst must be entirely numbers that are valid in the max() operator # lst must contain at least one element #postconditions # maximum >= x for x in lst def maxoflist(lst): if len(lst) == 1: #if the list is one element (base case) return lst[0] else: return max(lst[0], maxoflist(lst[1:])) #recurse on cdr of lst #examples #>>> maxoflist([1, 2, 3, 4, 5]) #5 #>>> maxoflist([1, 2, 3, 4, -5]) #4 #>>> maxoflist([10, 2, 3, 4, 5]) #10
1fd98ee0243d3a61fef92ab759509ddb2e5c7b17
HaoMoney/leetcode
/lc_jz22.py
485
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: cur = ListNode(0) cur = head length = 0 if not head: return None while head.next: length += 1 head = head.next for _ in range(length-k+1): cur = cur.next return cur
c77e69af4d82e88b08d43e8e9f22bd1da16b2261
thirtyaughtsix/solidity-math-utils
/project/emulation/FixedPoint/IntegralMath.py
3,728
3.671875
4
from .common.BuiltIn import * from .common.Uint import * ''' @dev Compute the largest integer smaller than or equal to the binary logarithm of `n` ''' def floorLog2(n): res = 0; if (n < 256): # at most 8 iterations while (n > 1): n >>= 1; res += 1; else: # exactly 8 iterations for s in [1 << (8 - 1 - k) for k in range(8)]: if (n >= 1 << s): n >>= s; res |= s; return res; ''' @dev Compute the largest integer smaller than or equal to the square root of `n` ''' def floorSqrt(n): if (n > 0): x = n // 2 + 1; y = (x + n // x) // 2; while (x > y): x = y; y = (x + n // x) // 2; return x; return 0; ''' @dev Compute the smallest integer larger than or equal to the square root of `n` ''' def ceilSqrt(n): x = floorSqrt(n); return x if x ** 2 == n else x + 1; ''' @dev Compute the largest integer smaller than or equal to the cubic root of `n` ''' def floorCbrt(n): x = 0; for y in [1 << k for k in range(255, -1, -3)]: x <<= 1; z = 3 * x * (x + 1) + 1; if (n // y >= z): n -= y * z; x += 1; return x; ''' @dev Compute the smallest integer larger than or equal to the cubic root of `n` ''' def ceilCbrt(n): x = floorCbrt(n); return x if x ** 3 == n else x + 1; ''' @dev Compute the nearest integer to the quotient of `n` and `d` (or `n / d`) ''' def roundDiv(n, d): return n // d + (n % d) // (d - d // 2); ''' @dev Compute the largest integer smaller than or equal to `x * y / z` ''' def mulDivF(x, y, z): (xyh, xyl) = mul512(x, y); if (xyh == 0): # `x * y < 2 ^ 256` return xyl // z; if (xyh < z): # `x * y / z < 2 ^ 256` m = mulMod(x, y, z); # `m = x * y % z` (nh, nl) = sub512(xyh, xyl, m); # `n = x * y - m` hence `n / z = floor(x * y / z)` if (nh == 0): # `n < 2 ^ 256` return nl // z; p = unsafeSub(0, z) & z; # `p` is the largest power of 2 which `z` is divisible by q = div512(nh, nl, p); # `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p` r = inv256(z // p); # `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256` return unsafeMul(q, r); # `q * r = (n / p) * inverse(z / p) = n / z` revert(); # `x * y / z >= 2 ^ 256` ''' @dev Compute the smallest integer larger than or equal to `x * y / z` ''' def mulDivC(x, y, z): w = mulDivF(x, y, z); if (mulMod(x, y, z) > 0): return safeAdd(w, 1); return w; ''' @dev Compute the value of `x * y` ''' def mul512(x, y): p = mulModMax(x, y); q = unsafeMul(x, y); if (p >= q): return (p - q, q); return (unsafeSub(p, q) - 1, q); ''' @dev Compute the value of `2 ^ 256 * xh + xl - y`, where `2 ^ 256 * xh + xl >= y` ''' def sub512(xh, xl, y): if (xl >= y): return (xh, xl - y); return (xh - 1, unsafeSub(xl, y)); ''' @dev Compute the value of `(2 ^ 256 * xh + xl) / pow2n`, where `xl` is divisible by `pow2n` ''' def div512(xh, xl, pow2n): pow2nInv = unsafeAdd(unsafeSub(0, pow2n) // pow2n, 1); # `1 << (256 - n)` return unsafeMul(xh, pow2nInv) | (xl // pow2n); # `(xh << (256 - n)) | (xl >> n)` ''' @dev Compute the inverse of `d` modulo `2 ^ 256`, where `d` is congruent to `1` modulo `2` ''' def inv256(d): # approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method x = 1; for i in range(8): x = unsafeMul(x, unsafeSub(2, unsafeMul(x, d))); # `x = x * (2 - x * d) mod 2 ^ 256` return x;
903f764f8a01935ec4e92767df22484698821a67
Vibhurathore09/python-
/no_of_days_in_month.py
550
4.28125
4
# Number of DAYS IN A MONTH print('Program will print number of days in a given month') flag = 1 month_days = int(input(("enter month (1-12)"))) if month_days == 2: year = int(input("enter year")) if year%4==0 and year%100!=0 or year%400==0: num_days = 29 else: num_days = 28 elif month_days in {1,3,5,7,8,10,12}: num_days = 31 elif month_days in {4,6,9,11}: num_days = 30 else: print("enter valid month") flag = 0 if flag == 1: print("There are ",num_days, "days in ",month_days)
70305aa1024e444ecfa0d8de385e95b3074d890d
JakubKazimierski/PythonPortfolio
/Coderbyte_algorithms/Medium/LongestMatrixPath/LongestMatrixPath.py
2,460
4.40625
4
''' Longest Matrix Path from Coderbyte December 2020 Jakub Kazimierski ''' def LongestMatrixPath(strArr): ''' Have the function LongestMatrixPath(strArr) take the array of strings stored in strArr, which will be an NxM matrix of positive single-digit integers, and find the longest increasing path composed of distinct integers. When moving through the matrix, you can only go up, down, left, and right. For example: if strArr is ["345", "326", "221"], then this looks like the following matrix: 3 4 5 3 2 6 2 2 1 For the input above, the longest increasing path goes from: 3 -> 4 -> 5 -> 6. Your program should return the number of connections in the longest path, so therefore for this input your program should return 3. There may not necessarily always be a longest path within the matrix. ''' matrix = [[int(digit) for digit in row] for row in strArr] rows, columns = len(matrix), len(matrix[0]) path_from_points = [[0] * columns for i in range(rows)] def find_longest(row_id, column_id): ''' Nested function (can use variables of LongestMatrixPath(strArr)). Uses recurency to find longest possible sequence in matrix. ''' # for unvisited points if path_from_points[row_id][column_id] == 0: val = matrix[row_id][column_id] # get lenght of longest sequence, traverse in all directions path_from_points[row_id][column_id] = 1 + max( # if there is no next elem in sequence returns 0, but each step is counted in recurency call by # path_from_points[row_id][column_id] = 1 + max(...) find_longest(row_id - 1, column_id) if row_id > 0 and val > matrix[row_id - 1][column_id] else 0, find_longest(row_id + 1, column_id) if row_id < rows - 1 and val > matrix[row_id + 1][column_id] else 0, find_longest(row_id, column_id - 1) if column_id > 0 and val > matrix[row_id][column_id - 1] else 0, find_longest(row_id, column_id + 1) if column_id < columns - 1 and val > matrix[row_id][column_id + 1] else 0) return path_from_points[row_id][column_id] # do not count starting element in sequence return max(find_longest(row_id, column_id) for row_id in range(rows) for column_id in range(columns)) - 1
e465386f01b4b28887ebdb8f7d03af638b5b6765
ezhk/algo_and_structures_python
/Lesson_8/2.py
1,944
3.96875
4
""" 2*. Определение количества различных подстрок с использованием хэш-функции. Пусть дана строка S длиной N, состоящая только из маленьких латинских букв. Требуется найти количество различных подстрок в этой строке. """ import hashlib def get_substrings(input_string): uniq_substrings = {} len_str = len(input_string) window_size = len_str - 1 while window_size > 0: for idx in range(0, len_str - window_size + 1): encode_string = input_string[idx:idx + window_size].encode('utf-8') hash_substring = hashlib.sha1(encode_string).hexdigest() # проверяем, что ключа ещё нет if hash_substring in uniq_substrings: continue uniq_substrings[hash_substring] = encode_string.decode('utf-8') window_size -= 1 return uniq_substrings if __name__ == "__main__": init_string = input("Введите исходную строку: ") string_hashes = get_substrings(init_string) print(f"Количество подстрок = {len(string_hashes)}") print("\tхеши и их строки:") print("\n".join((f"{k} = {v}" for k, v in string_hashes.items()))) """ Введите исходную строку: qazq Количество подстрок = 8 хеши и их строки: 7c286a779653e0c1d9cbc2b9c772fbea7033e452 = qaz 87f2b544a9eb902ae78b9e05d5e2fe4f1094076f = azq d3c583412a36313ab5e24293924c39a36b842c56 = qa 90283840d90de49b8e7984bd99b47fee0d4bd50d = az 56164622c104ef8e076c1707304ed92a62f7013c = zq 22ea1c649c82946aa6e479e1ffd321e4a318b1b0 = q 86f7e437faa5a7fce15d1ddcb9eaeaea377667b8 = a 395df8f7c51f007019cb30201c49e884b46b92fa = z """
dcdf12a35c673a41498fe588350911ec5642e726
GokulAB17/Decision-Trees
/DecisionTree/Company_Data.py
2,096
3.9375
4
#A cloth manufacturing company is interested to know about the segment or #attributes causes high sale. #Approach - A decision tree can be built with target variable Sale # (we will first convert it in categorical variable) & #all other variable will be independent in the analysis. import pandas as pd import matplotlib.pyplot as plt import numpy as np #loading dataset Company_dataset data = pd.read_csv(r"filepath\Company_Data.csv") #Data Preprocessing and EDA data.head() len(data['Sales'].unique()) data.isnull().sum() colnames = list(data.columns) predictors = colnames[1:11] target = colnames[0] data["Sales"].max() data["Sales"].min() #new dataframe created for preprocessing data_new=data.copy() #Making categorical data for Target column Sales # 1 : Sales<=5 # 2 :5>Sales<=10 # 3 : Sales>10 for i in range(0,len(data)): if(data_new["Sales"][i]<=5): data_new["Sales"][i]="<=5" elif(data_new["Sales"][i]<=10 and data_new["Sales"][i]>5): data_new["Sales"][i]="5>s<=10" else: data_new["Sales"][i]=">10" data_new.Sales.value_counts() #Mapping columns which are categorical to dummy variables data_new.Sales=data_new.Sales.map({"<=5":1,"5>s<=10":2,">10":3}) data_new.ShelveLoc=data_new.ShelveLoc.map({"Bad":1,"Good":3,"Medium":2}) data_new.Urban=data_new.Urban.map({"Yes":1,"No":2}) data_new.US=data_new.US.map({"Yes":1,"No":2}) # Splitting data into training and testing data set by 70:30 ratio from sklearn.model_selection import train_test_split train,test = train_test_split(data_new,test_size = 0.3) #Decision Tree Model building and Validity checking from sklearn.tree import DecisionTreeClassifier model = DecisionTreeClassifier(criterion = 'entropy') model.fit(train[predictors],train[target]) preds = model.predict(test[predictors]) pd.Series(preds).value_counts() pd.crosstab(test[target],preds) # Accuracy = train np.mean(train.Sales == model.predict(train[predictors]))#1 # Accuracy = Test np.mean(preds==test.Sales) # 0.6083
274c9fb219473adcf49406386743d30f948b8b72
CrisExpo/Python
/Yatzy/yatzy.py
3,145
3.71875
4
class Yatzy(): @staticmethod def chance(*dice): # *argv keeps a random number of arguments, you can run 3 or 5 arguments without changing de code score = 0 for num_dice in dice: score += num_dice return score @staticmethod def yatzy(dice): if dice.count(dice[0]) != 5: return 0 return 50 @staticmethod def ones(*dice): ONE = 1 return dice.count(ONE) * ONE @staticmethod def twos(*dice): TWO = 2 return dice.count(TWO) * TWO @staticmethod def threes(*dice): THREE = 3 return dice.count(THREE) * THREE def fours(self): FOUR = 4 return self.dice.count(FOUR) * FOUR def fives(self): FIVE = 5 return self.dice.count(FIVE) * FIVE def sixes(self): SIX = 6 return self.dice.count(SIX) * SIX @staticmethod def score_pair(*dice): PAIR = 2 for number in range(6, 0, -1): if dice.count(number) >= PAIR: return PAIR * number return 0 @staticmethod def score_two_pairs(*dice): PAIR = 2 pairs = 0 score = 0 number = 1 while pairs < 2 and number <= 6: if dice.count(number) >= 2: pairs += 1 score += PAIR * number number += 1 if pairs == 2: return score else: return 0 @staticmethod def four_of_a_kind(*dice): FOUR = 4 for number in range(6, 0, -1): if dice.count(number) >= FOUR: return FOUR * number return 0 @staticmethod def three_of_a_kind(*dice): THREE = 3 for numero in range(6, 0, -1): if dice.count(numero) >= THREE: return THREE * numero return 0 @staticmethod def small_straight(*dice): for number in range(1, 6): if dice.count(number) != 1: return 0 return Yatzy.chance(*dice) @staticmethod def large_straight(*dice): for number in range(2, 7): if dice.count(number) != 1: return 0 return Yatzy.chance(*dice) @staticmethod def fullHouse(d1, d2, d3, d4, d5): tallies = [] _2 = False i = 0 _2_at = 0 _3 = False _3_at = 0 tallies = [0] * 6 tallies[d1 - 1] += 1 tallies[d2 - 1] += 1 tallies[d3 - 1] += 1 tallies[d4 - 1] += 1 tallies[d5 - 1] += 1 for i in range(6): if (tallies[i] == 2): _2 = True _2_at = i + 1 for i in range(6): if (tallies[i] == 3): _3 = True _3_at = i + 1 if (_2 and _3): return _2_at * 2 + _3_at * 3 else: return 0 def __init__(self, d1, d2, d3, d4, _5): self.dice = [0] * 5 self.dice[0] = d1 self.dice[1] = d2 self.dice[2] = d3 self.dice[3] = d4 self.dice[4] = _5
90b54a77f8d95c9ed18f6f117cddd37db7ea8c74
PiscesDante/Python_Crash_Course
/chapter_08/print_models.py
301
3.8125
4
def make_great(magicians_list) : new_list = [] for name in magicians_list : name += " the Great" new_list.append(name) return new_list def show_magicians(magicians_list) : magicians_list = make_great(magicians_list) for name in magicians_list : print(name)
64206e421f6ae3f4f6502b76841bcf9df7de0f89
AhmedEltaba5/Numeric-Optimization
/practical 4/Practical Session 4 Adagrad-RMSProp-Adam.py
11,611
4.59375
5
#!/usr/bin/env python # coding: utf-8 # ## Practical Work 4 # For this practical work, the student will have to develop a Python program that is able to implement the accelerated gradient descent methods with adaptive learning rate <b>(Adagrad, RMSProp, and Adam)</b> in order to achieve the linear regression of a set of datapoints. # #### Import numpy, matplotlib.pyplot and make it inline # In[529]: import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') from sklearn.metrics import r2_score import math from numpy import linalg as LA # To have a dataset or set of data points, the student must generate a pair of arrays <b>X</b> and <b>y</b> with the values in <b>X</b> equally distributed between <b>0</b> and <b>20</b> and the values in <b>y</b> such that: # <b>yi = a*xi + b (and a = -1, b = 2)</b> # # In[530]: x = np.linspace(0, 20,50) y = -1 * x + 2 # In[531]: print(x,y) # #### Plot your data points. # In[532]: plt.scatter(x,y) # ## Adagrad # ### For a single variable linear regression ML model, build a function to find the optimum Theta_0 and Theta_1 parameters using Adagrad optimization algorithm. # #### The funtion should have the following input parameters: # ##### 1. Input data as a matrix (or vector based on your data). # ##### 2. Target label as a vector. # ##### 3. Learning rate. # ##### 4. Epsilon. # ##### 5. Maximum number of iterations (Epochs). # #### The funtion should return the following outputs: # ##### 1. All predicted Theta_0 in all iterations. # ##### 2. All predicted Theta_1 in all iterations. # ##### 3. Corresponding loss for each Theta_0 and Theta_1 predictions. # ##### 4.All hypothesis outputs (prdicted labels) for each Theta_0 and Theta_1 predictions. # ##### 5.Final Optimum values of Theta_0 and Theta_1. # #### Choose the suitable number of iterations, learning rate, Epsilon, and stop criteria. # #### Calculate r2 score. Shouldn't below 0.9 # #### Plot the required curves (loss-epochs, loss-theta0, loss-theta1, all fitted lines per epoch (single graph), best fit line) # #### Try different values of the huperparameters and see the differnce in your results. # ![image.png](attachment:image.png) # In[533]: #### Adagrad Algorithm def adagrad_algorithm(x,y,learning_rate,epsilon,max_iter): final_thetas = [] cost_func = []; theta0_val = []; theta1_val = []; hypothesis_output = []; theta_0 = 0 theta_1 = 0 vt_zero = 0 vt_one = 0 i=1 while i <= max_iter : #step 2 output_hx = theta_0 + theta_1 * x hypothesis_output.append(output_hx) #step 3 j_theta = 0 j_theta = (1/(2*output_hx.size))*((output_hx - y)**2).sum() cost_func.append(j_theta) theta0_val.append(theta_0) theta1_val.append(theta_1) #step 4 #theta 0 gradient theta_0_gradient = 0 theta_0_gradient = (1/(output_hx.size)) * (output_hx - y).sum() #theta 1 gradient theta_1_gradient = 0 theta_1_gradient = (1/(output_hx.size)) * ( (output_hx - y) * x ).sum() #step 5 vt_zero = vt_zero + theta_0_gradient**2 vt_one = vt_one + theta_1_gradient**2 #next theta 0 => update theta_0 = theta_0 - (learning_rate / ( math.sqrt(vt_zero) + epsilon ))* theta_0_gradient #next theta 1 => update theta_1 = theta_1 - (learning_rate / ( math.sqrt(vt_one) + epsilon ))* theta_1_gradient gradient_vector = np.array(theta_0_gradient,theta_1_gradient) gradient_vector_norm = LA.norm(gradient_vector) if i == max_iter or gradient_vector_norm<=0.0001:#stop criteria final_theta_0 = theta_0 final_theta_1 = theta_1 final_thetas.append(final_theta_0) final_thetas.append(final_theta_1) return final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output i+=1 # In[534]: final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output = adagrad_algorithm(x,y,0.15,1e-8,1000) print("No of iterations: " , len(cost_func)) # In[535]: print(r2_score(y, hypothesis_output[-1])) # In[536]: plt.plot(range(len(cost_func)),cost_func) plt.xlabel("epochs") plt.ylabel("cost func") # In[537]: plt.plot(theta0_val,cost_func) plt.xlabel("theta zero") plt.ylabel("cost func") # In[538]: plt.plot(theta1_val,cost_func) plt.xlabel("theta one") plt.ylabel("cost func") # In[539]: for i in range(len(theta0_val)): plt.plot(x,hypothesis_output[i]) # In[540]: plt.scatter(x,y) plt.plot(x,hypothesis_output[-1],color="red") # ## Trying Different Hyperparameter # In[541]: final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output = adagrad_algorithm(x,y,0.08,1e-8,1000) print("No of iterations: " , len(cost_func)) print(r2_score(y, hypothesis_output[-1])) # In[542]: plt.plot(range(len(cost_func)),cost_func) plt.xlabel("epochs") plt.ylabel("cost func") # In[543]: plt.plot(theta0_val,cost_func) plt.xlabel("theta zero") plt.ylabel("cost func") # In[544]: plt.plot(theta1_val,cost_func) plt.xlabel("theta one") plt.ylabel("cost func") # In[545]: for i in range(len(theta0_val)): plt.plot(x,hypothesis_output[i]) # In[546]: plt.scatter(x,y) plt.plot(x,hypothesis_output[-1],color="red") # ## RMSProp # ### Update the previos implementation to be RMSProp. # #### Compare your results with Adagrad results. # ![image.png](attachment:image.png) # In[547]: #### RMSProp Algorithm def RMSProp_algorithm(x,y,learning_rate,epsilon,max_iter): beta = 0.9 final_thetas = [] cost_func = []; theta0_val = []; theta1_val = []; hypothesis_output = []; theta_0 = 0 theta_1 = 0 vt_zero = 0 vt_one = 0 i=1 while i <= max_iter : #step 2 output_hx = theta_0 + theta_1 * x hypothesis_output.append(output_hx) #step 3 j_theta = 0 j_theta = (1/(2*output_hx.size))*((output_hx - y)**2).sum() cost_func.append(j_theta) theta0_val.append(theta_0) theta1_val.append(theta_1) #step 4 #theta 0 gradient theta_0_gradient = 0 theta_0_gradient = (1/(output_hx.size)) * (output_hx - y).sum() #theta 1 gradient theta_1_gradient = 0 theta_1_gradient = (1/(output_hx.size)) * ( (output_hx - y) * x ).sum() #step 5 vt_zero = beta * vt_zero + (1-beta) * theta_0_gradient**2 vt_one = beta * vt_one + (1-beta) * theta_1_gradient**2 #next theta 0 => update theta_0 = theta_0 - (learning_rate / ( math.sqrt(vt_zero) + epsilon ))* theta_0_gradient #next theta 1 => update theta_1 = theta_1 - (learning_rate / ( math.sqrt(vt_one) + epsilon ))* theta_1_gradient gradient_vector = np.array(theta_0_gradient,theta_1_gradient) gradient_vector_norm = LA.norm(gradient_vector) if i == max_iter or gradient_vector_norm<=0.0001:#stop criteria final_theta_0 = theta_0 final_theta_1 = theta_1 final_thetas.append(final_theta_0) final_thetas.append(final_theta_1) return final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output i+=1 # In[548]: final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output = RMSProp_algorithm(x,y,0.01,1e-8,400) print("No of iterations: " , len(cost_func)) # In[549]: print(r2_score(y, hypothesis_output[-1])) # In[550]: plt.plot(range(len(cost_func)),cost_func) plt.xlabel("epochs") plt.ylabel("cost func") # In[551]: plt.plot(theta0_val,cost_func) plt.xlabel("theta zero") plt.ylabel("cost func") # In[552]: plt.plot(theta1_val,cost_func) plt.xlabel("theta one") plt.ylabel("cost func") # In[553]: for i in range(len(theta0_val)): plt.plot(x,hypothesis_output[i]) # In[554]: plt.scatter(x,y) plt.plot(x,hypothesis_output[-1],color="red") # ## Adam # ### Update the previos implementation to be Adam. # #### Compare your results with Adagrad and RMSProp results. # ![image-4.png](attachment:image-4.png) # In[555]: #### Adam Algorithm def Adam_algorithm(x,y,learning_rate,epsilon,max_iter): beta1 = 0.9 beta2 = 0.99 final_thetas = [] cost_func = []; theta0_val = []; theta1_val = []; hypothesis_output = []; theta_0 = 0 theta_1 = 0 vt_zero = 0 vt_one = 0 mt_zero = 0 mt_one = 0 i=1 while i <= max_iter : #step 2 output_hx = theta_0 + theta_1 * x hypothesis_output.append(output_hx) #step 3 j_theta = 0 j_theta = (1/(2*output_hx.size))*((output_hx - y)**2).sum() cost_func.append(j_theta) theta0_val.append(theta_0) theta1_val.append(theta_1) #step 4 #theta 0 gradient theta_0_gradient = 0 theta_0_gradient = (1/(output_hx.size)) * (output_hx - y).sum() #theta 1 gradient theta_1_gradient = 0 theta_1_gradient = (1/(output_hx.size)) * ( (output_hx - y) * x ).sum() #step 5 mt_zero = beta1 * mt_zero + (1-beta1) * theta_0_gradient vt_zero = beta2 * vt_zero + (1-beta2) * theta_0_gradient**2 #correction mt_zero_corrected = mt_zero / (1-beta1**i) vt_zero_corrected = vt_zero / (1-beta2**i) mt_one = beta1 * mt_one + (1-beta1) * theta_1_gradient vt_one = beta2 * vt_one + (1-beta2) * theta_1_gradient**2 #correction mt_one_corrected = mt_one / (1-beta1**i) vt_one_corrected = vt_one / (1-beta2**i) #next theta 0 => update theta_0 = theta_0 - (learning_rate / ( math.sqrt(vt_zero_corrected) + epsilon ))* mt_zero_corrected #next theta 1 => update theta_1 = theta_1 - (learning_rate / ( math.sqrt(vt_one_corrected) + epsilon ))* mt_one_corrected gradient_vector = np.array(theta_0_gradient,theta_1_gradient) gradient_vector_norm = LA.norm(gradient_vector) if i == max_iter or gradient_vector_norm<=0.0001:#stop criteria final_theta_0 = theta_0 final_theta_1 = theta_1 final_thetas.append(final_theta_0) final_thetas.append(final_theta_1) return final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output i+=1 # In[556]: final_thetas,cost_func,theta0_val,theta1_val,hypothesis_output = Adam_algorithm(x,y,0.01,1e-8,1000) print("No of iterations: " , len(cost_func)) # In[557]: print(r2_score(y, hypothesis_output[-1])) # In[558]: plt.plot(range(len(cost_func)),cost_func) plt.xlabel("epochs") plt.ylabel("cost func") # In[559]: plt.plot(theta0_val,cost_func) plt.xlabel("theta zero") plt.ylabel("cost func") # In[560]: plt.plot(theta1_val,cost_func) plt.xlabel("theta one") plt.ylabel("cost func") # In[561]: for i in range(len(theta0_val)): plt.plot(x,hypothesis_output[i]) # In[562]: plt.scatter(x,y) plt.plot(x,hypothesis_output[-1],color="red") # ## Congratulations # ![image.png](attachment:image.png)