blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
2d98185a02e977585b4a2c473bde4b1f36b9605f
DEEPTHA26/guvi
/codekata/armstrong.py
127
3.65625
4
a=int(input()) temp=a sum=0 while(a>0): r=a%10 sum=sum+(r*r*r) a=a//10 if(temp==sum): print("yes") else: print("no")
c6e41bcb00aa0bf16b64392840dfb55ef7c1f115
mrcosta/pythonchallenges
/codagem/submissions/careem.py
1,559
3.625
4
def consecutive(num): count = 0 times = 0 for current in range(1, num + 1): sum = current next = current + 1 while (sum < num): sum+= next if (sum == num): count+= 1 next+=1 times+=1 print(times) return count d...
7e4219a2ab8a2380c289902eeebf783ff0eeb8d5
ClodaghMurphy/dataRepresentation
/Week9/Walkthrough/server.py
3,531
3.78125
4
#This code is recycled from Lecture week 8 #+++++++RUNNING INSTRUCTIONS++++++++ #either server.py OR # SET FLASK_APP=server # echo %FLASK_APP% #(now flask run will work!) #url_for otherwise that app won't work #request to get your data import request object see also week 5code #redirect seamlessly redirects them to an...
53278384c43040cc338634ce14edead946b604a0
ClodaghMurphy/dataRepresentation
/Week6/lab06.01.05-getgithub.py
862
3.609375
4
#Challenge read from github: #5. Create a spread sheet that gets all the users that are following me (datarepresentationcourseware) and # outputs the users login and repos URL to a spreadsheet. #a. Get the list from the the github API and output to the console (messy) #b. Then output it to a file neatly import requ...
ab6bbe77a52513a743a05cbd3c858b943c6992fa
junyi1997/Python_class_Final_project
/test/menu.py
748
3.640625
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 9 15:36:57 2019 @author: user1 """ import tkinter as tk #from tkFileDialog import askopenfilename def NewFile(): print ("New File!") def OpenFile(): print ("Open File!") def About(): print( "This is a simple example of a menu") root = tk.Tk() menu = tk.Men...
1c7c049efb21773be5ec997a69d89b9ff1ca0a16
BioMining/k-Means-and-k-NN
/Question3.ckulkarn.py
4,124
4.25
4
#!/usr/bin/python import sys ''' This program is used to implement the k-means algorithm. ''' '''This function is used to print the correct usage for running the program. ''' def usage(): return "python\t<Question3.ckulkarn.py>\t<Initial_Cluster_Centers>\t<Data_Points>\t<K-value>" def extract_intial_cluster_cente...
7dbdb3d789642184a569d567b5e0c96941ef73d3
AmazingPopularo/Python_tutorial_code
/timer.py
493
4.375
4
import time #python has a built in module to help us with time # variable for the timer seconds = int(input("How long should the timer be? (number only):")) #now we create the actual timer for i in range(seconds): print(str(seconds-i) + " second(s) remain") #print("Loading..." + str(seconds - i)) # or ...
12803ba255041ea4a1fae0b2ca3557cb071cb7db
mlabuda2/DesignPatterns
/01Singleton/Students/2018/AdrychowskiDariusz/singleton.py
669
3.71875
4
import time class Singleton(object): class __Singleton: def __init__(self): self.val = None #def __str__(self): # return 'self ' + self.val instance = None def __new__(cls): if not Singleton.instance: Singleton.instance = Singleton.__Singleton() ...
9093c1c231f9308013c64c21fd96033369d42965
tamcb2708/python1
/viet.py
1,576
3.53125
4
import numpy as np import pandas as pd df_house = pd.read_csv("data/housing.csv") #df_house = df_house.sample(frac=1) print (df_house.shape) print (df_house.head(10)) list = ["Avg. Area Income", "Avg. Area House Age", "Avg. Area Number of Rooms", "Avg. Area Number of Bedrooms", "Area Population"] X = df_house[list]...
deddd638918229a94685e5545375be4f64ba0fe6
alwinjoseph7/CVcodes
/finder.py
265
3.5625
4
import cv2 import numpy as np # Load image im = cv2.imread('red.jpeg') # Define the blue colour we want to find - remember OpenCV uses BGR ordering blue = [42,0,213] # Get X and Y coordinates of all blue pixels X,Y = np.where(np.all(im==blue,axis=2)) print(X,Y)
e2a42351143da75b17e76ee8907b2d7c9b95a932
jkkimGH/learning-opencv
/contours.py
2,892
4.15625
4
# OpenCV Tutorial 6 import cv2 as cv import numpy as np # Contours are basically the boundaries of an object. However, in a mathematical POV, these are not the same as edges. # But in programming, you can get away with thinking contours as edges because they are sort of the edges of the image # - They are the curves ...
163d6ae20ac0a2759eb1809405e5db5bda1855b9
jkkimGH/learning-opencv
/draw.py
1,521
4.0625
4
# OpenCV Tutorial 3 import cv2 as cv import numpy as np # Creating a blank window to draw on with numpy # Give it a shape tuple length of 3: first two are height and width. # The last is the number of color channels, in this case BGR (Blue Green Red) blank = np.zeros((500, 500, 3), dtype='uint8') cv.imshow('Blank', b...
5eee4ed0801f8e9e7d9e1e3ed7b5c5a6f35ea7fa
prabal1997/Cracking-The-Coding-Interview-Python
/linked_lists/2_8.py
911
3.84375
4
import sys from node import * #input params input_list_1 = list([1, 9, 3, 6, 5, 11, 3, 2]); linked_list_1 = node(); linked_list_1.make_list(input_list_1); index_to_loop = [5, 3]; linked_list_1.give_node(index_to_loop[0]).next = linked_list_1.give_node(index_to_loop[1]); #solution: we use two poniters moving at diff...
6bd6d86ce679361ed2697762ba7c44faf122f9d8
prabal1997/Cracking-The-Coding-Interview-Python
/graphs_and_trees/tree.py
10,323
3.765625
4
import sys sys.path.append('../linked_lists'); from node import * from collections import deque #make a tree class class binary_tree: def __init__(self, input_array=[]): #initialize tree self.root = None; self.count = 0; self.ref_list = []; #set tree attributes...
35497336ae8ead876f06bf88dff026cc4a96fc25
prabal1997/Cracking-The-Coding-Interview-Python
/arrays_and_strings/1_6.py
605
3.609375
4
import sys input_string = "aaaaaaaaaaaaaabca"; #compressing string index = 1; input_list = [ [input_string[0], 1] ]; while(index < len(input_string)): if (input_string[index] == input_string[index-1]): input_list[-1][1] += 1; else: input_list.append([input_string[index], 1]); index += 1; ...
0f328b2ac4d044ce55afd979b638d7a910282c2b
prabal1997/Cracking-The-Coding-Interview-Python
/stacks_and_queues/3_4.py
2,094
3.984375
4
import sys class MyQueue: #initialize the main, buffer queues def __init__(self, input=[]): self.main_stack = []; self.buffer_stack = []; self.enqueue(input); #enqueue-ing a list of input data def enqueue(self, input_list): #very basic error checking ...
4d230be2ae3be662fa495fcbb0114b053b7db07e
prabal1997/Cracking-The-Coding-Interview-Python
/arrays_and_strings/1_2.py
1,329
4.09375
4
import sys input_string_1 = "test"; input_string_2 = "tTtt"; #we make an assumption, and then try to disprove it is_permutation = True; #we hash the first string, then second string, and compare the frequency of letters in each if (len(input_string_1) != len(input_string_2)): is_permutation = False; else: #h...
7bc6cecf81b187c4daf08b8ed734fe94c23644c6
andrikoulas7/python_examples
/PassGen.py
252
3.84375
4
import string from random import* characters = string.ascii_letters + string.punctuation + string.digits password = "".join(choice(characters)for x in range(randint(8,8))) print("Password Generator") print() print("Your new password is: " + password)
01a8b09833cb750345f9d9c681220fad3c46f9fe
shravankt/python
/Black-Jack-Using-Classes.py
7,336
3.734375
4
import random class Player(object): Wins = 0 Losses = 0 Busts = 0 amount = 0 def __init__(self,bank): self.bank = bank def bet_ammount(self): self.amount = int(raw_input("Enter amount you want to put as betting:")) def win_balance(self): self.bank += self.amount ...
e91f8dab1aa979fec8d04807c9d17eca70a6072b
shravankt/python
/guessing-game-2.py
941
3.765625
4
import random import time si = random.randint(0,101) print "hey user Think of a integer of your choice between 0 to 100 \nlet's start now" #print si time.sleep(5) running = True attempt = 0 while running: print "You gussed No.", si answer = raw_input("Is it a correct guess or not: y/n:") if "y" in answer.lower():...
7829892934fd7d08d5fbb345158b6a53e707ee72
DavidLegg/PhysicsUtils
/computation.py
2,068
3.84375
4
from utils.quantity import Quantity def sqrt(value): '''Square root that works for Unit or Quantity as well.''' return value**0.5 def kahan_sum(iterable, start = 0): '''Low-error Kahan Summation. Taken from https://en.wikipedia.org/wiki/Kahan_summation_algorithm''' total = start c = 0*start fo...
4708d9c8037e52ea8b388edb5f2b5fc27873ed7b
rogerlog/python-studies
/intro/initialExamples.py
1,154
4.125
4
print("Hello, World!") x = int(1) y = float(2.8) z = str(3.0) thislist = ["apple", "banana", "cherry"] print(thislist) thislist = ["apple", "banana", "cherry"] if "apple" in thislist: print("Yes, 'apple' is in the fruits list") thistuple = ("apple", "banana", "cherry") print(thistuple) thisset = {"apple", "ban...
c1a716f307ee93517be21488e8b4c1d6ae3a62c1
rogerlog/python-studies
/intro/pythonOperators.py
1,846
4.34375
4
#Addition x = 5 y = 3 print(x + y) #Subatraction print(x - y) #Multiplication print(x * y) #Division print(x / y) #Modulus print(x % y) #Assignment print(x) #Exponentiation print(x**y) #Floor division print(x//y) #Python Comparison Operators """ == Equal x == y != Not equal ...
49501b53052fdfcce98c7ceaeceecaf17614e2c0
felipemfp/py-exercicios
/exercicios-iii/questao1.py
636
4.0625
4
# Implementar um gerador de números primos def is_prime(number): """ Verify if number is prime """ if number < 2: return False elif number == 2: return True elif number % 2 == 0: return False else: for x in range(2, number): if number % x == 0: return False else: return True def prime_numbers(...
1d390eb2105234330672731276a24ed5ff1fde94
felipemfp/py-exercicios
/exercicios-ii/questao1.py
609
4.375
4
# Implementar um programa que receba um nome de arquivo e # gere estatísticas sobre o arquivo (número de caracteres, # número de linhas e número de palavras) def read_file(fn): count_chars, count_lines, count_words = 0, 0, 0 for line in open(fn).readlines(): count_lines += 1 if line: count_chars += len(line)...
6f20e5ce8af2c61aa9e0c1676691093563641254
felipemfp/py-exercicios
/exercicios-i/questao1.py
582
4.625
5
# Implementar duas funções: # - Uma que converta temperatura em graus Celsius para Fahrenheit # - Outra que converta temperatura em graus Fahrenheit para Celsius def celsius_to_fahrenheit(degrees): return 9 / 5 * degrees + 32 def fahrenheit_to_celsius(degrees): return (degrees - 32) * 5 / 9 print("Celsius para F...
da0e1846c5b2bc79b14aad1f6bc8e2de2a40cca5
fongoses/seguranca-2013-2
/06 - Geração de Chaves de Sessão/largestPrimeFactor.py
3,647
3.875
4
""" The original code for the following program was written by Sangam Kumar Jain and can be found in the file test.py in this git project You can connect with him at: http://www.facebook.com/jain.sangam The code was written as a part of solving Project Euler Problem 3 (http://projecteuler.net/problem=3) which deal...
5a1a54ab2f68e94a5dacdc7d465daa73c7e50bf4
bashikan/python
/aisatu.py
562
3.96875
4
import datetime def aisatuk(): dt_now=datetime.datetime.now() year=dt_now.year month=dt_now.month day=dt_now.day hour=dt_now.hour minute=dt_now.minute print('{}/{}/{}'.format(year,month,day)) print('{}:{}'.format(hour,minute)) if hour>=3 and hour<=9: print('おはよう!、足立佳奈だよ') ...
cc217eebb80d1bb6c657ac08c4e6636ea61d5931
bashikan/python
/kurasu.py
1,404
4.15625
4
# class Member: # '''スポーツクラブの会員クラス''' # def __init__(self,no:int,name:str,weight:float) -> None: # #コントラクタ # self.no=no #会員番号 # self.name=name #指名 # self.weight=weight #体重 # def print(self)->None: # #データの表示 # print(('{}:{} {}kg'.format(self.no,self.name,sel...
dd3e75507ce489691989bc4cb5cb00c66cfcf7a2
martamaslankowska/Stratego
/computer_loop.py
24,930
3.671875
4
import pygame from variables import * # from mainloop import * from drawing import * import copy import time import math import random # Initialize the game engine pygame.init() # Loop until the user clicks the close button. done = False clock = pygame.time.Clock() pygame.time.set_timer(pygame.USEREVENT, 1000) pygam...
e877ede9c618c5b21ceb138b6ff57f3cb15f81a2
wtkleonard/math480
/AmericanOption.py
5,659
3.671875
4
""" Provides classes and methods to compute the prices of American options under the CRR binomial tree model. We only consider American options which are Markovian in the sense that the payoff depends only on the current stock price. The user can define an American option by specifying a payoff function. The algorithm ...
68c4bce40f6d35946a2ac42df030bdcf9b6bcb44
plibither8/iiitd_cse101-ip
/tests/parth.py
631
3.984375
4
import json import math import os import random import re import sys # # Complete the 'Nested_sum' function below. # # The function is expected to return an INTEGER. # The function accepts STRING num_list as parameter. # def Nested_sum(num_list): # Write your code here final_sum = 0 num_list = json.load(...
6a58fa3508d8c44d145fe52785175f691450966c
Tunna/List-Exercises
/while_fun_loops.py
322
3.765625
4
# i = 1 # while (i < 21): # print i, # i = i + 1 # i = 1 # while (i < 21): # if i == 13: # print "Hello" # else: # print i, # i = i + 1 # i = 0 # while (i < 101): # print i, # i = i + 10 list_2 = ["apples", "oranges", "bananas"] fruit = 0 while fruit < len(list_2): print list_2[fruit] fruit = fruit + ...
85b0e9b3eb4df29907d55b163c883c26d8bd4acb
CoderDojoLu/py-club
/Fractals/python/turtle/DragonCurve_pythonic.py
378
3.53125
4
from turtle import right, left, forward, speed, exitonclick, hideturtle def dragon(level=4, size=200, zig=right, zag=left): if level <= 0: forward(size) return size /= 1.41421 zig(45) dragon(level-1, size, right, left) zag(90) dragon(level-1, size, left, right) zig(45) spe...
75548fed6500bf208c48936357c5269a1dadf821
CoderDojoLu/py-club
/pygame/kepler.py
3,294
4.0625
4
#Kepler's Laws.py # plots the orbit of a planet in an eccentric orbit to illustrate # the sweeping out of equal areas in equal times, with sun at focus # The eccentricity of the orbit is random and determined by the initial velocity # program uses normalised units (G =1) # program by Peter Borcherds, Universit...
5acc9dddd6ca50276ee7cbd7b6172458dcb72bc1
CoderDojoLu/py-club
/class.py
1,447
3.9375
4
#!/usr/bin/env python3 import sys import platform class Animal: def talk(self): print('I cannot talk') def walk(self): print('I can walk') def clothes(self): print('I do not need clothes') class Duck(Animal): ##def __init__(self, color = 'white'): ## self._color = color ##def __init__(self, **kwargs): ## self...
39108ba827ca9ece16698e3adf34905779b73237
moonso/iker_first
/iker_first/cli.py
7,085
3.59375
4
import click import sys import locale import random import difflib def get_answer(integer=True): """Ask user for a answer. Check if answer is correct and return it """ answer = input('Svar: ') print(type(answer)) # answer = input().decode(sys.stdin.encoding or locale.getpreferredencoding(True)...
1a8285c16b776d70d960c9bad6b8d293d77703d0
PancakeTornado/playground
/x.py
837
3.53125
4
class FamilyFeud: def buzzer(self, height, char='X'): char_pos = 0 for row_num in range(0, height): line = [] for col_num in range(0, height): # Always print entire first and last row if row_num in [0, height - 1]: line....
311e6614de84852c41c5a3f8897f87e93a31089c
centem/test-repo
/wpe1_travel.py
1,176
3.84375
4
# wpe1_travel from __future__ import print_function places = dict() while True: response = raw_input("Tell me where you went:") if len(response) == 0: break else: try: place = response.split(',') country = place[1] city = place[0] ...
8fe70d7eb99944a56465836ca85de2767c871a7f
Aniketttttttewariii/HacktoberFest-21
/Programs/Circular-linkedlist.py
883
3.875
4
class Node: def __init__(self, my_data): self.data = my_data self.next = None class circularLinkedList: def __init__(self): self.head = None def add_data(self, my_data): ptr_1 = Node(my_data) temp = self.head ptr_1.next = self.head if self.head is not None: ...
772fcbca02996715d46afa343af6786ffb3a9c5d
EnzoGarofalo/Python
/Ex_3.py
416
4.1875
4
#Imprima um Número # aprenda as diferenças entre as funções raw_input() e input() # usando o inputa funfa deboas, mas para versões de python antigos gera uma exeção NameErrror: "input" num = input("Digite sua Idade: ") print ('Você tem', num, 'anos') #você resolve usando raw_input(), isso apenas para pythons de vers...
d26ab25db9d5a39f7608471a593839f9b82965af
psharma228/Python3
/Python Mini Projects/passGen.py
793
3.6875
4
import random def shuffle(string): tempList = list(string) random.shuffle(tempList) return ''.join(tempList) #Add 2 upper case characters uppercaseLetter1= chr(random.randint(65,90)) uppercaseLetter2= chr(random.randint(65,90)) #Add 2 Lower case characters lowercaseLetter1= chr(random.randint(97,122)...
6090e3ef8818c009fffa4643873e3168b370239f
Sindhujavarun/Training
/Python/npowern.py
190
4.34375
4
# print n to the power of n. powernumber = int(input("Enter a number to find n to the power of n: ")) print(powernumber, "to the power of", powernumber,"is: ",powernumber ** powernumber)
c91f70205baef39d9f8fcfb083d88a765e317f19
Sindhujavarun/Training
/Python/tablesBook.py
694
4.21875
4
# print tables book. print('Multiplication table') startTableNumber = int(input('Enter a number from which the multiplication table is to be printed: ')) endTableNumber = int(input('Enter a number upto which the multiplication table is to be printed: ')) countOfRows = int(input('Enter the number of rows needed in...
dbb5654f663b3ab7e052bf201cadab2e625040ce
sirenatroxa/python
/practice/cast.py
211
3.953125
4
a = input( "Enter A Number: " ) b = input( "Now Enter Another Number: " ) sum = a + b print( "\nData Type sum :" , sum , type(sum ) ) sum =chr( int( sum ) ) print( "Data Type sum :" , sum , type( sum ) )
8ab3f53cc2150783677f927b9ba32067a52b844b
JeremyJMoss/MileToKmConverter
/main.py
718
3.796875
4
from tkinter import * window = Tk() window.title("Mile to Km Converter") window.config(padx=20, pady=30) def output_kms(): miles = int(entry.get()) kms = round(miles * 1.609) km_output.config(text=kms) entry = Entry(width=10) entry.insert(END, string="0") entry.grid(column=1, row=0) l...
182583ad38d2ec6d47ff38f3eb0c26d209a7d2d6
RupanjanDas/pythontutorials
/revision1prograam6.py
236
3.5625
4
x = [1, 17, 3, 5, 6, 8, 34, 32, 121, 11, 9, 13] y = int(input("enter an integer")) b = 0 while b < len(x) and x[b]!= y: if x[b] == y: print(x[b]) b = b + 1 if b == len(x): print('"not exist"') else: print(b,x[b])
d7698b2fa762c7a8d4246417c6ac064b9c7fbfbd
dasom0801/python-for-everybody
/getting-started-with-python/ex_02_03.py
232
3.796875
4
xh = input("Enter Hours: ") xr = input("Enter Rate: ") #input이 반환하는 것은 문자열 #문자열 * 문자열을 하면 에러가 발생하기 때문에 숫자로 형변환 필요 xp = float(xh) * float(xr) print("Pay:", xp)
abe761ed947f5b0f399823b7b8d6ad679bb25a2c
ashlitaylor/Biodegradation
/util.py
6,510
3.8125
4
from scipy import stats import numpy as np import math #* This method computes entropy for information gain def entropy(class_y): #* Input: #* class_y : list of class labels (0's and 1's) #Compute the entropy for a list of classes #* #* Example: #* entropy([0,0,0,...
641315ef78b70485d2d1ef5f1b00845bb123c4fd
rossdrucker/python_common_functions
/common_functions.py
5,510
3.625
4
# -*- coding: utf-8 -*- """ Useful Python functions I use repeatedly @author: Ross Drucker """ import os import time import numpy as np import math import sys import datetime sys.path.insert(0, function_library) import UnitConversions as convert # =====================================================...
701a7a3606a39773854db9fb61b3905f6305a9af
whiz-Tuhin/Python-Stuffs-
/list_slicing.py
153
3.53125
4
mylist = list('jaishreedhage') print mylist mylist[8:] = list('khare') print mylist name = list('tuhinkhare') name[5:] = list('patgaokar') print name
5e9f2f947d75d4b9ebc713225afe64b3950ad05e
markgu713/python-challenge
/PyBank/main.py
1,928
3.546875
4
import os import csv csvpath = os.path.join("..", "PyBank", "Resources", "budget_data.csv") date= [] change = [] with open(csvpath, encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csvheader = next(csvreader) # return total number of months and sum of profit/loss numOfMont...
4c8b1696c28991d0e237da5ae3c3ae9ac2605216
avrudik/easy_it
/practice/prime_number.py
198
3.890625
4
def prime_number(num): d = 2 while num % d != 0: d += 1 return d == num if __name__ == '__main__': n = int(input('Введите число: ')) print(prime_number(n))
a4b22cfa66b445d1b6edab1b8a744c2b29a49d13
avrudik/easy_it
/course_tasks/and/hmw_1/task_3.py
379
3.96875
4
def do_it(data, sub): data = data[data.find(sub) + len(sub):] return 1, data input_str = input('Input some string: ') sub_str = input('Input a sub-string: ') answer = 0 while input_str and sub_str in input_str: sum, input_str = do_it(input_str, sub_str) answer += sum else: print('String is over or ...
649c471cf2581ca1d376e24a6f8c7318e16ca1d5
munishdeora/python_training_2019
/Day 4/operation.py
1,721
4.375
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 12:40:58 2019 @author: de Code Challenge Name: Operations Function Filename: operation.py Problem Statement: Write following functions for list operations. Take list as input from the User Add(), Multiply(), Largest(), Smallest(), Sorting(), R...
8fd5a5030525a38200599c6353532f96c9fcc1cf
munishdeora/python_training_2019
/Day 1/temp_cal.py
748
4
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 24 11:21:18 2019 @author: de """ """ Code Challenge Name: Temperature Calculator Filename: temp_cal.py Problem Statement: Assume today's temperature in Jaipur is 29 degree Centigrade. Calculate the temperate in Degree Fahrenheit and print it. ...
f852604da929b92bac50df8d7f994130af70221c
munishdeora/python_training_2019
/Day 4/book_shop1.py
2,114
3.75
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 12 16:35:57 2019 @author: de """ """ Code Challenge Name: Book Shop Filename: book_shop1.py Problem Statement: Imagine an accounting routine used in a book shop. It works on a list with sublists, which look like this: Order Number Bo...
0079bc8e11fcf92fb969c3382b80512f8c231aa2
munishdeora/python_training_2019
/Day 1/heartrate_cal.py
1,053
4
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 23 17:04:21 2019 @author: de """ """ Code Challenge Name: Target Heart Rate Calculator Filename: heartrate_cal.py Problem Statement: Calculate the Maximum Heart Rate and Target Heart Rate Range ( Lower and Higher value ) of a person of a specific...
fa62086ea3921a26bd443012246d1ad93d11da2d
munishdeora/python_training_2019
/Day 4/reverse.py
517
4.125
4
# -*- coding: utf-8 -*- """ Created on Wed Aug 7 11:51:17 2019 @author: de Code Challenge Name: Reverse Function Filename: reverse.py Problem Statement: Define a function reverse() that computes the reversal of a string. Without using Python's inbuilt function Take input from User I...
3c076f7848ffa0bcd5446e4c329e636947d9b825
munishdeora/python_training_2019
/Day 4/centered.py
1,014
4.09375
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 8 18:52:28 2019 @author: de """ """ Code Challenge Name: Centered Average Filename: centered.py Problem Statement: Return the "centered" average of an array of integers, which we'll say is the mean average of the values, except ignoring the lar...
336048cacb234c027d66114e871f1daa55ce584e
munishdeora/python_training_2019
/Day 2/city_temp.py
493
4
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 24 14:54:29 2019 @author: de """ """ Code Challenge Name: Temperature of City Filename: city_temp.py Problem Statement: Print the temperature of your city in Degree Celsius for the day Hint: Use \u00b0 as the unicode for Degree Input: ...
0d2b57cb029097e42e621683bd08907a78212ab5
6v6/algorithm-for-codingTest2
/boj/boj12100.py
1,283
3.53125
4
import sys from copy import deepcopy from collections import deque max_value = 0 def move(board, n): temp = [[0]*n for _ in range(n)] for x in range(n): flag = 0 target = -1 for y in range(n): if board[y][x] == 0: continue if flag == 1 and boar...
c824fd1884b5d04e2dbd69645eafc7d1f0077a29
unsortedtosorted/elgoog
/medium/string/findAndReplacePattern.py
967
3.53125
4
""" #890 Find and Replace pattern 1. Runtime : O(P + W*N ) """ class Solution: def findAndReplacePattern(self, words, pattern): """ :type words: List[str] :type pattern: str :rtype: List[str] """ p="" pm={} for i...
ca781441d45059ec856581e71db420135dd34541
unsortedtosorted/elgoog
/Easy/bfs/orangesRotting.py
1,807
3.5
4
""" 994. Rotting Oranges """ class Solution(object): def orangesRotting(self, grid): """ :type grid: List[List[int]] :rtype: int """ self.max = 0 self.marked = set() def markadj(x,y,curr): ...
67995a13183537d7989e1e5228b9e97fcd28bb3d
unsortedtosorted/elgoog
/medium/linkedlist/numComponents.py
664
3.5
4
""" 817. Linked List Components 1. check if curr in list and curr.next also in list, if yes continue 2. if curr in list and curr.next not in list, then count +=1 return count Run time : O(N) """ class Solution(object): def numComponents(self, head, G): """ :type head: ListNode :type G: L...
0e2f70792a3be80417a521cc1510df31ccab8206
unsortedtosorted/elgoog
/Easy/design/MaxStack.py
1,217
4.125
4
""" 1. Max Stack use regular stack Find what operation is going to take place the most for top : find max in O(N) for popmax: find max and remove it from the stack """ class MaxStack(object): def __init__(self): """ initialize your data structure here. """ self.arr = [] ...
0c774a3b949ff6929deb1ed0d964cea7c55df1aa
unsortedtosorted/elgoog
/medium/trees/preorderTraversal.py
899
3.921875
4
""" 144. Binary Tree Preorder Traversal Steps: 1. Add root to stack 2. until length of stack is greater than zero, do: 1. curr = pop 2. add curr.val to result 3. push curr.right to stack 4. push curr.left to the stack RunTime : O(N) """ # Definition for a binary tre...
87c310e05b77897c52eba4d926ad86219d769110
unsortedtosorted/elgoog
/medium/trees/countUnivalSubtrees.py
1,199
3.546875
4
""" 250. Count Univalue Subtrees """ class Solution(object): def countUnivalSubtrees(self, root): """ :type root: TreeNode :rtype: int """ self.count = 0 def backTrack (root): l = True r = True if...
45fef73c430ec33f6132a23409d8a050623095e6
unsortedtosorted/elgoog
/medium/Arrays/totalFruit.py
1,710
3.546875
4
""" #904 1. Maintain a set with size at most 2 2. If a curr is in set, add it to the window 3. If curr is not in set, get the prev of curr 4. remove all elements from the window untill only prev is present 5. add curr to the window 6. if lenght of the window is larger than last one, update max return max """ ...
3994ff730390f1e8883a52aaa1b290531e4b3064
unsortedtosorted/elgoog
/medium/Arrays/maxChunksToSorted.py
1,741
3.90625
4
""" 769. Max Chunks To Make Sorted 2 algo's: Slower: 1. Divide the array into 2 halves: -- first half : arr[:i+1] -- second half : arr[i+1:] 2. If max of first half is less than the min of the second half, then we have found a chunk else continue to expand first chunk Run time : ...
2375a70e597ee454c3ae746f3fe97b9831757920
unsortedtosorted/elgoog
/medium/trees/isSubtree.py
1,261
3.78125
4
""" #572. Subtree of Another Tree 1. Do DFS of first Tree, if node equal to root of another tree, do preorder traversal together and return if True if traversal is same 2. if no Node is equal to root of another tree , return False RunTime : O (N*M) """ class Solution: def isSubtree(self, s, t): """...
218848c3b059435d5139e1f91deffe8cf1828d74
AyaAymanMohamed/Image_Captioning_Engine
/word_generator.py
2,016
3.671875
4
""" Creates a data generator that inputs the encoded words and features to the LSTM model Implemented by: Nada Ibrahim """ import numpy as np from keras.utils import to_categorical def word_generator(batch_size, dictionary_size, num_steps, features_length, features_path, annotations_path): """ Generate data ...
4ee6fad730aefec25ba5015eaed9ae4854a20e9a
veeps/MIT_Python
/ps_1c.py
1,364
3.890625
4
n#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 23 21:04:17 2019 @author: vivianpeng """ annual_salary = float(input("Enter your annual salary: ")) rate_of_return = 0.04 semi_annual_raise = .07 monthly_rate_of_return = rate_of_return / 12 monthly_salary = annual_salary / 12 down_payment = 250...
052f34fbf51d7d09f711c5372a3aa62512e69e2b
rdincher/CompSCI755
/MonoalphabeticCiphers/frequencyAnalysis.py
3,729
4.25
4
import argparse import re from string import ascii_lowercase as lower, ascii_uppercase as upper parser = argparse.ArgumentParser() # Take arguments for the cipher text as well as where to print the frequency analysis parser.add_argument("-i", "--inputFile", help="Path and name of the file to read in") parser.add_argum...
df55ec74adf4e8f78c0fa625103247468099315e
IanYHWu/debate_breaker
/src/run_breaker.py
3,059
3.71875
4
""" Main program for debate breaker. Simulates many tournaments to obtain the break statistics """ from collections import Counter import breaker_class import input_reader import sys def simulation(input_file): """Simulate many debate tournaments using input from the read_input function in input_reader""" #...
9163a6e40a7b6d3d9b76b8c922628c17b9cba563
aakanksha-otari/python-programming-lab
/fibonacci.py
223
3.53125
4
()) l=[] a=0 b=1 count=0 if n<=0: print("Series does not exist") elif n==1: print("0") elif n==2: print("1") else: l.append(0) l.append(1) while count<n-2: l.append(a+b) c=a+b a=b b=c count+=1 print(l)
cad82baa3df22dfe27d8cdd61b37190820ea2c37
Badrain/Leetcode
/Basic algorithm/Quick_sort.py
711
4
4
# coding = utf-8 # 快排主函数 def quick_sort(l, left, right): if left>=right: return index = part_sort(l, left, right) # 递归 quick_sort(l, left, index-1) quick_sort(l, index+1, right) def part_sort(l, left, right): start = left # 枢纽值的序号 key = l[left] # 枢纽值 while(left<righ...
faea4dec35c194a3fc32a1bc65015a9ee9ace4d4
tenqaz/crazy_arithmetic
/算法/冒泡排序.py
990
4.15625
4
""" 冒泡排序 两两交换,将大的值往后放。 """ from typing import List def bubble_sort(arr: List[int]): """ 如果前面的值大于后面的值,则交换位置。 """ arr_len = len(arr) for i in range(arr_len): for j in range(arr_len - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], a...
c8d644bc0ff209c8f31ce22d37c9588f6c40fc47
tenqaz/crazy_arithmetic
/leetcode/111_二叉树的最小深度.py
1,801
3.609375
4
""" @author: Jim @project: crazy_arithmetic @file: 111_二叉树的最小深度.py @time: 2020/1/30 0:09 @desc: 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最小深度  2. """ from tools.tree_node_tools import make_Treelist class...
3515829d863ecd3720f9467c8ac1a1f3927c34ec
tenqaz/crazy_arithmetic
/leetcode/300_最长上升子序列.py
892
3.765625
4
""" @author: Jim @project: crazy_arithmetic @file: 300_最长上升子序列.py @time: 2020/2/8 20:45 @desc: https://leetcode-cn.com/problems/longest-increasing-subsequence/ [10,9,2,5,3,7,101,18] """ from typing import List class Solution: def lengthOfLIS(self, nums: List[int]) -> int: """ 动态规划 ...
394112ff4065ee23124a4e4bdf7fb2475d70a8a5
tenqaz/crazy_arithmetic
/算法/插入排序.py
440
4.21875
4
def insert_sort(arr): """ 插入排序 Args: arr: Returns: """ arr_len = len(arr) for i in range(1, arr_len): val = arr[i] for j in range(i - 1, -2, -1): if val < arr[j]: arr[j + 1] = arr[j] else: break arr[...
1c27f8eca53b5cde7fc51a2c1a9fca9f49eb890f
tenqaz/crazy_arithmetic
/leetcode/344_反转字符串.py
687
3.703125
4
""" 编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。 你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。 https://leetcode-cn.com/problems/reverse-string/ """ class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-plac...
5490971e975bfcce10ccd1b9ffe2100189e5ad3c
tenqaz/crazy_arithmetic
/leetcode/122_买卖股票的最佳时机二.py
2,434
3.671875
4
""" @author: Jim @project: crazy_arithmetic @file: 122_买卖股票的最佳时机二.py @time: 2020/1/16 22:47 @desc: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: [7,1,5,3,6,4] 输出: 7 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 =...
43f886de44df2ec41e58ed7821bceffb35a95d9a
tenqaz/crazy_arithmetic
/leetcode/21_合并两个有序链表.py
1,396
3.796875
4
""" https://leetcode-cn.com/problems/merge-two-sorted-lists/ 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 """ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def print_linkedlist(head: ListNode): print("--------分割线------") while head: ...
1e8959090825c864e325537dd7289621d0158277
tenqaz/crazy_arithmetic
/leetcode/5268_找出两数组的不同.py
478
3.5625
4
""" @author: Jim @project: crazy_arithmetic @file: 5268_找出两数组的不同.py @time: 2022/3/27 19:37 @desc: 使用Set类型,可以进行差集获取到结果。 """ from typing import List class Solution: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: nums_set = set(nums1) nums2_set = set(nums2) ...
12ffe669bc298465d566e2cc2679b456b4e7a12d
tenqaz/crazy_arithmetic
/leetcode/139_单词拆分.py
1,021
3.640625
4
""" @author: Jim @project: crazy_arithmetic @file: 139_单词拆分.py @time: 2021/9/20 18:37 @desc: https://leetcode-cn.com/problems/word-break/ """ from typing import List class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: """ 动态规划 """ s_bool = [False for i in ra...
239fdce70b51f1475ea4ea87c4ef28f8802c43b0
tenqaz/crazy_arithmetic
/算法/二叉查找树.py
2,628
3.78125
4
""" @author: Jim @project: crazy_arithmetic @file: 二叉查找树.py @time: 2020/2/24 12:25 @desc: 二叉查找树 该代码没有测试过 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class BinarySearchTree: def find(self, root: TreeNode, target: int) -> TreeN...
83a7fb1e92dbb0e4bd0ece2a09421ffd039d706e
tenqaz/crazy_arithmetic
/leetcode/剑指offer/剑指Offer38_字符串的排列.py
1,082
3.53125
4
""" @author: Jim @project: crazy_arithmetic @file: 剑指Offer38_字符串的排列.py @time: 2021/5/29 15:58 @desc: https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/ 输入一个字符串,打印出该字符串中字符的所有排列。 你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。 """ from typing import List class Solution: def permutation(self, s: str) -> List[st...
1ea75bb4b0bf7ade6b0671309b845012fdf4b2ac
tenqaz/crazy_arithmetic
/leetcode/235_二叉搜索树的最近公共祖先.py
1,290
3.53125
4
""" @author: Jim @project: crazy_arithmetic @file: 235_二叉搜索树的最近公共祖先.py @time: 2019/12/16 16:24 @desc: 二叉搜索树最近公共祖先 """ from tools.tree_node_tools import make_Treelist class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestC...
210269cea00424fd186d178dac028523d3342abd
tenqaz/crazy_arithmetic
/leetcode/35_搜索插入位置.py
738
3.796875
4
""" @author: Jim @project: crazy_arithmetic @file: 35_搜索插入位置.py @time: 2021/9/20 16:20 @desc: https://leetcode-cn.com/problems/search-insert-position/ """ from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left = 0 right = len(nums) - 1 ...
494c279afab0723007b26c3cae13a322fa448e53
James-Beckwith/DSA
/decon.py
1,633
3.625
4
import numpy as np # create a Ricker wavelet def ricker(f, time, u): y = (1.0 - 2.0*(np.pi**2)*(f**2)*((time - u)**2)) * np.exp(-(np.pi**2)*(f**2)*((time - u)**2)) y /= np.sum(y) return y # utility to find the next integer power of two of the input def nextpow2(input): return int(2 ** np.ceil(np.log(i...
ec4372bb7d799c8d135ef72bd554c43afefabe68
SerVB/hyperskill-projects
/numeral-system-converter/stage6.py
3,647
3.75
4
# -*- coding: utf-8 -*- FRACTION_SYMBOLS = 5 SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyz" ERROR = "error" def intToString(number, base): assert 1 <= base <= 36 if base == 1: return "1" * number if number < base: return SYMBOLS[number] else: return intToString(number // ...
8ade5a75e465ad970b3be72a3e8dbb1c3fa87480
SerVB/hyperskill-projects
/numeral-system-converter/stage5.py
2,579
3.578125
4
# -*- coding: utf-8 -*- FRACTION_SYMBOLS = 5 SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyz" def intToString(number, base): assert 1 <= base <= 36 if base == 1: return "1" * number if number < base: return SYMBOLS[number] else: return intToString(number // base, base) + SY...
3631daf833b89e80464c551cfc1a75751a6e8d3c
Blvisse/30DayPython
/day1_2.py
499
4.15625
4
#get user input userInput=input("Input integers separated by spaces: \n") userList=[] #convert input to list numbers=userInput.split(" ") for i in numbers: numberConvert=int(i) userList.append(numberConvert) print(len(userList)) #create a function that counts the number of elements in a list def listCoun...
bf30e42a52c78c72f9968c723b4bb25fb301b391
13709206394/pthon_study
/python_学习/正则表达式.py
1,269
3.8125
4
# ls = [1, 2, 3, 4, 4, 5, 6, 67] # # print(ls[::-1]) # # ls.reverse() # reverse()是Python列表内置的一个方法(字典、字符串、元组是没有的),该方法用于列表中比数据的反转 # # print(ls) # f = reversed(ls) # print(list(f)) # # ss = "qwer1234" # print(''.join(reversed(ss))) # def BinarySearch(arr, key): # min = 0 # max = len(arr) - 1 # if key in arr:...
06ca2e50e76f1a729982309a91a501bb7a4f0a90
13709206394/pthon_study
/python_学习/@property.py
1,177
3.5625
4
# class Student(object): # # def get_score(self): # return self._score # # def set_score(self,value): # if not isinstance(value,int): # raise ValueError('score must be an install!') # if value<0 or value>100: # raise ValueError('score must be between 0~100!') # ...
08ed5633e6c80e80ff9a630b0de9763553ef8ff9
xiaodongzi/pytohon_teach_material
/05/exec02.py
711
3.96875
4
# coding:utf-8 def add_all_1(*nums): if len(nums) == 0: return 0 result = 0 for num in nums: num = str(num) print num if num.isdigit(): result += int(num) print result return result # float 1.3 result error def add_all(*nums): # if le...
4e6091df235d9373cf383c8332d7b0665ccdb6c8
xiaodongzi/pytohon_teach_material
/03/exec07-capitalize.py
648
3.96875
4
# coding:utf-8 # 练习7:实现首字母大写的功能 其他字母小写 # function: capitalize # way 1st: a_str = 'fadfILILafLIk' a_list = list(a_str) for i in xrange(len(a_list)): if i == 0: a_list[i] = a_list[i].upper() else: a_list[i] = a_list[i].lower() cap_str = ''.join(a_list) print cap_str # way 2nd: a = 'fadfILILa...
5164fae31743f56be74f1b9e3d95e3f2c7994871
xiaodongzi/pytohon_teach_material
/02/exec10.py
576
3.640625
4
# --coding:utf-8-- # 求两个数组共同的值(去重) # 1. 求共同的值 # 2. 去重 # way1 # set arr1 = [1,2,3,4,2,12,3,14,3,2,12,3,14,3,21,2,2,3,4111,22,3333,4] arr2 = [2,1,3,2,43,234,454,452,234,14,21,14] arr1 = set(arr1) arr2 = set(arr2) arr_union = arr1 & arr2 arr_union = [i for i in arr_union] print arr_union # way2 arr1 = [1,2,3,4,2,12...
0191802356491e8855e942391b75d9dba00d122d
xiaodongzi/pytohon_teach_material
/01/exec07-02.py
552
4.0625
4
while True: str_input = raw_input('input a year: ') if str_input.isdigit() == False: print "please input a year." else: year = int(str_input) if year % 4 == 0: if year % 100 == 0 and year % 400 == 0: print "%d is a leap year." % year break ...