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
eb8e8a1407cacd352d29f3796cdad6d2d7cf4e90
Adnan-Aziz/PythonPractice
/MITPerson.py
769
3.6875
4
from Person import Person class MITPerson(Person): nextIdNum = 200 #identification number def __init__(self,name): Person.__init__(self,name) self.IdNum = MITPerson.nextIdNum MITPerson.nextIdNum +=1 def getIdNum(self): return self.IdNum def __lt__(self,other):...
3cb30407ab66aeeda4477966de665aaecb1f41dd
Sreejith8a/FaceDetection
/FaceDetection/videtect.py
1,086
3.53125
4
import cv2 from random import randrange # Loading some pre-trained frontal-face data from opencv (haar cascade algorithm) trained_face_data = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Choose an video to detect faces in webcam = cv2.VideoCapture(0) # 0 refers default webcamera and videofiles...
e35933e8969ca511a1d533a23875f42bf2d7a671
yogeshwaran01/Python-Scripts
/Scripts/spin_words.py
825
4.03125
4
""" Function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed. Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present. """ def spin_words(sentence: str) -> str: ""...
a8b090a4b727201c14d59bcaf573c072d0cc94a6
yogeshwaran01/Python-Scripts
/Scripts/periodic-table.py
644
3.78125
4
import requests url = "https://elements-table-api.herokuapp.com/" def get_data_by_name(name: str) -> dict: """ Function get data from api by name of elements """ return requests.get(url + "name/" + name).json() def get_data_by_number(num: str) -> dict: """ Function get data from api by ato...
aff950e6eb663d1dc7defdf7a8e1b19c480da3fd
yogeshwaran01/Python-Scripts
/Scripts/anagram.py
540
4.1875
4
""" What is an anagram? Two words are anagrams of each other if they both contain the same letters. For example: 'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca' == false """ def is_anagram(a: str, b: str) -> bool: """ >>> is_anagram("xyxyc", "xyc") False ...
be400c71c8bec4678819b669f6a0fa8a3ac8bf62
CherilusSamBracley/Random-Password-Generator-
/RandomPasswordGenerator.py
1,228
3.859375
4
#Cherilus Sam Bracley #cherilussambracley@gmail.com #Random Password Generator import random import time USER_CHARACTERS = input("Insert your character(s) in the order to have the password...") #INTERVAL= PROCESS_THREE[0:8] x= input("Insert the first step for password len (only one number [RECOMANDED (0) THE FIR...
4844cb4f637df273315139cf6340ad1a0d66caa8
JavierPerezGithub/Python
/src/EstructurasControl/For.py
583
3.671875
4
''' Created on 5 nov. 2017 @author: Javier ''' print "Comienzo" for i in [3, 4, 5]: print "Hola. Ahora i vale", i print "Final" print "Comienzo" for i in ["coche", "casa", "moto"]: print "Ahora i es: ", i print "Final" for i in range(1, 11): #Para que llegue al numero deseado hay que sumarle 1...
4264ae0477c38f63d43dc1521f4d48f29dfd7f31
JonkeDAB/Python
/Lek 2.py
302
3.828125
4
# variabler för att komma ihåg namn och ålder # Läsa in namn name = input("Skriv ditt namn här: ") # Läsa in ålder age = int(input("Skriv din ålder: ")) # skriva ut om du är 18 eller inte if age > 17: print("Hej", name , "du är", age ,"år") else: print ("du har inte fyllt 18 än")
879673b00be6a8eff5685581a77d19aa63ac4750
mmsf84/msantosf_notacion_bigo
/bigo.py
1,066
3.765625
4
class Fibonacci: __fibocache = [] def fibonaccirecur(self, numero): if numero < 0: return " No se admiten valores menores a cero" elif numero < 2: return numero return(self.fibonaccirecur(numero-1) + self.fibonaccirecur(numero-2)) def fibonacci...
77398f244189e60188a12b46cb3140b9e5e3632c
rmhowe/advent-of-code
/day5/part_one.py
1,362
3.59375
4
# # Learning about python regexes. Learnt about the if __name__ == "__main__" # pattern which makes sense from a module perspective. Using double quotes # now, feels more natural in python for some reason. I'm using underscores # in file names now as well so that they can be imported as modules (dashes # were causing s...
7fee3f42c3e53fb6e481a951c144466cf5b58208
rmhowe/advent-of-code
/day12/part_one_two.py
1,783
3.6875
4
# # Read a lot about EAFP and duck typing in python here for use when determining # if I'm reading an array or an object in the JSON file. Seems like convention # is to use duck typing with error handling, but only when you expect the # condition to succeed. In this case we'll run into the 'exception' case a lot, # so ...
13aba6575bbaa84bd29c32786c96e51696806b84
rajakumarks/acsl-python
/StringASF.py
4,465
4
4
''' PROBLEM: Given 2 strings, separated by a space, calculate the ACSL Sameness Factor (ASF). Repeat the following 3 steps in order until no other deleting aligns like characters: ● Align the strings from left to right. ● Delete the like characters in the like locations from left to right. ● Proceeding fr...
e30e21ba28c0f5b59ac64293d6e95e831b988bcd
ChittojiMuraliSreeKrishna/TkinterPython
/ContactBook.py
3,015
3.734375
4
from tkinter import * import tkinter as tk from tkinter import messagebox import sqlite3 root = tk.Tk() root.title('contact book') root.configure(bg='black') conn = sqlite3.connect('contactbook.db') c = conn.cursor() c.execute("""CREATE TABLE IF NOT EXISTS contact( Name text, Mobile int, Email text, ...
e57b956d38680390e54daf714a1180c327da91a0
ChittojiMuraliSreeKrishna/TkinterPython
/login&signup/signup.py
4,339
3.9375
4
import tkinter as tk from tkinter import * import sqlite3 from tkinter import messagebox from PIL import ImageTk, Image root = tk.Tk() root.title('signup database') root.configure(bg='black') conn = sqlite3.connect('signup.db') c = conn.cursor() # creating the table if it does not exists c.execute("""CREATE TABLE IF ...
21a90ad802ba70c162ecc0bf498244a47f0ab1d7
jonXue92/AlgoDaStGit
/GrokkingAlgorithms/sum.py
164
3.609375
4
def sum1(arr): result=0 if len(arr)==0: result=0 else: result=arr.pop(0)+sum1(arr) return result print(sum1([])) print(sum1([6])) print(sum1([1,2,3,4,5]))
705c13897fd795b6b5b2cd0ab9c41116e460cd69
nghianja/Password-Hacker
/.idea/VirtualEnvironment/lib/python3.8/site-packages/hstest/dynamic/stdout.py
1,133
3.546875
4
import io from typing import List class OutputMock: """ original stream is used to actually see the test in the console and nothing else cloned stream is used to collect all output from the test and redirect to check function partial stream is used to collect output between input calls i...
c321c8fd8b88829d473b5d6e194e7a433fa59818
Popa-Sebastian/Python3-Specialisation
/C$/scrach.py
326
3.859375
4
class City: def __init__(self, n, p, s): self.name = n self.population = p self.state = s def __str__(self): return '{}, {} (pop: {})'.format(self.name, self.population, self.state) city_tuples = zip(cityNames, populations, states) cities = [City(n, p, s) for (n, p, s) in city_t...
1fd96f13db708da1487bb13f0ef6ebf00d585592
gracedamico18/python
/DamicoFinalProject2.py
10,150
3.875
4
#Project 2 - Grace D'Amico #Activity 1 import random def main(): name, current_money = restore() if name == ' ': name = input("Name? ") current_money = int(1000) print(name, " has $", current_money, "\n",sep="") bet = 25 user_bet = input_bet(bet, current_money, name) ...
3632ca41b4220ba6706bb0be7cf8f7ea2cb02767
g-quest/bulls_and_cows
/game.py
1,256
3.859375
4
import bulls_and_cows as bc def main(): print('Welcome to Bulls and Cows!') again = 'yes' while (again == 'yes'): play_game() again = input('Would you like to play again? (yes/no)') print('Bye!') def play_game(): guess = 0 attempts = 0 answer = bc.generate_secret() ...
b5335d4aebb301d4d512646ba504db701bffb729
cagbal/robotDBRedis
/robotDBRedis/fields.py
3,122
3.609375
4
#!/usr/bin/python from copy import deepcopy #instance check decorator def setter_decorator(func): def wrapper(self, val): if isinstance(val, self._type): func(self, deepcopy(val)) elif isinstance(val, str): func(self, val) else: raise Exception('Paramet...
a9adbb6b77f339396dcdc24c4032dc97216261c2
CruzJeff/ProjectEuler
/Project Euler ~ Python/Euler005.py
400
3.515625
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 8 03:25:05 2017 @author: User """ # only has to be really divisible by 11 12 13 14 15 16 17 19 20 # It has to be a multiple of 2520 divisors = [11,12,13,14,15,16,17,18,19,20] MIN = 9999999999 for x in range(2520,999999999,2520): if all(x % y == 0 for y in diviso...
0a5e32f7e1aad444c4217a21e8425d63a30e5c57
CruzJeff/ProjectEuler
/Project Euler ~ Python/Euler016.py
172
3.703125
4
# -*- coding: utf-8 -*- """ Created on Fri Oct 20 02:06:13 2017 @author: User """ result = 0 for char in str(2**1000): result = result + int(char) print(result)
18b2002a7adcd142cdb952750a92e906f81f1e1d
CruzJeff/ProjectEuler
/Project Euler ~ Python/Euler006.py
507
4
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 9 01:18:23 2017 @author: User """ # I don't know why this works but the formula to get the sum of the square of # n natural numbers is the gaussian sum multiplied by # 7, plus 2/3rd for every number above 10 that is part of the sum def gauss(n): result = (n*(n + 1))...
a5eab278be52daae3f5996ab6c7df55e8667ece6
alex-bellon/cryptopals
/set-1/challenge6.py
1,380
3.546875
4
def hamming(a, b): aBin = ''.join(format(ord(x) , 'b').zfill(8) for x in a) bBin = ''.join(format(ord(x) , 'b').zfill(8) for x in b) diff = 0 for aBit, bBit in zip(aBin, bBin): diff += int(aBit) ^ int(bBit) return diff def findDist(cipher): distances = [] for keysize in range(2, 4...
d6099f5dd1af5ba84714ccc6773f62d492d9d0d9
benjaminhuanghuang/ben-leetcode
/0026_Remove_Duplicates_from_Sorted_Array/solution.py
1,117
3.796875
4
''' 26. Remove Duplicates from Sorted Array Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, Given input array nums = [1,1,2], Your funct...
7d10795deece7b397c83f1b8ff5ec22c6f91f686
benjaminhuanghuang/ben-leetcode
/0108_Convert_Sorted_Array_to_Binary_Search_Tree/solution.py
920
3.96875
4
''' 108. Convert Sorted Array to Binary Search Tree Given an array where elements are sorted in ascending order, convert it to a height balanced BST. balanced means the difference of the height of left sub tree and the right sub tree <=1 ''' from data_structure.tree_node import TreeNode class Solution(object): ...
821fb57333dafe347d4272f5d9578ef93c5acf11
benjaminhuanghuang/ben-leetcode
/0214_Shortest_Palindrome/solution.py
755
4.09375
4
''' 214. Shortest Palindrome Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa". Given "abcd", return "dcbabcd". ''' class S...
745c4c1220d088eac0a39f5519237d1303fb8ca0
benjaminhuanghuang/ben-leetcode
/0061_Rotate_List/solution.py
694
3.671875
4
''' 61. Rotate List Given a list, rotate the list to the right by k places, where k is non-negative. For example: Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL. ''' from data_structure.list_node import ListNode class Solution(object): def rotateRight(self, head, k): if k == 0 or head ...
e14c143ea086ca19b10c2f4f9cb59e0d4d55f651
benjaminhuanghuang/ben-leetcode
/0306_Additive_Number/solution.py
2,106
4.21875
4
''' 306. Additive Number Additive number is a string whose digits can form additive sequence. A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two. For example: "112358" is an additive number bec...
7b2621677509993b7cd9f87df07be098dc6b5578
benjaminhuanghuang/ben-leetcode
/0055_Jump_Game/solution.py
1,666
3.765625
4
''' 55. Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: A = [2,3,1,1,4], return true. A = [3,2,1,0,4], ret...
e399195ee9411f017f6f87e8edc7a9a8f8d8561a
benjaminhuanghuang/ben-leetcode
/0012_Integer_to_Roman/solution.py
1,310
3.859375
4
''' 12. Integer to Roman Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. reference 13. Roman to Integer ''' class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ # ROMAN = ...
a4ff52bf767bec2d17ad4e192855aa4380807c6b
benjaminhuanghuang/ben-leetcode
/0398_Random_Pick_Index/solution.py
1,366
4.125
4
''' 398. Random Pick Index Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array. Note: The array size can be very large. Solution that uses too much extra space will not pass the judge. Example: i...
272a843592f160ad7cdbb2c798a266e0a7c50293
benjaminhuanghuang/ben-leetcode
/0123_Best_Time_to_Buy_and_Sell_Stock_III/solution.py
3,922
3.953125
4
''' 123. Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. Note: You may not engage in multiple transactions at the same time (ie, you must sell the sto...
f36d2444c9d61e79d25863846dbde00867d0b4d2
benjaminhuanghuang/ben-leetcode
/0796_Rotate_String/solution.py
182
3.609375
4
''' 796. Rotate String Level: Easy https://leetcode.com/problems/rotate-string ''' ''' Solution: ''' class Solution: def rotateString(self, A: str, B: str) -> bool:
f24a4e7f79d93b45958808f9b7759c25d0ab7989
benjaminhuanghuang/ben-leetcode
/0164_Maximum_Gap/solution.py
1,939
3.609375
4
''' 164. Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negative integers and fit in the 32-bit signed int...
c3b37226c380e8c08fff3cbcff91bbce2ecd1c71
benjaminhuanghuang/ben-leetcode
/1299_Replace_Elements_with_Greatest_Element_on_Right_Side/solution_test.py
437
3.59375
4
''' 1299. Replace Elements with Greatest Element on Right Side Level: Easy https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side ''' import unittest class TestSum(unittest.TestCase): def test_sum(self): self.assertEqual(sum([1, 2, 3]), 6, "Should be 6") def test_sum_tu...
25bae10ece13bc533f19441742688a962ae663fd
benjaminhuanghuang/ben-leetcode
/0166_Fraction_to_Recurring_Decimal/solution.py
1,282
3.96875
4
''' 166. Fraction to Recurring Decimal Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, return "0.5". Given numerator = ...
c7b600395166be7c5069592f77ee9d1e11794fe8
benjaminhuanghuang/ben-leetcode
/0046_Permutations/solution.py
1,132
3.890625
4
''' 46. Permutations Given a collection of distinct numbers, return all possible permutations. For example, [1,2,3] have the following permutations: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ''' class Solution(object): def permute_bad(self, nums): """ :type nums: List...
30e05ab2298b35f1e9562e00561f3cecf40c0b6f
benjaminhuanghuang/ben-leetcode
/1184_Distance_Between_Bus_Stops/solution.py
254
3.5
4
''' 1184. Distance Between Bus Stops Level: Easy https://leetcode.com/problems/distance-between-bus-stops ''' ''' Solution: ''' class Solution: def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
d867c5500e74fdf0eae3e44eb8738eff9e78303d
benjaminhuanghuang/ben-leetcode
/1334_Find_the_City_With_the_Smallest_Number_of_Neighbors_at_a_Threshold_Distance/solution.py
347
3.53125
4
''' 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance Level: Medium https://leetcode.com/problems/find-the-city-with-the-smallest-number-of-neighbors-at-a-threshold-distance ''' ''' Solution: ''' class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThres...
366f98c4234ef4c88c22925b45813bbb60cc1247
benjaminhuanghuang/ben-leetcode
/0093_Restore_IP_Addresses/solution.py
2,068
3.75
4
''' 93. Restore IP Addresses Given a string containing only digits, restore it by returning all possible valid IP address combinations. For example: Given "25525511135", return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) ''' class Solution(object): def restoreIpAddresses(self, s): ""...
216a5d6c9fe251b4c2bc3282b3f17c17114cc833
benjaminhuanghuang/ben-leetcode
/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts/solution.py
341
3.90625
4
''' 1374. Generate a String With Characters That Have Odd Counts Level: Easy https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts ''' ''' Solution: ''' class Solution: def generateTheString(self, n: int) -> str: if n % 2 == 0: return 'a'*(n-1) + 'b' else: ...
0836acd4024753e8799825c107c426f318eff4ac
benjaminhuanghuang/ben-leetcode
/0283_Move_Zeroes/solution.py
901
4.03125
4
''' 283. Move Zeroes Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: You must do this in-place without making a copy of ...
fc6127107d0807ee269b4505543ee30741c4695a
benjaminhuanghuang/ben-leetcode
/0189_Rotate_Array/solution.py
1,649
4.1875
4
''' 189. Rotate Array Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. ''' class Solution(object): de...
71711bc8f90927777f71535cb938e72eaf4dc1a1
benjaminhuanghuang/ben-leetcode
/0169_Majority_Element/solution.py
1,413
4
4
''' 169. Majority Element Given an array of size n, find the majority element. The majority element is the element that appears more than n/2 times. You may assume that the array is non-empty and the majority element always exist in the array. ''' # naive # sorting takes time of nlog(n) def majority_element(nums): ...
378aa30c20242c9228a08c4f7be48c444c7d29e0
benjaminhuanghuang/ben-leetcode
/0257_Binary_Tree_Paths/solution.py
835
4
4
''' 257. Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1->2->5", "1->3"] ''' class Solution: # @param {TreeNode} root # @return {string[]} def binaryTreePaths(self, root): ...
45929efac6474bb344733cd8130f9c2ea68f7bcd
benjaminhuanghuang/ben-leetcode
/0414_Third_Maximum_Number/solution.py
2,003
4.1875
4
''' 414. Third Maximum Number Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n). Example 1: Input: [3, 2, 1] Output: 1 Explanation: The third maximum is 1. Example 2: Input: [1, 2] Output: 2 Expl...
02b12c4d32a20ef261e92d11b57041faa3e5de4d
benjaminhuanghuang/ben-leetcode
/0450_Delete_Node_in_a_BST/solution.py
531
3.953125
4
''' 450. Delete Node in a BST Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the node is found, delete the node. Note: ...
e6cdd47a3fe566991b401e000debe99d16451178
benjaminhuanghuang/ben-leetcode
/0031_Next_Permutation/solution.py
1,715
4.125
4
''' 31. Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra...
5f6d71fb2ae0b9190211e11982ca98ce3be8edb7
benjaminhuanghuang/ben-leetcode
/0242_Valid_Anagram/solution.py
979
3.8125
4
''' 242. Valid Anagram Given two strings s and t, write a function to determine if t is an anagram of s. For example, s = "anagram", t = "nagaram", return true. s = "rat", t = "car", return false. Note: You may assume the string contains only lowercase alphabets. Follow up: What if the inputs contain unicode charac...
77f9a2759dece1420a00ff430b9b1a3b1be4d5d5
benjaminhuanghuang/ben-leetcode
/0038_Count_and_Say/solution.py
934
3.671875
4
''' 38. Count and Say The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ... 1 is read off as "one 1" or 11. 11 is read off as "two 1s" or 21. 21 is read off as "one 2, then one 1" or 1211. Given an integer n, generate the nth sequence. Note: The sequence of integer...
aba8b25c6cadd32238b10c0972f7324fe6590d97
benjaminhuanghuang/ben-leetcode
/0137_Single_Number_II/solution.py
1,597
3.546875
4
''' 137. Single Number II Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' class Solution(object): # Time limit exceeded def singleNumber_n...
daff8c9e7f9b79ba19caf28bf6fa06f6c94a5d92
benjaminhuanghuang/ben-leetcode
/0393_UTF-8_Validation/solution.py
3,308
4.09375
4
''' 393. UTF-8 Validation A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code. For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bi...
4c672653468f1efe2a08325e36581850e93fcee6
KingsDemise/Speedrun-Projects
/YTVIDDOWN.py
817
3.5625
4
import tkinter as tk import pytube from pytube import YouTube from tkinter import * root=Tk() root.geometry('500x300') root.resizable(0,1) root.title("EZ YouTube Video Downloader by K13") Label(root,text='Youtube Video Downloader',font='"Billy Ohio" 25 bold').pack() link = StringVar() Label(root,text='PASTE L...
3e51408dcb57af5d6856a2b84dbca16e9d240920
Robin-Andrews/Compucademy-Data-Science
/Probability Distributions with Python/dice.py
560
3.609375
4
""" Plot Discrete Probability Distribution for Fair 6-Sided Die """ import numpy as np import matplotlib.pyplot as plt import seaborn as sns NUM_ROLLS = 1000 values = [1, 2, 3, 4, 5, 6] sample = np.random.choice(values, NUM_ROLLS) # Numpy arrays containing counts for each side side, count = np.unique(sample, return...
79dcac1b35606b4217dbfa966b3cb55162658de7
CodyDeepPlay/LeetCodePractice
/Q205_IsomorphicStrings.py
5,752
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu May 13 22:06:55 2021 @author: mingmingzhang leetcode 205, isomorphic strings, Given two strings s and t, determine if they are isomorphic. Two strings s and t are isomorphic if the characters in s can be replaced to get t. All occurrences of a cha...
a378651ee4a9fcddef77255964443d0e2812af52
alankrit03/CodeForces_Solutions
/59A. Word.py
159
3.671875
4
data = input() l=u = 0 for x in data: if x.islower(): l+=1 else: u+=1 if l>=u: print(data.lower()) else: print(data.upper())
8566310dfc485f09f0fda2d98671d0fcf4f1bcf3
alankrit03/CodeForces_Solutions
/136A. Presents.py
161
3.640625
4
n = int(input()) data = input().split() dict_ = {} for i in range(n): data[i] = int(data[i]) for i in range(n): print(data.index(i + 1) + 1, end=' ')
74d3f5a5bc9b0cef564d2149f9bf062d1de3c0b5
albertoborsatto/DesafioPontosTaxi-ITAcademy
/funcoes/pontosProximos.py
2,721
3.625
4
import os from math import radians, sin, cos, sqrt, asin from operator import itemgetter def MostraPontos(arq): os.system('cls') or None print(arq) def Troca(lat, lon, char1, char2): lat = lat.replace(char1, char2) lon = lon.replace(char1, char2) return [lat, lon] def Localizacao(): os.sys...
024caf52ce66f03255d68ed2191c0c68a8677612
Mrityunjay8852/Coding
/question3.py
660
3.59375
4
#Given five positive integers, find the minimum and maximum # values that can be calculated by summing exactly four of the five integers. # Then print the respective minimum and maximum values as a single line of two # space-separated long integers. arr=[1,2,5,6,9] #arr=[5,5,5,5,5] maximum=[] minimum=[] sum=0 sum2...
60ade8a28691b7a6644416d1f1209bb77184cbd4
nwtgck/python-type-hints-prac
/union_prac.py
623
3.640625
4
import typing def f1(i_or_s: typing.Union[int, str]) -> bool: return type(i_or_s) == int def f2(i_or_s_or_f: typing.Union[int, str, float]) -> bool: return type(i_or_s_or_f) == int print(f1(1)) print(f1("hello")) # print(f1(1.2)) # mypy error (GOOD!): error: Argument 1 to "f1" has incompatible type "flo...
b3764b765b85409587788a1f2ad07dde6e7d2f3d
nwtgck/python-type-hints-prac
/hello.py
546
4
4
import numbers def hello() -> str: "hello, world" def add_int(a: int, b: int) -> int: return a + b def add_float(a: float, b: float) -> float: return a + b # (error: Unsupported left operand type for + ("Number")) # def add_number(a: numbers.Number, b: numbers.Number) -> numbers.Number: # return a ...
7a232421178274dc43595de0dc355d2948f8731b
jcho13/python-ch2.4
/for.py
1,728
3.671875
4
print("--- for 반복 ---") a = ['cat', 'dog', 'fish'] for animal in a: print(animal, end=" ") else: print("") print("--- break ---") for i in range(10): if i > 5: break else: print(i, end=", ") print("") print("--- 복합자료형을 사용하는 for ---") l = [('둘리', 10),('치킨',100),('돈',1000)] for data ...
a9ed6c083ba89a89f43daf012241f802a37b1753
krito1124/200820
/english_dic.py
1,862
3.9375
4
d = {} print('welcome to the 高手系統') while True: print('1.建立字典') print('2.enter all the 單字') print('3.english翻chinese') print('4.chinese翻english') print('5.test') print('6.leave') option = input('please enter 選項:') if option == '6': break elif option ...
b8f6e39447a33973e6a3d806cc407b73b372f7be
walokra/theeuler
/python/euler-1_fizzbuzz.py
413
4.125
4
# Problem 1 # 05 October 2001 # # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. # # Answer: 233168 # #!/usr/bin/python sum = 0 max = 1000 for i in range(1,max): if i%3 ...
9091106bbd1ddf8d12e1a82dc8ae2a33746ba7b8
dsjmhjs/pyetf
/examples/chapter2.py
484
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sun Jul 28 09:22:00 2019 @author: w """ first_number = input("第一个数:") operator = input("运算符:") second_number = input("第二个数:") if ("." in first_number) or ("." in second_number): n1 = float(first_number) n2=float(second_number) else: n1 = int(first_number) n2=int...
7a3a0cbfa39f46a1e3a986fee88b68c6c0f50397
monpro/algorithm
/src/binary-trees/find-bottom-left-tree-value-513.py
683
3.796875
4
# 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 __init__(self): self.maxDepth = 0 self.val = 0 def findBottomLeftValue(self, root): """ ...
866251abd454a5f25cf710b5be8773ba325ab029
monpro/algorithm
/src/dps/Longest_Common_Subsequence_77.py
666
3.625
4
class Solution: """ @param A: A string @param B: A string @return: The length of longest common subsequence of A and B """ def longestCommonSubsequence(self, A, B): # write your code here if len(A) == 0 or len(B) == 0: return 0 dp = [[0 for _ in range(len(B)...
be1e13b8c3636196e3c28acbc246a9ed4ac506e4
monpro/algorithm
/src/binary-trees/maximum-depth-of-binary-tree.py
801
3.875
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: An integer """ def maxDepth(self, root): # write your code here...
1557d535e8ff776b87180cd35523c105cd3c1f9a
monpro/algorithm
/src/designs/add-and-search-word-data-structure-design-211.py
1,261
4
4
import collections class TrieNode(): def __init__(self): self.children = collections.defaultdict(TrieNode) self.isWord = False class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def addWord...
1e2406c8c46fa9119757b73511940b89d4a6dac5
monpro/algorithm
/src/designs/design-twitter-355.py
1,627
3.90625
4
import collections class Twitter: def __init__(self): """ Initialize your data structure here. """ self.tweets = collections.defaultdict(list) self.following = collections.defaultdict(set) self.order = 0 def postTweet(self, userId, tweetId): """ ...
e223b626fee8d4ed92415612d02a59584c41f523
monpro/algorithm
/src/arrays/sequential-digits-1291.py
583
3.546875
4
class Solution(object): def sequentialDigits(self, low, high): """ :type low: int :type high: int :rtype: List[int] """ result = [] for digit in range(1, 9): cur, nextDigit = digit, digit while cur <= high and nextDigit < 10: if...
d21d48032d83cbe3f967d4c1fb2a1e5c0b49bef0
monpro/algorithm
/src/binary-trees/binary-tree-postorder-traversal.py
1,038
3.828125
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A Tree @return: Postorder in ArrayList which contains node values. """ def postorderTraversal(self, root):...
958f8321c4b5dcba13a9585746f6b91cfc08ae26
monpro/algorithm
/src/bfs/minesweeper-529-bfs.py
1,395
3.5625
4
class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: if not board: return board x, y = click[0], click[1] if board[x][y] == "M": board[x][y] = "X" else: direction = [[0, 1], [0, -1], [1, 0], [-1, 0], [...
ed1b60df3cfc41ba49c4afbbe628ae19416f0640
monpro/algorithm
/src/graphs/valid_tree_in_graph.py
1,198
3.90625
4
class Solution: """ @param n: An integer @param edges: a list of undirected edges @return: true if it's a valid tree, or false """ def validTree(self, n, edges): # write your code here if n == 0: return False # if #edges == n - 1 if len(edge...
638e4c705d25e0b18a591253636b22894b257947
monpro/algorithm
/src/stack/maximum-depth-of-n-ary-tree-559.py
830
3.65625
4
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: if not root: return 0 if not root.children: return 1 ...
d0d6f1367eaa05095dcf9f686faa37e2add66c58
monpro/algorithm
/src/backtraces/WordSearch-79.py
1,099
3.859375
4
class Solution: """ @param board: A list of lists of character @param word: A string @return: A boolean """ def exist(self, board, word): if len(word) == 0: return False if len(board) == 0 or len(board[0]) == 0: return False for i in range(len(bo...
298c1a84d5d0cef07f40c7d73b52847ffc19d467
monpro/algorithm
/src/linked-lists/remove-elements-27.py
422
3.578125
4
class Solution: def removeElement(self, nums, val): if len(nums) == 0: return 0 cur = 0 for i in range(len(nums)): if nums[i] == val: continue else: nums[cur] = nums[i] cur += 1 nums = nums[:cur] ...
85d021b348e5879e0018ec834731b1ff96289efb
monpro/algorithm
/src/binary-trees/binary-tree-level-order-traversal-ii-107.py
869
3.796875
4
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: A tree @return: buttom-up level order a list of lists of integer """ def levelOrderBottom(self, root): ...
af63a6170a1cc490e0cc161cbc968e8bfab47578
monpro/algorithm
/src/binary-searches/Smallest_Rectangle_Enclosing_Black_Pixels.py
2,811
3.828125
4
from typing import Any, Union class Solution: def minArea(self, image, x, y): ''' to find min area, you need to find left, right, up and down of 1 first shown position :param image: image mixed with 0 and 1, only 1 connected components of black pixels( all 1s') :param x: (x,y) posi...
a1d31b32e70f7e324a2de098967f7cd113081264
monpro/algorithm
/src/contest/169/all-elements-in-two-binary-search-trees-1305.py
1,402
3.78125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]: queue_1 = [] queue_2 = [] result = [] ...
62faa9633f4386aa9402155addcfabfc15183dea
AleksandraBard/milestone_2
/generators.py
803
3.890625
4
def hundred_numbers(): i = 0 while i < 100: yield i i += 1 # print(hundred_numbers()) # print([x * 2 for x in hundred_numbers()]) # function remembers where it stopped g = hundred_numbers() print(next(g)) print(next(g)) print(list(g)) # starts from 2 - where we stopped my_range_obj = range...
1c61efc8ffa18c5b8892ab26aa4c3b15c218aabd
oguzaktas/competitive-programming
/leetcode/october-leetcoding-challenge/best_time_to_buy_and_sell_stock_iv.py
747
3.5625
4
class Solution: def maxProfit(self, k: int, prices: List[int]) -> int: # Kadane's algorithm if 2 * k >= len(prices): return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, len(prices))) pnl = [0] * len(prices) for _ in range(k): val = 0 ...
a5f8779b2956285fe4f90c991eaac64ef4969724
oguzaktas/competitive-programming
/project-euler/longest_collatz_sequence.py
1,926
3.71875
4
sequence_length = {1: 0} def collatz_sequence_length(i): global sequence_length if i in sequence_length: return sequence_length[i] if i % 2 == 0: length = collatz_sequence_length(i // 2) else: length = collatz_sequence_length(3 * i + 1) length += 1 sequence_length[i] = l...
e6027b17bc4ba6360b35205de23fc3e77f78966e
Saumyaa27/FACE-RECOGNITION-USING-OPENCV-DEEP-LEARNING
/face.py
3,087
3.5625
4
import cv2 import numpy as np # Load Cascade Classifier - a pre-trained frontal_face haar classifier face_classifier = cv2.CascadeClassifier( 'E:\\Saumyaa\\sem 6\\ai app\\Deep-Learning-Face-Recognition-master\\haarcascade_frontalface_default.xml') # Defining a function which identifies the face and extracts it #...
8eeb3b9fb2593f8a3c84b80cb7bd220d2b221ccb
dipnrip/Python
/Python/Labs/lab2.py
294
4.15625
4
weight = int(input("Enter weight: "),10) height = int(input("Enter height: "),10) bmi = (weight/(height**2))*703 if(bmi < 18.5): print("underweight") if(bmi > 18.5 and bmi < 24.9): print("normal") if(bmi < 29.5 and bmi > 25.0): print("overweight") if(bmi >= 30): print("obese")
515528ac9053d7e6ee28c848efd42ad46a284a42
iurantr/python_exercises
/sum_of_sqrt.py
482
4.03125
4
def sum_of_sqrt(*args): """Return the sum of square roots of the parameters""" ans = .0 for x in args: ans += x ** 0.5 return ans print(sum_of_sqrt(12, 13, 7)) import numpy as np def basic_statistics(*args): """Return average and variance of numbers""" print(args) return np.mean...
bfdde1cfc574f2fad37b71a43b3ec0b0599ef912
nickguyjs/Encryption-with-Flask
/CaesarCipher.py
915
4.03125
4
from random import randint def decryptCaesar(text): """Returns the decrypted message using the key 'a'.""" dec = "" for i in range(len(text)): # loops through all chars in text val = ord(text[i]) # sets val to current char val -= Key.key # removes the key from val dec += chr(val) # turns val to char,...
8b9e48179dd8cc05b0a2013bc27ada76b545d690
zenggang888/blogs
/Python/learning/99tables.py
131
3.515625
4
m=1 while m<=9: i=1 while i<=m: print("%d*%d"%(m,i)+"="+str(i*m),end="\t") i+=1 print() m+=1
c1aa88fb8cb4a2b79ad916e3f462da64fa4ec125
technodactyl/dda-emulator
/dda.py
2,008
3.546875
4
import decimal from random import randint def make_grid(): grid = [] for i in range(50): pixel_row = [] for j in range(50): pixel_row.append("-") grid.append(pixel_row) return grid screen = make_grid() def dda(x1, y1, x2, y2): dx = x2 - x1 dy = y2 - y1 adx ...
d8b1d9e71ccb9fd29781aa4eb62ae3b175921fb0
yansolov/gb
/gb-python/lesson03/ex06.py
967
4.1875
4
# Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и # возвращающую его же, но с прописной первой буквой. # Например, print(int_func(‘text’)) -> Text. # Продолжить работу над заданием. В программу должна попадать строка # из слов, разделенных пробелом. Каждое слово состоит из латинских ...
364b39ae12c52f969ec99a0d0111042efbca5cf5
yansolov/gb
/gb-python/lesson04/ex06.py
917
4.125
4
# Реализовать два небольших скрипта: # а) итератор, генерирующий целые числа, начиная с указанного, # б) итератор, повторяющий элементы некоторого списка, определенного заранее. from itertools import count, cycle def count_func(start, stop): for el in count(start): if el > stop: bre...
59249ad2378eae8d10121660b550b65231c75d06
yansolov/gb
/gb-python/lesson01/ex06.py
312
3.859375
4
firstkm = int(input("Спортсмен пробежал в первый день, км: ")) lastkm = int(input("В последний день он пробежал не менее, км: ")) day = 1 while firstkm <= lastkm: firstkm = firstkm * 1.1 day += 1 print("Номер дня: ", day)
42970ad7e8f55be04a2fa2085931396bc186d85a
NickMichaels/morning-commute
/signal.py
2,857
4.09375
4
import random class Signal: """ Class to create a "signal" that will be placed on a road Attributes: location (str): Location of the signal, should correspond to a mile marker within the confines of a road. r_cycle (int): Amount of time in seconds that the sig...
5a87c90eadead4e15121af4ab96c39325baeb437
hayasam/se4ai-i5-tpot
/transformers/ExtractReleaseDateFeatures.py
1,012
3.515625
4
from sklearn.base import BaseEstimator, TransformerMixin class ExtractReleaseDateFeatures(BaseEstimator, TransformerMixin): """ This transformer takes a column with a date string formatted as 'YYYY-mm-dd', extracts the year and month, and returns a DataFrame with those columns. """ def __init_...
f3b2f3f751e37256e051e596960e063e86fe7f12
WinDaLex/jacks-or-better-calculator
/TestCardClass.py
1,631
3.625
4
# -*- coding: utf-8 -*- import unittest from Card import * class TestCardClass(unittest.TestCase): def test__init__(self): card = Card('S', 'T') self.assertEqual([card.suit, card.rank], ['S', 'T']) with self.assertRaises(ValueError): card = Card('invalid_suit', '4') ...
fc666585ae9b65e6f6d52c7047d4090cd2a4397c
adalei11/ics3u-classwork
/coding_practice_2020_11_25.py
6,211
3.953125
4
#CODING BAT #hello_name def hello_name(name): return "Hello " + name + "!" #make_abba def make_abba(a, b): return a + b*2 + a #make_tags def make_tags(tag, word): return "<"+tag+">" + word + "</"+tag+">" #make_out_word def make_out_word(out, word): return out[:2] + word + out[2:] #extra_end def extra_end(s...
e82cdf4c0ca7e3259176900d2e4aa98cfb674ae2
ChanelAquino/Image_Manipulation_with_Python
/Aquino_project1.py
1,605
3.640625
4
#Names: Chanel Aquino and Marcus Dixon #Date Due: 12 February 2016 #Description: CST205 Project 1 Image manipulation to replace undesireable pixels in a set of otherwise similar images. #prompt user to choose a directory folder = pickAFolder() #create a list of pictures pictures = [] #traverse through contents of fo...
fb95c2e91c3161e71760267ccb1874f6d1453437
Ayona04/pop-one-project-adunca04
/cities.py
5,141
4.125
4
from math import * import random import pandas as pd import matplotlib.pyplot as plt def read_cities('city-data.txt'): file = open('city-data.txt','r') road_map = [] for line in file: road_map.append(tuple(line.strip().split('\t'))) file.close() return road_map """ Read in the citi...
da464f0933d06dc70857561578baf4126af3687b
treiina/artezio_prishchepa_kseniia
/Lesson 2/Task1.py
179
3.625
4
# Task 1 X = int(input()) counter = 0 for i in range(X): if i % 2 == 1: print(i*i) counter += 1 print("Количество таких чисел: ", counter)