blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
c45867f3199dbb730ae4764ece11d7a4742af826
walton0193/cti110
/P3HW2_BasicMath_WaltonKenneth.py
1,198
4.1875
4
#This program is a calculator #It performs basic math operations #CTI - 110 #P3HW2 - BasicMath #Kenneth Walton #17 March 2020 def add(number1, number2): return number1 + number2 def subtract(number1, number2): return number1 - number2 def multiply(number1, number2): return number1 * number2 pr...
d9def864aa5e206010392eaf373070201b4abe2a
Anshrivastava9/python3
/hack5.py
198
3.734375
4
no_ofWords=int(input()) a=[] for _ in range(no_ofWords): b=input() a.insert(_,b) d=set(a) print(len(d)) for i in range(no_ofWords): b=a.count(a[i]) print(b,end=" ")
b0c99ad473d14d8488a904db839ca328c1cceb1d
Patricia-Henry/tip-calculator-in-python-
/tip_calculator_final.py
440
4.28125
4
print("Welcome to the Tip Calculator") bill_total = float(input("What was the bill total? $")) print(bill_total) tip = int(input("How much of a tip do you wish to leave? 10, 12, 15 \n")) people_eating = int(input("How many people are splitting the bill?")) percentage_tip = tip / 100 tip_amount = bill_total * ...
7f8b0ab0b62fb32cb767dfcead2733ea46d0246d
theovoss/leet
/leet/api/problems/two_sum.py
2,256
4.03125
4
class TwoSum: NOT_FOUND = "No solution found" LEET = "https://leetcode.com/problems/two-sum/" PLACE_THEO_SOLVED = "Criteo inteview August 27, 2020" def brute(self, numbers, target, multiple=False): """ Complexity of O(N logN) most likely. Depends on how python does item in list. ...
28fcd79f93af5e8516506dcb1402152ff26b9cfb
samdoty/smor-gas-bord
/morty.py
995
4.28125
4
# If you run this there is a bunch of intro stuff that will print a = 10 print(a + a) my_income = 100 tax_rate = 0.1 my_taxes = my_income * tax_rate print(my_taxes) print('hello \nworld') print('hello \tworld') print(len('hello')) print(len('I am')) mystring = "Hello World" print(mystring[2]) print(mystrin...
e285f5988aadaf7a25c5afa2b54f8484f801bbfd
emtes/learning-adventure
/fellow-notes/delanuez-enmanuel/012120_linked_lists/singly_linked_list.py
208
3.75
4
class Node(object): def __init__(self, value): self.value = value self.next_node = None a = Node(1) b = Node(2) c = Node(3) a.next_node = b print(a.value) b.next_node = c print(b.value)
f0f3d9f77b36e1f5bae8d1fe77fa6841e96ad277
ryan8806/codeabbey
/20/myscript
280
3.65625
4
#!/usr/bin/python import sys vowels = ['a', 'e', 'i', 'o', 'u', 'y'] count = sys.stdin.readline() for i in range(int(count)): line = sys.stdin.readline() vowel_count=0 for c in line: if c in vowels: vowel_count += 1 print vowel_count,
c561e808eda2293b11bfd5d3a76d4d1c24303ed6
ryan8806/codeabbey
/28/myscript
438
3.859375
4
#!/usr/bin/python import sys def assess(bmi): if bmi < 18.5: return "under" elif bmi < 25.0: return "normal" elif bmi < 30.0: return "over" else: return "obese" def calc_bmi(weight, height): return float(weight) / (float(height) ** 2) count = int(sys.stdin.readlin...
869d715d80af035b6c189ce57cdf0e6620dff497
idugcoal/Python-Projects
/fibonacci.py
183
3.859375
4
def fib(): a = 0 b = 1 limit = input("Enter the upper limit: ") c = a + b print a print b while c < limit: print "number is: " + str(c) a = b b = c c = a + b fib()
e93c12b31c52ef9f0fabfb0bb293ae9ddfea072d
ojbrahme/parseltonguep1
/02_daenerys.py
210
3.828125
4
output = raw_input("Who goes there?") if output == "DHTFHNUQARFMQMKGSPRLRSKBCMD": print("Welcome, Daernerys.") elif output == "Dany": print("Dany who?") else: print("Move along, now.")
d928744c32bde2b1aa046090a2fac343b2faf10d
SallyM/implemented_algorithms
/merge_sort.py
1,458
4.1875
4
def merge_sort(input_list): # splitting original list in half, then each part in half thru recursion # until left and right are each one-element lists if len(input_list) > 1: # print 'len(input_list)= {}'.format(len(input_list)) split = len(input_list)//2 left = input_list[: split] ...
08b55b1c778714d4a4c2ea0950f8084c062fcbdd
PatrickHuntington/patrick
/Prob11B.py
2,514
3.71875
4
# Problem 11: Drow Lasrever | 25 Points # Custom code to open and read the file line by line, get the next line in the file with next_line() with open('Prob11.in.txt','r') as f: lines = f.read().splitlines() marker = 0 def next_line(): global marker line = lines[marker] marker += 1 return line def ...
821a8f6d77daaf538ea8a0dcc9a72145557cc94d
Qiwen-Yu/MIT6.000_PythonPractice
/6.0001-1.py
1,863
3.875
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ #%% import random as rd print(rd.randint(1,100)) #%% num = input("G.S says something to me: ") print(num*100) #%% input_1 = float(input("enter a number: ")) input_2 = float(input("enter a number: ")) if input_1 == input_2: print("in...
6f74a09eb4b76315055d796874feeb993514e8f7
USFMumaAnalyticsTeam/Kattis
/Autori.py
590
4.1875
4
# This python code is meant to take a single string that is in a # long naming variation (ex. Apple-Boy-Cat) and change it # to a short variation (ex. ABC) import sys # Receive user input as string long_var = input() # Verify user input is no more than 100 characters if (long_var.count('') > 100): sys.e...
2004040b126c3488581205a26f819dc10c19a34a
JG-11/python
/Basics/Conditionals.py
429
4.03125
4
def classify(grade): if grade >= 0 and grade < 70: print('Calificación reprobatoria') elif grade >= 70 and grade < 90: print('Tienes una calificación aprobatoria') elif grade >= 90 and grade <= 100: print('¡Muy buena calificación!') else: print('Calificación no válida') ...
5025d9b09963b3919cd40dbaf79acb7f9e48918e
JulianArmour/codewars_python
/perimeter_of_squares_in_a_rectangle.py
303
3.59375
4
def fib_gen(): cur_fib, next_fib = 1, 1 while True: yield cur_fib cur_fib, next_fib = next_fib, cur_fib + next_fib def perimeter(n): length_sum = 0 fib_generator = fib_gen() for _ in range(n + 1): length_sum += next(fib_generator) return 4 * length_sum
3fbb50b92d66e3ecc7d468a075d81cfe3da24aa8
JulianArmour/codewars_python
/hamming_numbers.py
451
3.890625
4
from bisect import bisect def hamming(n): numbers = [1] for ham_no in range(n - 1): ham = numbers[ham_no] for h in [ham * 2, ham * 3, ham * 5]: insert_index = bisect(numbers, h) # only insert if h isn't already in `numbers` if numbers[insert_index - 1] != h:...
5b2a09f1663bde885b8ee39a641a518720e6631b
GhazaleZe/Biology-Meets-Programming
/ReverseComplement.py
459
3.96875
4
def Reverse(Pattern): new= Pattern[::-1] return new def Complement(Pattern): new = "" for c in Pattern: if c == 'A': new += 'T' elif c == 'T': new += 'A' elif c == 'G': new += 'C' elif c == 'C': new += 'G' ...
ced3bb8cd546b32fd8939c7f6e1aab7bf7a2faa7
Aartee/stock-market-analysis
/functions1.py
11,871
3.625
4
# coding: utf-8 # In[1]: import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime import pandas_datareader.data as web import io import requests # In[9]: # Import data #function to get stock data def yahoo_stocks(symbol, start, end): return web.DataReader(symbol, 'yahoo', start...
e9c7187e3f56e6bd0dd46ac18c0ff70b879eb0b0
sahilshah1/algorithm-impls
/course_schedule_ii.py
2,497
4.15625
4
# There are a total of n courses you have to take, labeled from 0 to n - 1. # # Some courses may have prerequisites, for example to take course 0 you have # to first take course 1, which is expressed as a pair: [0,1] # # Given the total number of courses and a list of prerequisite pairs, # return the ordering of course...
f8e9dd18faff91827300636d1cab2b439cddf1eb
sahilshah1/algorithm-impls
/longest_substring_nonrepeating.py
2,247
4.09375
4
# # https://leetcode.com/problems/longest-substring-without-repeating-characters/ # Given a string, find the length of the longest substring without repeating characters. # # Examples: # # Given "abcabcbb", the answer is "abc", which the length is 3. # # Given "bbbbb", the answer is "b", with the length of 1. # # Given...
0455e0bd8f25d96b03eb7d50606a0867a7d08ced
lefuernest/pdsnd_github
/bikeshare.py
9,221
4.46875
4
import time import pandas as pd CITY_DATA = { 'chicago': 'chicago.csv','new york': 'new_york_city.csv','washington': 'washington.csv' } MONTHS= {'january': 1,'february': 2,'march': 3,'april': 4,'may': 5,'june': 6, 'jan': 1,'feb': 2,'mar': 3,'apr': 4,'may': 5,'jun': 6} DAYS = {'monday': 0,'tuesday': 1,'wednes...
755b947c537fd5ce24675f2274198a095472eb50
srajeevteaching/programming-assignment-3-ejcatanzariti
/assignment 3.py
3,319
4.15625
4
# Emily Catanzariti # CS151, Dr. Rajeev # 10/28/2021 # Programming Assignment 3 # Program Inputs: choice of sport, rates in sports # Program Outputs: calculations for the scores of each sport # quarterback function def qb_score(a, c, py, tp, i): rating = float((100 * (5*(c/a) + 0.25*(py/a - 3) + 20*(tp/a) + 2.375 ...
9782ad74dc82f3704ca992817b886bd994e23529
kalani3010/Internship-Experience-UK-2021_GoogleWorkSample
/src/video_player.py
12,049
3.640625
4
"""A video player class.""" from .video_library import VideoLibrary import random class VideoPlayer: """A class used to represent a Video Player.""" def __init__(self): self._video_library = VideoLibrary() self._current_video = 'none' self._paused_video = 'none' self._playlis...
9ada4b5702bdaadf48c03c61563ac413917ff2e6
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Easy/019_Remove_Nth_Node_From_End_of_List.py
838
3.796875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ # Set...
7c87b42b0164ad5f6d05f0751ffb23c75b4a289a
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Easy/083_Remove_Duplicates_from_Sorted_List.py
674
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(None) ...
e8185cb3248cc7ab4cc51818d6098ab5a5c7a696
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Easy/397_Integer_Replacement.py
419
3.8125
4
class Solution(object): def integerReplacement(self, n): """ :type n: int :rtype: int """ ret = 0 while n != 1: if n & 1 == 0: # last digit is 0 n = n >> 1 elif n == 3 or ((n >> 1) & 1) == 0: n -= 1 ...
82256b1198580b50ddce99209f0ca4006a47c94e
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Medium/011_Container_With_Most_Water.py
923
3.828125
4
# # 11_Container_With_Most_Water # Given n non-negative integers a1, a2, ..., an, where each represents a point # at coordinate (i, ai). n vertical lines are drawn such that the two endpoints # of line i is at (i, ai) and (i, 0). Find two lines, which together with # x-axis forms a container, such that the container ...
34ca61f5de5c3f2d5a1efce3d86459ab59b82414
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Medium/016_3Sum_closest.py
1,533
3.640625
4
# 16. 3Sum Closest # Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. # For example, given array S = {-1 2 1 -4}, and target = 1. # The sum t...
b71228816a4dfca5e119d44817b95b5ea8479bff
gaoyanwang/Algorithms_and_Data_Structures
/Leetcode_Easy/100_Same_Tree.py
1,454
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Recursive Method class Solution(object): def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :r...
7ced9bf4f1657d9d88dec884f1ddc2b3158d361e
ziejaCode/CLI_Project1
/Click_Tutorial/basic_cli.py
531
3.5625
4
import click @click.command() @click.option('--firstname','-f',help="First name", type=str, default="Friend") @click.option('--num','-n',help="number", type=int, default=1) @click.option('--salary','-s',nargs=2) @click.option('--city','-c', help="Your cities", multiple=True) @click.version_option('0.01',prog_name='bas...
cd3f6260abd40a388484dec02bf51e01fa90766f
junior333/lista-python
/ex14.py
265
4.0625
4
#Receba 2ângulos de um triângulo. Calcule e mostre o valor do 3o ângulo. a= int(input('digite o primeiro angulo: ')) b=int(input('digite o segundo angulo: ')) if a+b<180: print(f'o valor o terceiro angulo é {180-a-b}') else: print('angulos inválidos')
4785af943e36bdb47b78e42a0d8f60511a6b699a
junior333/lista-python
/ex13.py
240
3.53125
4
#Receba a quantidade de alimento em quilos. Calcule e mostre quantos dias #durará esse alimento sabendo que a pessoa consome 50g ao dia. qtd=int(input('digite a quantidade da alimento(kg): ')) print(f'o alimento durará {qtd/0.050} dias')
afe0475da5c0d77e1fc909805cf5412cbdc58268
junior333/lista-python
/ExGuanabara/ex011.py
239
3.703125
4
larg=float(input('digite a largura da parede(mts): ')) alt=float(input('digite a altura da parede(mts): ')) #cada litro de tinta cobre 2m² print(f'numa área de {larg*alt:.2f}² o total de tinta necessária é {larg*alt/2:.2f} litros')
7191fab2cde6ff64bb9b428c09ea1635980a49f7
junior333/lista-python
/ExGuanabara/ex003.py
110
3.828125
4
a=int(input('digite um numero ')) b=int(input('digite outro numero ')) print(f'a soma de {a} + {b} é {a+b}')
282a8d6be45541c4e7285fae80804d83fa678fcb
Lonsomem/Python_coding
/webhacking_old_6.py
935
3.5
4
import base64 text = "admin".encode('utf-8') text2 = "nimda".encode('utf-8') def stringTobase64(s): return base64.b64encode(s) def base64Tostring(s): return base64.b64decode(s).decode('utf-8') for n in range(20): text = stringTobase64(text) text2 = stringTobase64(text2) text = text...
de13303d6d69df8b2de859015ebd115a4c07c3ee
uvsq22005102/snake
/snake.py
1,536
3.515625
4
import tkinter as tk import random as rd from tkinter.constants import ALL WIDTH = 600 HEIGHT = 600 mouvement = 10 vitesse = 60 snake_positions = [[300, 300], [290, 300], [280, 300]] direction = "Right" score = 0 coord_serpent = [] demarrage = 1 def mouvement_snake(): """Pour faire bouger le serpent dans différe...
04cdb82fa55228c3673123dc12013b56109c218b
prateeknima/Data-Extraction-Using-YouTube-API-Python-
/youtube_api.py
3,539
3.53125
4
#importing libraries import csv import os from googleapiclient.discovery import build import pandas as pd # API Key generated from the Youtube API console api_key = "AIzaSyB6oEFCmMe4dJpIyOliDIpqqBiZmhEDurg" youtube = build('youtube','v3',developerKey=api_key) # Setting up the directory location os.chdir('...
ec76b2b35b9fd3a03c730bb98d18ac839a2c5b48
forin-xyz/forin-xyz.github.io
/src/sorts/insertsort.py
591
4.09375
4
#!/usr/bin/env python3 def insertsort(lst): length = len(lst) for i in range(1, length): j = i tmp = lst[i] while j and tmp < lst[j-1]: lst[j] = lst[j-1] j -= 1 if j<i: lst[j] = tmp return lst def test_insertsort(): # lst = [ 9, 4, 3, 10, 7, 13,...
99411c474c0d7deed3f4a1fd990a013bd96432dd
ifarshgar/Encryption-Techniques
/DES/app.py
1,281
4.09375
4
import DES if __name__ == "__main__": print('Data Encryption Standard (DES)') menu = '\n1.Encrypt' menu += '\n' + '2.Decrypt' menu += '\n' + '0.Exit' menu += '\n' + '> ' ch = -1 while(ch != 0): print(menu, end='') try: ch = int(input()) exc...
919312477553dac531f9313b1666b9af26cb1abe
evgranato/compensation-calculator
/margin_compensation.py
1,698
3.890625
4
# root = tk.Tk() # frame = tk.Frame(root) # frame.pack() # def calculator(cost, margin): # answer = round(int(cost) / (1 - int(margin)/100), 2) # compensation = round((answer-int(cost)) * .20, 2) # return f"The quoted price should be ${answer} and your compensation will be ${compensation}" # cost = input(...
81f3c89de7aebd1d982e710bdf87ad9e62334f5e
heyese/python_jumpstart
/birthday.py
1,973
4.34375
4
import datetime def get_birth_date(): print('Please tell me when you were born:') year = int(input('Year [YYYY]: ')) month = int(input('Month [mm]: ')) day = int(input('Day [dd]: ')) print('\n') bdate = datetime.date(year, month, day) return bdate def is_a_leap_year(year): leap_year ...
6176e91f3e9fc7e7238034d992ffa0ae08453b36
amol125/Python_Assignment_Programs
/pro8.py
315
4.03125
4
#Q 8] program to Eliminate consecutive elements from list l1=[1,1,1,2,3,4,4,5,6] print ('list before :',l1) i=0 while (i<len(l1)-1): if(l1[i]==l1[i+1]): del l1[i] else : i=i+1 print ('list after:',l1) ''' output list before : [1, 1, 1, 2, 3, 4, 4, 5, 6] list after: [1, 2, 3, 4, 5, 6] '''
52d0586ed3cdbe18346e70d45883b74ec929e6c7
pavankalyannv/Python3-Problems
/HackerRank.py
1,718
4.34375
4
Problme: @HackerRank ========== Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Note: If there are multiple students with the same grade, order their names alphabetically and print each name...
76cedca1f9b08976aa3240f9f1a6ab0de59ec61b
lixuanhong/LeetCode
/350. Intersection of Two Arrays II.py
1,521
3.9375
4
""" Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in an...
6c5d294880f06bc8f011308ea179d17f69e45a6e
lixuanhong/LeetCode
/MaximumSwap.py
1,927
4.0625
4
""" Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get. Example 1: Input: 2736 Output: 7236 Explanation: Swap the number 2 and the number 7. Example 2: Input: 9973 Output: 9973 Explanation: No swap. Note: The given numbe...
a38ed28ea100ab0963aa07cd0703f10e8a4b1b95
lixuanhong/LeetCode
/387. First Unique Character in a String.py
695
3.75
4
""" Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. Examples: s = "leetcode" return 0. s = "loveleetcode", return 2. """ class Solution(object): def firstUniqueChar(self, s): """ :type s: str :rtype: int """ ...
64d8151fff233a9cbe953b191d2a3b77428ef896
lixuanhong/LeetCode
/DecodeWays.py
2,037
3.96875
4
""" A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. Example 1: Input: "12" Output: 2 Explanation: It could be decoded as "AB" (1 2) or "L" (...
1626b50c39f1fd5be5579dc61f1f3adc1294cd0b
lixuanhong/LeetCode
/ValidPerfectSquare.py
664
4
4
""" Given a positive integer num, write a function which returns True if num is a perfect square else False. Note: Do not use any built-in library function such as sqrt. Example 1: Input: 16 Returns: True Example 2: Input: 14 Returns: False """ class Solution(object): def isPerfectSquare(self, num): if...
944f2a67f38f40370b64c9e97914e355009b9c6b
lixuanhong/LeetCode
/LongestSubstring.py
979
4.15625
4
""" Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substri...
7e5f4348f5c9ec0fc85c08b070c70f6f5eacfa4c
lixuanhong/LeetCode
/658. Find K Closest Elements.py
1,177
3.6875
4
""" Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred. Example 1: Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4] Example 2: Input: [1,2,3,4,5], k=4, x=-1 Output: [1...
aa51f8cc9a11e4b4242d1ba15bd82113bd3fe4b9
lixuanhong/LeetCode
/621. Task Scheduler.py
1,699
3.90625
4
""" Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. However, there is a non-negat...
31741df654a18dc674a4b1dd61bd20eb2a116014
lixuanhong/LeetCode
/twosum.py
1,362
3.5
4
# Brutal Force # def twoSum(nums, target): # try: # for i in nums: # for j in nums: # value = target - i # if (j == value and j != i): # return [nums.index(i), nums.index(j)] # except: # return None # # nums = [2,8,7,11,15] # print(...
8019b9f5665c1edce2e15c965b85f2ba846ee99d
lixuanhong/LeetCode
/BuildBinaryTreePreorderInorderTraversal.py
1,213
3.9375
4
""" Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,15,7,20] root->left->right inorder = [15,9,7,3,20] left->root->right Return the following binary tree: 3 / \ 9 20 / \ 15 7 "...
118cd38a9e7de23b1564b78b7fbbed100145a519
lixuanhong/LeetCode
/304. Range Sum Query 2D - Immutable.py
2,085
4
4
""" Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2). Range Sum Query 2D The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8. Example...
3c9706a562aff0755d49f4e005230cd7b7ef48ae
lixuanhong/LeetCode
/ReverseLinkedList.py
509
3.875
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL """ class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseList(self, head): if not head: return None pre = N...
c4016f2848df08d47eea0a7d14d1879d9d272e6c
lixuanhong/LeetCode
/SmallestSubtreewithAllDeepestNodes.py
1,798
4.0625
4
""" Given a binary tree rooted at root, the depth of each node is the shortest distance to the root. A node is deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is that node, plus the set of all descendants of that node. Return the node with the largest depth such ...
bdfd7fb7d643f47426b674a28a09c3b5b394b789
lixuanhong/LeetCode
/3SumClosest.py
1,094
3.921875
4
"""Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.""" def threeSumCloest(nums, target): nums.sort() diff_min = 1000 for i in ran...
a7eb6cca9dd2df586842ebf3e2be1b65d1703adb
lixuanhong/LeetCode
/ConvertBinarySearchTreeToSortedDoublyLinkedList.py
758
3.59375
4
class Node(object): def __init__(self, x, left, right): self.val = x self.left = left self.right = right class Solution(object): def treeToDoublyList(self, root): if not root: return None head, tail = self.helper(root) return head def helper(self...
6a9652efd51c9215b6a00cc5b1a626c971d2313a
lixuanhong/LeetCode
/IntegerToEnglishWords.py
1,974
4.125
4
""" Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1. Example 1: Input: 123 Output: "One Hundred Twenty Three" Example 2: Input: 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: 1234567 Output: "One Million Two Hundred Th...
c73dc06bbea712cda5277a0980daa75c091c4d7d
lixuanhong/LeetCode
/RangeSumQueryMutable.py
1,765
3.921875
4
""" Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8 Note: The array is only modifiable by t...
4159bf75764f6587c62c7a0b763a8ad50fb45dbd
lixuanhong/LeetCode
/694. Number of Distinct Islands.py
2,677
3.8125
4
""" Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Count the number of distinct islands. An island is considered to be the same as another if and only ...
751955d10147cad64032e4a9e0965734e5f96f39
Ninad-Chaudhari/Emotional.ele
/responses.py
6,341
4.03125
4
def joy(): print("I'm glad to know that :) Looks like you're content.") print("Is there any thing else you would like to share?") response = input() if(response == "yes"): print("What would you like to share?") #back to tree else: print("It was really nice talking to you! Fee...
f4e0464583a7924dc0d575d727d01281e1bc1662
tamjd1/speech-classification-full-text-search
/voice_enabled_search.py
2,421
3.640625
4
from pydub import AudioSegment import glob import speech_classification as sc import full_text_search as fts import os import sys f = open(os.devnull, 'w') sys.stderr = f def voice_to_text_search(audio_search_term, text_search_term): """ This function takes an audio file, runs it through the speech classifica...
5405d7d84d8f316eae6431a5f1b55797b806db07
chiragpoddar12/Udacity_Full_Stack
/Project 1/turtleSquares.py
543
3.84375
4
import turtle def drawSquare(someTurtle): someTurtle.right(10) for i in range(1,5): someTurtle.forward(100) someTurtle.right(90) def drawArt(): window = turtle.Screen() window.bgcolor("black") brad = turtle.Turtle() brad.color("cyan") brad.shape("turtle") brad.speed(5)...
42e8f66d07a82c41af0d5640ad091a91d18b70a2
JiriVit/scripts-and-settings
/python/create_dual_wallpaper.py
2,971
3.515625
4
"""Creates dual monitor wallpaper by combining two single images. This script requires PIL module. Nowadays it is distributed as part of Pillow package. You install it just by entering: python -m pip install Pillow Warning: At the time of creating this script, Pillow 4.1.0 didn't work well with Python 3.6. So if yo...
1e7bb1649a181bed834e8e99cf82d4937ae3111f
mushBrainDave/Steganography
/encoder/encoder.py
1,735
3.515625
4
#!/usr/bin/env python3 from io import BytesIO from PIL import Image def CreateMessage(message): """ Takes a string and returns the ascii binary representation. :param message: string given from user :return: String; string """ temp = bin(int.from_bytes(message.encode(), 'big'))[2:] # removes ...
5d2c7daa82c4809a4ae53a052cd6488ccb487636
tkazusa/python_decorator_practice
/practice.py
1,447
4.03125
4
def print_result(func): """decorator for print result Args: func: function return: new_func:function decorated with printing calclation result """ def new_func(*args, **kwargs): result = func(*args, **kwargs) print(result) return result return new_func d...
0c98517de9e20d11e22f0b52b32342bc66fedf94
jsdelivrbot/demos
/python/argparse/3square.py
337
4
4
import argparse parser = argparse.ArgumentParser() # be default the parameters are treated as string. #parser.add_argument("square", help = "display a square of a given number") # Let us read it as int parser.add_argument("square", help = "display a square of a given number", type=int) args = parser.parse_args() print...
60a6e893f141676a792a0f55646556da6525c638
robertreichner/lpthw
/ex/ex45-game.py
2,528
3.765625
4
from sys import exit from random import randint class Scene(object): def enter(self): print "This scene is not yet configured. Subclass it and implement enter()." exit(1) class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene...
ac9e1e4d1bc018ced63237529a55c6f1578c6260
quockhanh29/Practice-Python-programming
/chapter05/sample05_4_2.py
137
3.796875
4
def adder(a): def inner(x): return x + a return inner add3 = adder(3) add5 = adder(5) print(add3(10)) print(add5(10))
65c875c567a6206cd442845643d6a9b3ba03bddf
quockhanh29/Practice-Python-programming
/chapter01/sample01_3_1.py
367
3.53125
4
#coding: utf-8 #乱数機能の使用 import random #0~2の乱数を発生させる #発生した乱数を変数fortunelに代入する fortune = random.randint(0,2) #変数の値(発生した乱数)に応じて大吉、中吉、小吉を表示 if fortune == 0: print('大吉') elif fortune == 1: print('中吉') elif fortune == 2: print('小吉')
3a60b53f4966c3913151f66c05be2769339f78b0
quockhanh29/Practice-Python-programming
/chapter07/sample07_2_1.py
404
3.84375
4
class Person: def __init__(self, name): self.__name = name def greet(self): print('Hello, my name is ' + self.__name) @property def name(self): print('name getter') return self.__name @name.setter def name(self, name): print('name setter') if na...
0d0c94764f7997b60c41dd32632e817113195625
Hydroenvironment/Evolution-of-Groundwater-Levels
/Groundwater_level_interpolation_maps.py
9,351
3.640625
4
import pandas as pd import os import matplotlib.pyplot as plt import numpy as np import statistics # set the working directory to the map with the data os.chdir('C:\\Users\\Julio\\Desktop\\IUPWARE\\ENVIRONMENTAL PROGRAMMING\\Project Groundwater\\Data') Dir=os.getcwd() #method returning the current working directory ...
e541df84265622bc5ac3ae4f72b88b117c2db827
SameerVanjari/cybrilla-test-
/Problem-2.py
688
3.84375
4
''' Problem 2 Write an Algorithm to find all unique triplets in the arrays which gives the sum of zero. Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0. Solution must not contain duplicate triplets. Sample: Input: [ -1, 0, 1, 2, -1, 4] Output: -1, 0, 1 -1, 2, -1 ''' def find...
94cf5b2d62a4800cbdff39a9c84e69cbb9e3109f
mriolfo/python_repo
/code/maxNumber.py
371
3.984375
4
#testing input, max and print format class MaxNumber(): def def_max_number(first_number, second_number): first_number = int(input("First number: ")) second_number = int(input("Second number: ")) return max(first_number, second_number) #maxNumber = max(firstNumber, secondNumber) ...
1befbc59176e9f2e35ba8b4d3bb3f8a0f995ffd5
Tanmay2262/OpenCV
/Color_Spaces.py
1,101
3.734375
4
# Color Spaces are basically a space of colors # OR # Color Spaces is system representing an array of colors # Eg. RBG, GrayScale, HSV, etc. # OpenCV displays only BGR image while matplotlib.pyplot displays a RBG image import cv2 as cv import matplotlib.pyplot as plt img = cv.imread('opencv img.jpg') c...
62d027d176a078a688ef69a0dfc35f7462aeffbc
DmitryPodpryatov/maze-solver
/algorithms/Solver.py
3,555
3.890625
4
from abc import ABC, abstractmethod from random import shuffle import cv2 import numpy as np from algorithms.Errors import InvalidStartError, InvalidFinishError, InvalidImageError class Solver(ABC): """ Abstract class for maze-solving algorithms 255 in the image is path and 0 is a wall """ def...
6e22ffee0fd54f5d44cd5aae6b61a449b90498ba
TheRealMarcusChiu/PythonMasterExample
/src/third-party/01_numpy/ndarray/3_array_operations.py
222
3.53125
4
import numpy as np # ordinary operations a = np.array([0, 0, 0]) b = np.array([1, 2, 3]) c = a + b print(c) # broadcasting a = np.array([[0, 0, 0], [10, 10, 10], [20, 20, 20]]) b = np.array([1, 2, 3]) c = a + b print(c)
e16cbf15647ec505980e935317db5a7c806628de
TheRealMarcusChiu/PythonMasterExample
/src/third-party/q-learning/main.py
4,118
3.8125
4
# https://towardsdatascience.com/q-learning-54b841f3f9e4 import pandas as pd import random class Game: rewards = None positionCol = None positionRow = None def __init__(self, start_col=1, start_row=1): self.distance = pd.DataFrame( {1: [8, 7, 6, 5, 4], 2: [7, 6, 5, 4, 3], 3: [6, 5...
431b55898f50b9071791e86cf07ff152658762d8
TheRealMarcusChiu/PythonMasterExample
/src/third-party/data-science/main.py
1,048
3.9375
4
import numpy as np import matplotlib.pyplot as plt np.random.seed(42) # construct population population = np.random.randint(0, 500, size=100) # # sample population of size 30 # sample = np.random.choice(population, size=30) # print('sample mean: ', sample.mean()) # print('sample std: ', sample.std()) # # # estimated...
3c07886258a33b1b5ddec3f65483c7f024bd81f0
bo-boka/python-tools
/list_comprehension.py
566
3.8125
4
li = [x for x in range(1,10)] print li # prints 1 - 9 in list form st_li = [ch for ch in 'string'] print st_li # prints string in list form series = [s**2 for s in range(1, 6)] print series # prints the square of each num in range even = [e for e in range(1, 21) if e%2==0] print even # prints evens row1 = [1, 2...
73cc42b9f05f5b83b6e81cee8f3aa2ad1ac786b8
bo-boka/python-tools
/NumberTools/iterate.py
1,265
4.1875
4
def print_multiples(n, high): i = 1 while i <= high: print n*i, '\t', i += 1 print def print_mult_table(high): i = 1 while i <= high: print_multiples(i, high) i += 1 def print_digits(n): """ >>> print_digits(13789) 9 8 7 3 1 >>> print_digits(39...
f01620eef664bcc7682ba734ea2d510110408bd2
pakpoomton/pythonMISC
/fallingObject.py
665
3.8125
4
from numpy import * import matplotlib.pyplot as plt def fallingObject(initialVelocity): t_max = 10 #total simulation time t_step = 0.1 #discrete step size in simulation g = -9.81 #gravity n_steps = int(t_max/t_step) t = zeros(n_steps) v = zeros(n_steps) #set initial condition t[0] = 0 ...
e6e6a59e87fd4e794b5e079fdc1f21e653f6458d
dobrynin-andrey/rkm4.diss
/rkm4.py
1,139
3.65625
4
import math # Метод Рунге-Кутты 4-го порядка # Пример dy/dx = sin(x)+cos(y), y(0)=5; # Параметры h = 0.1 # Размер шага xfinal = 1 # Решать с x = [0, xfinal] # Начальные значения x = 0 y = 5 Xframe = [x] Yframe = [y] # Определим функцию ОДУ def functionODU (x, y): f = math.sin(x)+math.cos(y) retu...
16757d5beb793f38c8c4c2a7e3806e0f9c05bdb0
nelizalde/python-challenge
/PyPoll Homework.py
2,058
3.890625
4
#!/usr/bin/env python # coding: utf-8 # In[118]: #import budget data import os import csv # In[119]: #create a path csvpath=os.path.join("..","Resources","election_data.csv") # In[120]: #Create list to store data number_votes=0 candidate_list=[] vote_count={} vote_percent=[] #to open the file with open(cs...
897ef7b71ea83ba9402d59bb016d2f62ff801fe0
Koffe-rgb/learning-python
/p1/week3/3.2-1.py
433
3.75
4
def update_dictionary(d, k, v): if k in d: d[k].append(v) else: if k * 2 in d: d[k*2].append(v) else: d[k*2] = [v] d = {} print(update_dictionary(d, 1, -1)) # None print(d) # {2: [-1]} update_dictionary(d, 2, -2) print(d) ...
85a28956a325201c85ac3facdfd909e619d647f1
KaranAulakh/Retro_Snake
/game.py
17,899
3.578125
4
''' **** GAME **** Handles all gameplay, runs with a set of helper functions and a seperate method to control the gameplay and logic for each seperate game mode ''' import pygame import random import time import snake import sys # CONST SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 ...
4b08b26de372f0681f7a4dde76451586e539bd0e
xiaozhu-sorce/Python
/6.4-6.6.py
680
3.75
4
user_0 = { 'user_name' : 'efermi', 'first' : 'enrico', 'last' : 'fermi' } #items()返回一个键值对列表 for key,value in user_0.items(): print("\nKey:" + key) print("Value:" + value) favorite_languages = { 'jen':'python', 'sarah':'c', 'edward':'ruby', 'phil':'python', } #keys()只遍历 键 或者默认遍历键 for name in favorite_langu...
a76e9bae90f5ff59c177ad208b6fcc805c5dad01
xiaozhu-sorce/Python
/5.8-5.11.py
1,406
4.03125
4
request_toppings = ['mushroons','green peppers','extra cheese'] for request_topping in request_toppings: if request_topping == 'green peppers': print("Sorry,we are out of green peppers right now") else: print("Adding " + request_topping+".") print("\nFinished making your pizza!") request_toppings = [] if reques...
a224ad07b4de0dcdf836298ef62d256e0c4b7dcc
xiaozhu-sorce/Python
/4.3-4.10.py
309
3.84375
4
for num in range(1,21): print(num) nums = list(range(1,1000001)) for num in nums: print(num) print(min(nums)) print(max(nums)) print(sum(nums)) jishu = list(range(1,21,2)) for ji in jishu: print(ji) div = [va*3 for va in range(1,11)] print (div) thr = list(range(1,11)) for th in thr: print(th**3)
fcff00819784447dff871c61fdbf7f5e81894a4b
jfriend08/Stock_Analysis_EngineII
/category_correlation/src/categoryCorrelation_step1_mapper.py
573
3.5625
4
#!/usr/bin/env python import sys import re for line in sys.stdin: line = line.strip() # remove leading and trailing whitespace fields=line.split('\t') # split by tab # pop out info, and only keep value in fields industry = fields.pop(0); symbol = fields.pop(0); weight = fields.pop(0); ...
8ade1f0d518d683a0fa0678d5bca1e103d5baf23
rismakov/Lexophilia
/src/Filtering.py
2,273
3.796875
4
import numpy as np import pandas as pd from datetime import datetime from Countries import count_country_mentions def filter_data(df, filter_date=False, min_year=None): df['date_posted'] = df.date_posted.apply(lambda date: datetime.fromtimestamp(date/1000)) df['y...
695891caebaeb9cefd45eae3fe0fb6aca03ac96d
OceansBlue2017/Head-First-Python
/001_theBasics.py
3,242
3.5
4
# First Line of Code to test ''' colors = ['Blue', 'Red', 'Brown', 'Hazel'] i = 0 while i < len(colors): print("When I was %d, my favorite color was %s" % (i, colors[i])) i = i+1 ''' # ************** Head First Python Book Page 4 Code ************** ''' from datetime import datetime odds = [1, 3, 5,...
1772283340ca8020ca317334ca28a23bf1c7797f
ronitshar/oop_02
/ex03/has_cycle.py
402
3.765625
4
from helper import Node def has_cycle(list_head): current = list_head while current.next != None: if current.next == list_head: return True break else: current = current.next return False firstHead = Node(3) secondNode = Node(4) thirdNode = Node(5) firstHead.next = secondNode s...
622b1b8207531caade6a886bf0e2e4b0bdeb6048
sanga3055/python_fun
/youtube_downloader_commandline.py
3,191
3.6875
4
# Youtube video downloader by Zothan Sanga # For any question reachout to sanga3055@gmail.com # First rev: Sunday 17 Oct 2021 # For complete pytube library check https://buildmedia.readthedocs.org/media/pdf/python-pytube/latest/python-pytube.pdf # Example video: https://www.youtube.com/watch?v=2XN-u0fsSLw # User nee...
e12d833e1a021df40cff396b07a5a681a8fffa66
gauravdhmj/Project
/Shelve.py
5,176
4.28125
4
# pickle has several drawbacks related to storing the data into the file # shelves are used to overcome that drawback # shelves can be considered as a persistent dictionary which means it can have all dictionary operations performed on it # shelve file is already opened in read and write format together # import ...
df7978f0c6a2f0959ecf5ead00a2d05f18325b10
gauravdhmj/Project
/if programfile.py
2,761
4.1875
4
name = input("please enter your name:") age = input("How old are you, {0}".format(name)) age = int(input("how old are you, {0}".format(name))) print(age) # USE OF IF SYNTAX if age >= 18: print("you are old enough to vote") print("please put an x in the ballot box") else: print("please come back aft...
5f2c26e678374df769b4f5237affe50ac61f99d4
gnpardini/PersonData
/Main.py
660
3.578125
4
from Person import Person person = Person("dyt") #funciones def askName(): name = raw_input('Ingrese su nombre por favor: ') person.addName(name) resultName = person.addName(name) while resultName == False: name = raw_input('Error. Ingrese nuevamente su nombre por favor') resultName =...
81e668db335aae6f6ee18001c718542509912a6e
vperrin59/mit-6.0001-intro-cs-python
/ps4/ps4a.py
1,983
4.03125
4
# Problem Set 4A # Name: <your name here> # Collaborators: # Time Spent: x:xx def conc_string(a, b, pos): ''' b is single char, pos is b position in the new string ''' if pos == len(a): return a + b else: res = [] for i, c in enumerate(a): if i == p...