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
e1c6e80463203711799cdf2c915ae6f267d48e3f
jackmoody11/project-euler-solutions
/python/p076.py
323
3.5
4
# Too slow - needs to be further optimized def partition(n, m): if n == m: return 1 + partition(n, m-1) elif m == 0 or n < 0: return 0 elif n == 0 or m == 1: return 1 else: return partition(n, m-1) + partition(n-m, m) if __name__ == "__main__": print(partition(100, 9...
970167ef3c2601beac886f365afae662981e1c15
jackmoody11/project-euler-solutions
/python/p065.py
518
3.734375
4
# Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e. from utils import digital_sum def cfrac_to_frac(seq): """ Continued fraction to fraction """ num, den = 1, 0 for i in reversed(seq): num, den = den + num*i, num return num, den def comput...
167f2bb00363cffc74b32bae18fe0839e887dce3
jackmoody11/project-euler-solutions
/python/p045.py
564
3.890625
4
from utils import is_tri, is_pent, is_hex def hex_num(i): return 2*i**2 -i def compute(): # We already found that H_143 satisfies this # condition, and we want to find the next num # that satisfies the condition # We use hex_num to generate the numbers, because this grows the fastest # and all...
8d77b90804fa8eb64356b97a6f9fc9c8db0d81d9
mzprz/antoify
/antoify.py
1,190
3.90625
4
import numpy as np import sys def antoify(text): text = text.lower() text_bin = text.split(" ") text_bin for i in range(len(text_bin)): word = text_bin[i] l = len(word) # char lenght of a word n = np.random.randint(1,l-1) if l-1 > 1 else l-1 # total random char per word ...
b9dd23c5823f25ebdeb35289aaac0aa364789e68
DrBrowntown/Udacity-projects
/programming-languages/fibonacci-memoization.py
469
3.9375
4
# Chart caches previous calculations chart = {} def memofibo(n): # Check chart for value, return if found if n in chart: return chart[n] # If n is less than 3 it has a value of 1 if n < 3: value = 1 # Assign recursively called functions to value else: value ...
357ef8139c352152920e09723d0c5fd608d1a86f
songbirdstew/latin-eng-prac
/vocabprac.py
1,514
3.671875
4
# Created by: Sarah Bicknell # Date: 15th September 2015 # Info: Latin vocabulary practice program as practice def openFiles(): # edit this to allow selection of specific chapter lists maybe latinDict = {} dictFile = open("unit1vocab.txt") for line in dictFile: latin, eng = ...
c55af45dee5dd8861b67840741f798d791302b35
AHoffm24/python
/Chapter2/classes.py
999
4.40625
4
# # Example file for working with classes # #methods are functions in python #self argument refers to the object itself. Self refers to the particular instance of the object being operated on # class Person: #example of how to initalize a class with variables # def __initialize__(self, name, age, sex): # s...
5e51e9e74eeac55f6d251917d7c11593c06e8d52
ziliangpeng/naoshima
/ml/transformers/RNN_LSTM/RNN.py
757
3.625
4
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import SimpleRNN, Dense # Prepare the dataset data = np.array([i for i in range(1, 101)]) # The numbers from 1 to 100 X = data[:-1].reshape(-1, 1, 1) # The inputs to the model are the numbers from 1 to 99 y = data[1:] # T...
58b14b436e842442e92a12cab3f08992e5f6acb2
XTremeRox/AI-Lab
/Day1/prog1.py
405
4.21875
4
#!/usr/bin/python3 def print_list_elements(l): for element in l: print(element, end=' ') print() if __name__=="__main__": l = [] l = ("Make me wanna say").split() print_list_elements(l) #insertion l.insert(4, "like") print_list_elements(l) #appending l.append("oh") ...
2ff1b1690ec24bf01f72a5f404b33e9cc43f8ac0
AK391/vits
/text/__init__.py
1,572
3.6875
4
""" from https://github.com/keithito/tacotron """ from text import cleaners from text.symbols import symbols # Mappings from symbol to numeric ID and vice versa: _symbol_to_id = {s: i for i, s in enumerate(symbols)} _id_to_symbol = {i: s for i, s in enumerate(symbols)} def text_to_sequence(text, cleaner_names): '...
e05183203807deaea037299d0b08569af4a36bab
zhaopan-vip/-
/Python知识图谱/基础知识/7.面向对象编程/oop.py
717
3.640625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @auth: zhaopan @time: 2020/8/18 10:19 @desc: Object Oriented Programming """ class A(object): """ 类与派生类 """ def __init__(self): print('enter A') print('leave A') class B(A): """ 继承类 """ def __init__(self): print...
2f2a6bb5c06dd40ffb851a906f80b3663384448d
zhaopan-vip/-
/Python知识图谱/基础知识/1.基本数据结构/集合/set.py
476
3.84375
4
#!/usr/bin/python # -*- coding: UTF-8 -*- """ @auth: zhaopan @time: 2020/8/13 11:55 @desc: set 集合 """ # https://docs.python.org/3.6/tutorial/datastructures.html#sets # 集合 s = {1, 2, 3} s.add(4) # 增加元素 s.remove(4) # 删除元素 # 排序 s_sorted = sorted(s) # 查找 assert 1 in s # 运算符 a = set('abracadabra') b = set('...
f47570ea24601c90a865a432834560c00becef38
sergiotasconmorales/brstmss
/evaluation/dice_similarity.py
2,910
3.515625
4
import numpy as np import cv2 as cv2 def dice_similarity(segmented_image, ground_truth): """ This function calculates the dice similarity index for the segmentation of a given image and its ground truth Parameters ---------- segmented_image: Numpy array binary mask( either 0-1 or 0-...
6c7cf0d06aa3f9fcf182335dd1c5c1abb4b01896
rodrigo9000/PycharmProjects
/Coderbyte/LetterCapitalize.py
334
4
4
# Using the Python language, have the function LetterCapitalize(str) take the str parameter being passed and capitalize # the first letter of each word. Words will be separated by only one space def main(): def LetterCapitalize(str): print str.title() LetterCapitalize('i ran there') if __name__== "__m...
e22f5ff5265d5073eeac203c5a6c8e017babdf23
rodrigo9000/PycharmProjects
/PlayingWithSeries/Mission3_RollTheDice.py
513
4.34375
4
# User should be able to enter how many dices he wants to roll: 1 ,2 or 3. He should pass this value as a parameter in the # function RollTheDice(num). Dices should show random numbers from 1 to 6. import random def main(): def RollTheDice(num): if num in [1, 2, 3]: for turns in range(1, (num + ...
a59e5241143f4d09efadf8253a5996741ce81ada
vonmoraes/Python-World
/chatbot/chat_funcoes.py
452
3.5
4
# -*- coding: utf-8 -*- from unicodedata import normalize """ Var Globais """ entrada = ">>: " """ Funcoes Globais """ def normalizar_frase(txt): return remover_acentos(txt).lower() pass """ """ def remover_acentos(txt): return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII') pass "...
4511d5b1cbcd7453584d218c6506cd13d5f15677
Laura7089/projectEuler
/python/26.py
552
3.890625
4
#!/bin/env python3 # Problem at: # https://projecteuler.net/problem=26 def recurringLength(n): total = 0 while True: return total upperBound = int(input("Enter the highest number you want to test: ")) lowerBound = int(input("Enter the lowest number you want to test: ")) lengths = [recurri...
fbfa66fe6e8c10e02712f7238868907894874a8e
anulrajeev/MA-323-Monte-Carlo-Simulation
/LAB 3/180123057_MOHAMMAD_HUMAM_KHAN_q2.py
3,213
3.921875
4
##To run the code type in terminal: python3 180123057_MOHAMMAD_HUMAM_KHAN_q2.py import random import math import numpy as np import statistics import matplotlib.pyplot as plt ##Function to calculate value of f(x) def f(x): y = 20*x*((1-x)**3) return y ##Distribution Function of f(x) def F(x): y = 10 * x**2 - 2...
644c107f50e7518db5f267377214b03d8bad176c
anulrajeev/MA-323-Monte-Carlo-Simulation
/LAB 10/180123057_MOHAMMAD_HUMAM_KHAN.py
1,867
3.953125
4
##To run the code type in terminal: python3 180123057_MOHAMMAD_HUMAM_KHAN.py import math import random import numpy as np import pandas as pd import statistics import matplotlib.pyplot as plt # Function that implements the Monte Carlo Estimator def Estimate(M): Y = [] for i in range(M): u = np.random.uniform(0,1...
b2e02bba51c661eec28508bce042d007dcab4da4
xVura/math
/math3.py
1,377
3.875
4
# acest script lasa utilizatorul sa introduca x si y si cu ele face un grafic # ajutator pentru math4 # importa modulele necesare import numpy as np import matplotlib.pyplot as plt import math fig = plt.figure() # momentan lasa utilizatorul sa introduca x si y x = float(input("Introdu numarul x: ")) y = float(input(...
3f718c0f1f9901eb49d1eb3098d970d19402e28e
adhammhaydat/game-of-greed
/game_of_greed/banker.py
797
3.984375
4
class Banker(): """ A class for holding the functionality of updating the shelf and the player's balance """ def __init__(self): """ The constructor method """ self.balance = 0 self.shelved = 0 def shelf(self, point): """ Add points to the she...
22c056f5611eee2207fe168b275bf43b55a45712
suryavanshi/Movies
/media.py
561
3.5
4
import webbrowser class Movie(): """Movie Class-Provides a way to store Movie related information""" VALID_RATINGS = ["G","PG","PG-13","R"] def __init__(self,movie_title,movie_storyline,poster_image,trailer_youtube): self.title = movie_title #these are instance vars accessible by object ...
fe8b249cdb4fc996b1f5c3b10619ca64869a690d
LonelyDuo/Book-Recommendation
/recom.py
7,438
3.796875
4
import requests import json import random #Make the actual request to the API using the python requests library #You may need to run the command 'pip install requests' in your terminal SEARCH_ENDPOINT = "https://www.googleapis.com/books/v1/volumes?" # SEARCH_ENDPOINT = "https://www.googleapis.com/books/v1/volum...
f5ead71fd7278f2c301d5448b4b1475527e8ea58
oskarjavier0131/Proyectos-Python
/Proyectos/Trapecio.py
461
3.703125
4
## AREA Y PERIMETRO DEL TRAPECIO base_1 = int(input("Ingrese la base inferior del trapecio: ")) base_2 = int(input("Ingrese la base superior del trapecio: ")) altura = int(input("Ingrese la altura del trapecio: ")) area = (base_1+base_2)*altura perimetro = (base_1 + base_2)+ (altura*2) are...
1933cd3385d25e4a1d15db79cff9c19c0736baf4
dhaval38/Python-Examples
/property/p.py
338
3.953125
4
class P: def __init__(self, x): self.x = x @property def x(self): return self.__x @x.setter def x(self, x): print("value of x : %s" %x) if x > 1000: self.__x = 1000 elif x < 0: self.__x = 0 else: self.__x = x if __name__ == "__main__": p = P(1001) print("p.x : %d" %p.x) p.x = -2 print("...
7c579d2699624b54631ce2a22d2460050307f560
dhaval38/Python-Examples
/LMFR/filter.py
202
3.671875
4
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] odd_numbers = list(filter(lambda x:x%2, fibonacci)) print odd_numbers even_numbers = list(filter(lambda x:x%2 == 0, fibonacci)) print even_numbers
ef0b4c8b5b4bc652287a4eaa3d43f9ee71ea1f15
dhaval38/Python-Examples
/LMFR/prime.py
151
3.5625
4
no_primes = [j for i in range(2, 8) for j in range(i*2, 100, i)] print no_primes primes = [x for x in range(2, 100)if x not in no_primes] print primes
3efc39ac8f5c6d993ddf9a0cadbeca97115d8236
abhishyam21/python_learning
/Problem31to39.py
2,823
3.6875
4
# problem 31 def compute_gcd(x, y): gcd = 1 if x % y == 0: return y for k in range((y / 2), 0, -1): if x % k == 0 and y % k == 0: gcd = k break return gcd print(compute_gcd(2, 5)) print(compute_gcd(12, 17)) print(compute_gcd(4, 6)) print("--------------Problem...
41e63ead44f9dd31192a76c379af439d042f875f
abhishyam21/python_learning
/strings/Problem11to20.py
2,900
3.859375
4
# problem 11 def remove_odd_index(input): temp = '' for i in range(0, len(input), 2): temp += input[i] return temp print(remove_odd_index("abhishyam")) print(remove_odd_index("ki")) print(remove_odd_index('abcdef')) print(remove_odd_index('python')) print("--------------Problem 11 End-----------...
39e3c73fef8e3e15635c92d403c544ad3cd18205
abhishyam21/python_learning
/lists/Problem51to60.py
2,432
3.6875
4
# problem 51 def list_slice1(input, n): res = [] for i in range(n): temp = [] for j in range(i, len(input), n): temp.append(input[j]) res.append(temp) return res def list_slice2(input, n): return [input[i::n] for i in range(n)] input = ['a', 'b', 'c', 'd', 'e', '...
5aac32c579996113a18885e9b3c0ee42bfeb256a
qiyuangong/Top_Down_Greedy_Anonymization
/utils/utility.py
504
3.671875
4
""" utility functions """ # !/usr/bin/env python # coding=utf-8 def cmp_str(element1, element2): """compare number in str format correctley """ try: return cmp(int(element1), int(element2)) except ValueError: cmp(element1, element2) def get_num_list_from_str(stemp): """ if fl...
cb996d43bb8e09d067a84af29c94db5cc5d426b5
jusmojito/HackerRank
/Viral Advertising.py
217
3.609375
4
n=int(input()) shared=5 cumulative=0 liked=int(shared/2) cumulative=liked+cumulative for i in range(0,n-1): shared=liked*3 liked=int(shared/2) cumulative=cumulative+liked print(cumulative)
e537bd845ccc229b2aa17d1d056ddf26555bfdee
95subodh/Leetcode
/055. Jump Game.py
729
3.65625
4
#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], return false...
3fde42315679f74e8f4cf312fd442aa8138e5066
95subodh/Leetcode
/122. Best Time to Buy and Sell Stock II.py
612
3.765625
4
#Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again). class Solution(object): def maxPr...
b410db6a9ea07a05b7e80afad10bfed4a7d643b6
95subodh/Leetcode
/116. Populating Next Right Pointers in Each Node.py
1,266
4.28125
4
#Given a binary tree # #struct TreeLinkNode { # TreeLinkNode *left; # TreeLinkNode *right; # TreeLinkNode *next; #} #pulate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. # #itially, all next pointers are set to NULL. # #te: # #u may only use c...
b50ac2af82d585feb9759e3a1bda535521ee143a
95subodh/Leetcode
/191. Number of 1 Bits.py
289
3.78125
4
#Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ ans=0 while n>0: if n&1: ans+=1 n/=2 return ans
6c0a52a3425174cb1d95b3c386122c76847aa6d5
95subodh/Leetcode
/151. Reverse Words in a String.py
441
3.984375
4
#Given an input string, reverse the string word by word. # #For example, #Given s = "the sky is blue", #return "blue is sky the". # #Update (2015-02-12): #For C programmers: Try to solve it in-place in O(1) space. class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ l=list(s.s...
93149f960c8b7d342dde0ea643b3977b3ae35bd3
95subodh/Leetcode
/326. Power of Three.py
240
4.34375
4
#Given an integer, write a function to determine if it is a power of three. from math import * class Solution(object): def isPowerOfThree(self, n): """ :type n: int :rtype: bool """ return True if n>0 and 3**20%n==0 else False
c2b35c7c531a6326d8c206da956d42ef40ff1b1e
95subodh/Leetcode
/319. Bulb Switcher.py
485
4.0625
4
#There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how man...
f476f89587104f2e2626c63d8cf749e91aa9d124
95subodh/Leetcode
/238. Product of Array Except Self.py
829
3.6875
4
#Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. # #Solve it without division and in O(n). # #For example, given [1,2,3,4], return [24,12,8,6]. # #Follow up: #Could you solve it with constant space complexity?...
e72aec8095f353060fa7365fbe4967f3f50ea952
95subodh/Leetcode
/415. Add Strings.py
765
3.859375
4
#Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2. # #Note: # #The length of both num1 and num2 is < 5100. #Both num1 and num2 contains only digits 0-9. #Both num1 and num2 does not contain any leading zero. #You must not use any built-in BigInteger library or convert ...
16a38a01b111328bc593135f2e5db0c6abe17332
95subodh/Leetcode
/216. Combination Sum III.py
641
3.6875
4
#Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. # # #Example 1: # #Input: k = 3, n = 7 # #Output: # #[[1,2,4]] # #Example 2: # #Input: k = 3, n = 9 # #Output: # #[[1,2,6], [1,3,5], [2,3,4]] c...
6149f293832281f19d85900c41e4c693f25d154c
95subodh/Leetcode
/168. Excel Sheet Column Title.py
290
3.609375
4
#Given a positive integer, return its corresponding column title as appear in an Excel sheet. class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ r="" while n>0: z=n%26 if z==0: z=26 n-=1 r+=chr(z+64) n/=26 return r[::-1]
0346424774a4b38d9111a81fb311a4f57c00f0ad
95subodh/Leetcode
/091. Decode Ways.py
859
3.625
4
#A message containing letters from A-Z is being encoded to numbers using the following mapping: # #'A' -> 1 #'B' -> 2 #... #'Z' -> 26 #Given an encoded message containing digits, determine the total number of ways to decode it. # #For example, #Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12). ...
cb480cd5efb8bf8c8d8f166cc83de9d32681497a
youavang/Model-Accuracy-Test
/Model Accuracy Test.py
7,776
3.953125
4
# In this program, we are going to test several models to see which is best for a categorical dataset. # Import libraries. import numpy as np import matplotlib.pyplot as plt #Load the dataset and split into training (75%) and test (25%) sets. from sklearn.datasets import load_digits df = load_digits() X = df.data y =...
8b9d2de6074b07cada11a254e41f178d6baa7b29
KevinGillet/pyalgo
/rendu_monnaie.py
1,800
3.640625
4
""" @name rendu_monnaie.py @version 0.0.1 Calcul de rendu de monnaie à partir d'un montant lu """ #Lecture du montant montant = 77.53 print("*************************") print("* Vous devez", montant, "€ *") somme = 200 print("* Montant donné :", somme, "€ *") #Calcul de la monnaie monnaie = somme - montant billet10...
33fa289bf90d66af8fb90cedcf7d52a4a3613baf
kphillips001/Edabit-Python-Code-Challenges
/usingternaryoperators.py
380
4.34375
4
# The ternary operator (sometimes called Conditional Expressions) in python is an alternative to the if... else... statement. # It is written in the format: # result_if_true if condition else result_if_false # Ternary operators are often more compact than multi-line if statements, and are useful for simple conditiona...
a78208e1c9c69e2e946d4c19bf8e8b78ac72490a
kphillips001/Edabit-Python-Code-Challenges
/checkstringforspaces.py
143
3.859375
4
# Create a function that returns True if a string contains any spaces. def has_spaces(txt): if ' ' in txt: return True else: return False
667062295838010bec6a75d74f43f887f06e4130
kphillips001/Edabit-Python-Code-Challenges
/sumlistlessthan100.py
169
3.8125
4
# Given a list of numbers, return True if the sum of the values in the list is less than 100; otherwise return False. def list_less_than_100(lst): return sum(lst) < 100
51f15f9102d32ed532929f3076000c2a7b9beae0
kphillips001/Edabit-Python-Code-Challenges
/checkintegerdivisiblebyfive.py
143
4.03125
4
# Create a function that returns True if an integer is evenly divisible by 5, and False otherwise. def divisible_by_five(n): return n % 5 == 0
46d591ffd8bb05e3798e5b853a632b825ccb57da
kphillips001/Edabit-Python-Code-Challenges
/convertalllistitemstostring.py
167
3.859375
4
# Create a function that takes a list of integers and strings. Convert integers to strings and return the new list. def parse_list(lst): return [str(i) for i in lst]
f592285895fefc4ab67fe157032dad0413096b42
kphillips001/Edabit-Python-Code-Challenges
/howmanydsarethere.py
198
3.90625
4
# Create a function that counts how many D's are in a sentence. # Your function must be case-insensitive. # Remember to return the result. def count_d(sentence): return sentence.lower().count('d')
8ced7006402771ea117d3531a778cfbf2bbba429
navinkrishna-tb/face-detection
/app.py
2,545
3.625
4
import streamlit as st import cv2 from PIL import Image import numpy as np import os # Loading pre-trained parameters for the cascade classifier try: face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + '...
645a10c131b2d15b68c15f95348f11e4ad21af6e
igor-si/shared
/recipies_sorted/_py/format_examples.py
8,669
3.9375
4
"Old" '%s %s' % ('one', 'two') "New" '{} {}'.format('one', 'two') # URL https://www.programiz.com/python-programming/methods/string/format # ======================================================================= print "\n Example 1: Basic formatting for default, positional and keyword arguments" # default arguments...
6a218e7b9e9e60bad4f89b68af57b7e536d1eb29
igor-si/shared
/recipies_sorted/_py/dictionaries_nested.py
5,476
4.96875
5
# URL https://www.programiz.com/python-programming/nested-dictionary # ================================================================== #In Python, a dictionary is an #unordered collection of items. For example: dictionary = {'key' : 'value', 'key_2': 'value_2'} #Here, dictionary has a key:value pair enclosed wi...
033294606257b50078682a2f6cbc4025966ffca4
igor-si/shared
/recipies_sorted/_py/functions.py
1,692
3.75
4
#Lambda-функции #Lambda-функция – это безымянная функция с произвольным #числом аргументов и вычисляющая одно выражение. #Тело такой функции не может содержать более одной инструкции (или выражения). # Данную функцию можно использовать в рамках каких-либо конвейерных #вычислений (например внутри filter(), map() и re...
d105bb3b576b58c7211c8a60e4c29238e953563a
igor-si/shared
/recipies/python/trash/classes_examples.py
316
3.8125
4
class FirstClass: # NOT THE CONSTRUCTOR ! "simple class" def say_hay(self,name="anonymous"): # Don't worry about 'self' we will come back soon print "Hi, " + name first_object = FirstClass() first_object.say_hay("python") first_object.say_hay() second_object = FirstClass() second_object.say_hay("test")
4af8b60a6149c7e6c28cc7ea83a6467dbdbc2e07
igor-si/shared
/recipies/python/strings_examples.py
193
4.0625
4
#Here we use Pyhon string formatting to replace { } with value from variable: print 'The fruits are {0}, {2}, {1}!'.format('Apple', 'Banana', 'Kiwi') >>>> The fruits are Apple, Kiwi, Banana!
36a0f49179f1135a619d1d694fa71974e0ffb71b
jbulka/CS61A
/hw2_solns.py
2,545
4.15625
4
"""Submission for 61A Homework 2. Name: Login: Collaborators: """ # Q1: Done def product(n, term): """Return the product of the first n terms in a sequence. We will assume that the sequence's first term is 1. term -- a function that takes one argument """ prod, k = 1, 1 while k <= n...
47e950a9f3a222e6bef0206727e86aba6d4a2699
Bullsquid/pythonPractice-1
/task8/task8.py
1,032
3.765625
4
import random as r def play_game(): summ = 0 for j in range(0, 4): summ += r.randint(1, 6) if summ < 9: return True else: return False def experiment(n): success = 0 for i in range(0, n): if play_game(): success += 1 p = success / float(n) ...
21a14a5c8912d514c6ae2d327e3a398eee2a281b
pconrad/MKIDPipeline
/mkidpipeline/speckle/binned_rician.py
19,392
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 21 11:24:00 2018 Author: Clint Bockstiegel Date: June 21, 2018 Last Updated: June 21, 2018 This code contains functions for analyzing photon arrival times using BINNING. For example usage, see if __name__ == "__main__": """ import numpy as np f...
f12f7780492ea8f6b48b1a47a2071ff03a5b0806
CArellG/humbio51
/helpers/central_dogma_helpers.py
2,149
3.6875
4
def reverse_complement(seq): seq=seq.upper() seq=seq[::-1] revcomp="" for char in seq: if char.upper()=="A": revcomp=revcomp+"T" elif char.upper()=="T": revcomp=revcomp+"A" elif char.upper()=="C": revcomp=revcomp+"G" elif char.upper()=...
e8982955be8a0822935a10d72d5f5d972018c91e
sadiamahfuz/LeetcodePython
/LinkedList/AddTwoNumbersLinkedList.py
788
3.890625
4
class ListNode: def __init__(self, val): self.val = val self.next = None def add_two_numbers(list_node1, list_node2): return get_integer_value(list_node1) + get_integer_value(list_node2) def get_integer_value(list_node): unit = 1 value = 0 while list_node is not None: va...
79897cfae9ea290a40a3cb4d2bf3fce7628ef371
dickynovanto1103/CP
/Online Judges/Codeforces/Gym/2007 2008 Summer Petrozavodsk Camp Japanese/j.py
1,027
3.59375
4
def gcd(a, b): if(a==0): return b else: return gcd(b%a, a) x = 0 y = 0 def gcdExtended(a, b): global x,y if(a==0): x = 0 y = 1 return b else: hasilGCD = gcdExtended(b%a, a) x1 = y - (b//a)*x y1 = x x = x1 y = y1 return hasilGCD def findSolution(a, b, c): global x,y gcd = gcdExtended(abs(...
185a54517d91df10da55d620320f3eb55c5f2fee
mkofinas/junkyard
/helpers/union_probability.py
355
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def union_prob(p, n): return 1 - (1-p) ** n def dice_union(min_roll, num_dice): prob = (7 - min_roll) / 6 return union_prob(prob, num_dice) def main(args): m = int(args[0]) n = int(args[1]) print(dice_union(m, n)) if __name__ == ...
5e4e14ca24bdbfc4504ddd89c18f43af5b7cea3e
Spintec/PythonTutorials
/Python 1-5/dictionaries.py
418
3.84375
4
#Dictionary operations dick={"Car":"Ford", "Age":21, "Sex":"Male", } #print(list(dick)) #for i in dick: # print(dick[i]) tel={'Jack':4098,'Sape':'4139'} tel['New']=4127 del tel['Sape'] tel['irv']=4127 print(sorted(tel)) print('Jack' in tel) print('jack' in tel) print('Jack' not in tel) #exista func...
34c4741a693ca40cfc04967275c99200ef10cdcd
Spintec/PythonTutorials
/Python 1-5/remember_ask_ok.py
427
3.9375
4
def ask_ok(prompt,retries=3,reminder="Please try again"): while True: ok=input(prompt) if ok in ("yes"): print("yes") break elif ok in ("no"): print("no") break retries=retries-1 if retries == 0: print("End of pro...
9120bf6aeb68bdf24bc61967052033e108e07f23
Spintec/PythonTutorials
/Python 1-5/dict_looping.py
533
3.5625
4
#items() function knights= {'Jesus':'The Saviour','Mary':"The Alleged Virgin"} for k,v in knights.items(): print(k,v) #enumerate() function seq=[('tic'),('tac'),('toe')] for i,n in enumerate(seq): print(i,n) #zip() function questions=['problem','favourite color','middle name'] answers=['You!','Black intertwi...
657bced70f217305d69ccad105b84b40e174df2f
Spintec/PythonTutorials
/Python 1-5/check_password_ok_v2.py
678
3.75
4
def check_password(name,password,retries=2,reminder="Wrong credentials, please try again..."): while True: name = input("Name please: ") password = input("Password please: ") if name in ("Hesuus", "hesuus") and password == "gogul": print("Welcome back Hesuus ") break...
4679ed8bcf1843277dc4e271b6cdf6578fe8e201
Spintec/PythonTutorials
/Python 1-5/ask_ok.py
434
3.625
4
def ask_ok(prompt, retries=2,reminder="Please try again"): while True: ok=input(prompt) if ok in ('y','ye','yes'): # print("Your answer was yes!") return True if ok in ('n','no','nop','nope'): # print("Your answer was no") return False re...
991c34fa4dee48b105d795d1f5fc65c1be45b0f5
JZavaGo/Pong
/Pong/Pong.py
2,463
3.75
4
import turtle #inicializando screen wn = turtle.Screen() wn.title("Pongo por noob") wn.bgcolor("black") wn.setup(width=800, height=600) wn.tracer(0) #Score score1 = 0 score2 = 0 #Paleta1 pA = turtle.Turtle() pA.speed(0) pA.shape("square") pA.color("white") pA.shapesize(stretch_wid=5, stretch_len=1)...
eddb8f910c7d48f96e7d6c89f8e0e355e513c66b
stefangojkovic/pong-game
/padle.py
1,070
3.8125
4
from turtle import Turtle UP = 90 DOWN = 270 MOVE_DISTANCE = 20 class Paddle(Turtle): def __init__(self): super().__init__() self.create_paddle() def create_paddle(self): self.shape("square") self.resizemode("user") self.setheading(UP) self.sha...
64afbb85cd8d3dc4fd3db95246fbd8394379c828
i300/AdventOfCode
/2017/four/part2.py
751
4.09375
4
def checkPhrases(file): infile = open(file, 'r') validPhrases = 0 for line in infile: # Remove newlines from string and split into phrase array line = line.replace("\n", "") phrases = line.split(" ") anagramList = [] # Check if phrase is valid valid = True for phrase in phrases: # Check if phra...
00e9096d691752dcbc7aa2bbeb01c4e6521c08d0
i300/AdventOfCode
/2018/seven/solution.py
2,800
3.5
4
if __name__ == "__main__": from queue import PriorityQueue events = set() dependencies = {} with open("seven/input.txt", "r") as dependencies_file: # build dependency dict and event set for dependency in dependencies_file.readlines(): event = dependency[36] depen...
3ab7fc759b77c8b89ad33b466688f079a2e89d34
emerim/intro
/lista4.py
3,363
4.1875
4
#1 cat1 = float(input("Informe o valor do primeiro cateto:")) cat2 = float(input("Informe o valor do segundo cateto:")) if cat1 <0 or cat2 <0: print("O valor tem que ser negativo") else: print(f"A hipotenusa é {(cat1**2+cat2**2)**(1/2)}") #2 val1 = float(input("Escolha um número: ")) val2 = float...
215aed3bd3d66a69c49bc841e6dc9011cc8bf156
QinmengLUAN/Daily_Python_Coding
/wk4_findNumbers.py
860
4.28125
4
""" 1295. Find Numbers with Even Number of Digits Given an array nums of integers, return how many of them contain an even number of digits. Example 1: Input: nums = [12,345,2,6,7896] Output: 2 Explanation: 12 contains 2 digits (even number of digits). 345 contains 3 digits (odd number of digits). 2 contains 1 digi...
982ab12c4fa3fe8a361f90b9ae4b204145b3107c
QinmengLUAN/Daily_Python_Coding
/wk8_Arrays101_removeDuplicates_v2.py
886
3.796875
4
""" 26. Remove Duplicates from Sorted Array Easy: Array: O(1) space, O(n) time Given a sorted array nums, 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 by modifying the input array in-place with O(1) ex...
991960f980eb27a0847f3014c635e4b2af0f5c99
QinmengLUAN/Daily_Python_Coding
/LC342_isPowerOfFour_Math.py
484
3.84375
4
""" 342. Power of Four Easy: Loop Example 1: Input: 16 Output: true Example 2: Input: 5 Output: false Follow up: Could you solve it without loops/recursion? """ class Solution: def isPowerOfFour1(self, num: int) -> bool: if (num <= 0): return False while num % 4 == 0: n...
d632ff768758195fefc983304238de01272faf05
QinmengLUAN/Daily_Python_Coding
/LC23_mergeKLists_heap.py
1,194
3.734375
4
""" 23. Merge k Sorted Lists Hard: Linked list, heapq My first Hard question. Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Example: Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6 """ # Definition for singly-linked list. # class ListNode: #...
eb2b0e4769fb061ff11ed7cbd95f4b331a4d791d
QinmengLUAN/Daily_Python_Coding
/wk10_DP_longestCommonSubsequence_LC1143.py
2,384
4
4
""" 1143. Longest Common Subsequence Medium: DP, table filling, recursion, time complexity N(MN), space complexity N(MN) Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence of a string is a new string generated from the original string with some characters(can be no...
d2300836d542397921578c8dd77637069d8dcee6
QinmengLUAN/Daily_Python_Coding
/DailyProblem62_list_cousins_Tree.py
1,898
4.03125
4
""" Hi, here's your problem today. This problem was recently asked by Amazon: Given a binary tree and a given node value, return all of the node's cousins. Two nodes are considered cousins if they are on the same level of the tree with different parents. You can assume that all nodes will have their own unique value. ...
9261b5b8c174058a10632b6cbe2a580c0a5e9cba
QinmengLUAN/Daily_Python_Coding
/DailyProblem20_maximum_product_of_three.py
651
4.375
4
""" Hi, here's your problem today. This problem was recently asked by Microsoft: You are given an array of integers. Return the largest product that can be made by multiplying any 3 integers in the array. Example: [-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128. ...
99845dad934230a83a99d4e8ac1ab96b24cd0c3f
QinmengLUAN/Daily_Python_Coding
/DailyProblem19_findKthLargest.py
653
4.125
4
""" Hi, here's your problem today. This problem was recently asked by Facebook: Given a list, find the k-th largest element in the list. Input: list = [3, 5, 2, 4, 6, 8], k = 3 Output: 5 Here is a starting point: def findKthLargest(nums, k): # Fill this in. print findKthLargest([3, 5, 2, 4, 6, 8], 3) """ import he...
5ff35f6f7a920113cec07c88e253ad06a9bdcfec
QinmengLUAN/Daily_Python_Coding
/LC354_maxEnvelopes_DP.py
2,042
4.40625
4
""" 354. Russian Doll Envelopes Hard You have a number of envelopes with widths and heights given as a pair of integers (w, h). One envelope can fit into another if and only if both the width and height of one envelope is greater than the width and height of the other envelope. What is the maximum number of envelopes...
dc33830a1d3708345a5d77f6f9dfd86017137e31
QinmengLUAN/Daily_Python_Coding
/wk2_sqrt.py
609
4.125
4
# Write a function to calculate the result (integer) of sqrt(num) # Cannot use the build-in function # Method: binary search def my_sqrt(num): left_boundary = 0 right_boundary = num if num <= 0: return False elif num < 1: return 0 elif num == 1: return num while (right_boundary - left_boundary) > 1: m...
479ffb2f52de91735be90a29d141fb53ade3ab95
QinmengLUAN/Daily_Python_Coding
/DailyProblem61_generate_skyline.py
1,244
4.0625
4
""" Hi, here's your problem today. This problem was recently asked by Facebook: Given a list of building in the form of (left, right, height), return what the skyline should look like. The skyline should be in the form of a list of (x-axis, height), where x-axis is the next point where there is a change in height s...
493d111b17682c2d73565aafb221aa525e0660db
QinmengLUAN/Daily_Python_Coding
/LC1556_thousandSeparator_String.py
710
3.5625
4
""" 1556. Thousand Separator Easy: String Given an integer n, add a dot (".") as the thousands separator and return it in string format. Example 1: Input: n = 987 Output: "987" Example 2: Input: n = 1234 Output: "1.234" Example 3: Input: n = 123456789 Output: "123.456.789" Example 4: Input: n = 0 Output: "0" "...
899135b7419531333b55adcfe42067384ba87128
QinmengLUAN/Daily_Python_Coding
/LC242_isAnagram_HashTable.py
660
3.953125
4
""" 242. Valid Anagram Easy: Hash Table, Array Given two strings s and t , write a function to determine if t is an anagram of s. Example 1: Input: s = "anagram", t = "nagaram" Output: true Example 2: Input: s = "rat", t = "car" Output: false Note: You may assume the string contains only lowercase alphabets. Follo...
9f5017921934a3eff2d4f0cdcb9c76a5a1f2495f
QinmengLUAN/Daily_Python_Coding
/LC1051_heightChecker_Array.py
1,160
4.0625
4
""" 1051. Height Checker Easy: Array Students are asked to stand in non-decreasing order of heights for an annual photo. Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height. Notice that when a group of students is selected they can reorder i...
c56694a8b21c7ef053fa330bfac3a75b6e712974
QinmengLUAN/Daily_Python_Coding
/wk1_checkNo.py
494
3.75
4
""" Check whether a number is appeared in the list """ class Solution: def checkNo(self, p, inp): length = len(p) left = 0 right = length -1 while right != left and abs(right-left) != 1: mid = (right+left)//2 # print(right, left, mid) if inp == p[mid]: return True elif inp > p[mid]: ...
7dab89ca1ef40d80b0ea0728cca5126bd021f291
QinmengLUAN/Daily_Python_Coding
/wk2_MoeList.py
1,106
4.28125
4
# To understand object and data structure # Example 1: https://www.w3schools.com/python/python_classes.asp # Example 2: https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm # write an object MyList with many methods: MyList, append, pop, print, node class MyNode: def __init__(self, value): s...
da40036d30262eb9afe7a97463dd02a9dacf62e7
QinmengLUAN/Daily_Python_Coding
/wk2_ReverseList.py
264
4.0625
4
# Reverse the list # e.g. [1,2,3] -> [3,2,1] # Use swap def ReverseList(inp): len_inp = len(inp) for i in range(len_inp // 2): temp = inp[i] inp[i] = inp[- 1 - i] inp[- 1 - i] = temp return inp # Validation inp = [1,2,3,4,5] print(ReverseList(inp))
4d09c4c6782c12470c7ad19b72fb89443acdd978
QinmengLUAN/Daily_Python_Coding
/wk11_HT_uniqueOccurrences_LC1207.py
1,056
3.953125
4
""" 1207. Unique Number of Occurrences Easy: Hash Table Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1....
fbab56bbdb85e8e2abab5578500fae52f8228d21
QinmengLUAN/Daily_Python_Coding
/LC15_threeSum_Array_2pointer.py
2,235
3.6875
4
""" 15. 3Sum Medium: Array, Binary Search Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A...
c48afae5e64ef91588c53ce962ea8c326a529d1b
QinmengLUAN/Daily_Python_Coding
/LC1189_maxNumberOfBalloons_String.py
858
4.125
4
""" 1189. Maximum Number of Balloons Easy: String, Counter, dictionary Given a string text, you want to use the characters of text to form as many instances of the word "balloon" as possible. You can use each character in text at most once. Return the maximum number of instances that can be formed. Example 1: ...
24b60cb185dcf1770906a0b042b297aa7ea0784b
QinmengLUAN/Daily_Python_Coding
/LC326_isPowerOfThree_Math.py
420
4.25
4
""" 326. Power of Three Easy: Math Given an integer, write a function to determine if it is a power of three. Example 1: Input: 27 Output: true Example 2: Input: 0 Output: false Example 3: Input: 9 Output: true Example 4: Input: 45 Output: false Follow up: Could you do it without using any loop / recursion? """ c...
3e96271de1ead6c2295979125c16fb97f239173d
QinmengLUAN/Daily_Python_Coding
/wk9_Queue_DFS_inorderTraversal_LC94.py
1,049
3.5625
4
""" 94. Binary Tree Inorder Traversal Medium: Hash table, Stack, Tree, Recursion Time complexity : O(n). The time complexity is O(n) because the recursive function is T(n) = 2⋅T(n/2)+1. Space complexity : The worst case space required is O(n), and in the average case it's O(log n)O(logn) where n is number of nodes. G...
700a056b88366df741751665db6fa00616c1b264
QinmengLUAN/Daily_Python_Coding
/LC409_longestPalindrome_String.py
723
3.921875
4
""" 409. Longest Palindrome Easy: String Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome here. Example 1: Input: s = "abccccdd" Output: 7 ...
ea27a81da0146733e81e51b59fcb87622e5f8cea
QinmengLUAN/Daily_Python_Coding
/DailyProblem04_isValid_String.py
1,649
4.21875
4
""" Hi, here's your problem today. This problem was recently asked by Uber: Leetcode 20 Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using s...
df67e407923fd4e57b6e8ea6712d2c52ddad9a1e
QinmengLUAN/Daily_Python_Coding
/LG_30Challenge_wk3_search.py
2,672
3.875
4
""" 33. Search in Rotated Sorted Array Medium: Binary Search, Array, O(log n) time complexity Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its i...