blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
1bc38bfc91f4dfcb642d0a281421889be0fb3608
brunomoita/Python_101
/PythonTestProject/src/Geometry.py
961
3.96875
4
''' Created on 4 de mar de 2019 @author: bruno ''' import turtle def draw_square(): window = turtle.Screen() window.bgcolor("green") chuck = turtle.Turtle() chuck.shape("circle") chuck.color("white") chuck.speed(1) square = 0 while square < 4: chuck.forward(1...
0641db3bd715ed0c4aca5190d149fe570276a57b
Art2Cat/LearnPython
/generator.py
417
3.90625
4
#!/usr/bin/env python3 # []包裹起来是列表解析式 L = [x * x for x in range(10)] print(L) # ()包裹起来是生成器,可以用next()方法调用 g = (x * x for x in range(10)) for n in g: print("n =", n) print("next()= ", next(g)) def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 ...
369737b248e01744df2b8a02009338741752c0b8
sapegin/sapegin.me
/assets/squirrelsong/examples/narrow/python.py
185
3.5625
4
class Squirrel: def __init__(self, name): self.name = name def greet(self): print( "Hola, %s" % self.name ) # Greet the squirrel! sqrl = Squirrel( 'Squeaky' )
5c3ca79b070e4b880f7b67ebad65b32400d1b68b
dmcdekker/interview-and-coding-problems
/easy-python-problems/longest-common-prefix/longest_common_prefix.py
1,813
3.71875
4
import unittest def longest_common_prefix_1(strs): if not strs: return '' longest = strs[0] # start at second index for string in strs[1:]: index = 0 # while not indexing out and previous chars are equal at the same indices while index < len(string) and index < len(longe...
47496ad10b3bb2ca0431b546ab118c7a054da4e4
adithyadn/Udacity-DS-Project2
/P01-LRU_Cache.py
3,157
3.671875
4
class LinkedListNode: def __init__(self, key, value): self.key = key self.value = value self.next = None class LRU_Cache(object): def __init__(self, capacity = 5): # Initialize class variables self.buckets = [None for _ in range(capacity)] self.deque = [] ...
6bda39823d8ddb95b08c1c126049a1f96a24d292
alakaz4m/GitHubRepoAssignment
/DojoAssignments/Python/fun_w_functions.py
616
4.28125
4
def odd_even(): for i in range(1,2001): if i % 2 == 0: print "Number is " + str(i) + ". This is an even number." else: print "Number is " + str(i) + ". This is an odd number." new_list = [] my_list = [1,2,3] count_list = [] def multiply(my_list, num): for i in my_list: new_list.append(i*num) return new_...
6877cb737db4c56276945343c256c1025e067649
Gonzalo-Ariel-Alonso/repositorio-gonzalo
/107898_Alonso_ej3.py
2,183
4.46875
4
#El diccionario "campeonato" tiene cargados a equipos de futbol como clave y una terna de números (lista), # cuyo significado es: partidos ganados (primer valor), partidos empatados (segundo valor), partidos perdidos (tercer valor). #Se pide que hagas un programa en Python que: # 1 -Indique si todos los equipos tie...
02affcae72c5ed634388c8225e511c05600494d4
AprajitaChhawi/365DaysOfCode.MAY
/Day 26 minimum number in a sorted rotated array.py
901
3.859375
4
#User function Template for python3 class Solution: #Function to find the minimum element in sorted and rotated array. def minNumber(self, arr,low,high): n=high-low while(low<=high): mid=(low+high)//2 if mid>0 and arr[mid]<arr[mid-1]: return arr[mid...
dd4e6437b8e297a3a8197813f6a4012e136ae114
NIDHISH99444/CodingNinjas
/CN_BasicRecursion/allIndicesOfNumbewr.py
915
4.03125
4
# Given an array of length N and an integer x, you need to find all the indexes where x is present in the input array. Save all the indexes in an array (in increasing order). # Do this recursively. Indexing in the array starts from 0. # Input Format : # Line 1 : An Integer N i.e. size of array # Line 2 : N integers whi...
b1a8dd36536b8cac01d94ed35355c118b57e6d0a
daveinnyc/various
/project_euler/005.least_common_multiple_of_sequence.py
1,185
3.796875
4
''' Problem 5 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? Since 5 is in the list the LCM has to end in 0 or 5, so only check those values. ...
62084a73fa46306eb4bd20556f6a362f2edf8834
linecoqueto/bootcamp-dio-clouddataengineer
/Introducao programacao com Python/aula11.py
733
4.21875
4
##-------------------------------------------------------------## ## EXCEÇÕES CUSTOMIZADAS COM TRY, EXCEPT, ELSE E FINALLY ##-------------------------------------------------------------## lista = [1, 10] arquivo = open('teste.txt', 'r') try: texto = arquivo.read() divisao = 10 / 1 numero = list...
a8e6d1858231e56177e1274ea510e43c9ac00664
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4444/codes/1715_3067.py
226
3.640625
4
tipo=str(input('digite o tipo de ataque: ')) dado1=int(input('digite dado1: ')) dado2=int(input('digite dado2: ')) dado3=int(input('digite dado3: ')) dado4=int(input('digite dado4: ')) if(tipo=='ESPADA'): print()
29003455b58451222ac808b2081a76cd974f05ff
joseslima/tpa-2021-1
/12190/12190.py
1,496
3.703125
4
consumptionRange = [ 100, 9900, 990000 ] prices = [2, 3, 5, 7] dp = {} def getTEnergy(price): global consumptionRange, prices tEnergy = 0 if (price in dp): return dp[price] # if (price == 0): return tEnergy # for i in range(len(consumptionRange)): tEnergy += min( max(0 , price / prices[i]), consump...
18d4a9f3b8ba5ba3c914a2ee0c4038d23747fdf0
Il-c/hy-data-analysis-with-python-2020
/part01-e06_triple_square/src/triple_square.py
389
3.671875
4
#!/usr/bin/env python3 def main(): for i in range(1,11): nelio = square(i) kolminkertainen = triple(i) if nelio>kolminkertainen: break print(f"triple({i})=={kolminkertainen} square({i})=={nelio}") def triple(parametri): return parametri*3 def square(parame...
03eda7d658cb495e2976719de18bfe4955bbd515
jz33/LeetCodeSolutions
/432 All O`one Data Structure.py
4,134
3.671875
4
''' 432. All O`one Data Structure https://leetcode.com/problems/all-oone-data-structure/ Implement a data structure supporting the following operations: Inc(Key) - Inserts a new key with value 1. Or increments an existing key by 1. Key is guaranteed to be a non-empty string. Dec(Key) - If Key's value is 1, remove it ...
755b7dc0e62b6a79e8a161c34d370c8834b7c67b
IshteharAhamad/project
/core_python/try.py
260
3.765625
4
n = int(input("Enter the string : ")) m = int(input("Enter second string : ")) try: c =n/m # raise Exception() print(c) except Exception as e: print(e) else: print("else block") finally: print("close db connection..") print("bye bye...")
e9cc92a0e6ea2465400d3bc0e9a1bdb97c285147
SharleneL/leetcode-python
/solutions/graph/0206-1319-md.py
1,731
3.8125
4
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: # create union find # for each connection in isConnected, call uf.union # return uf.setCount if len(connections) < n - 1: return -1 uf = UnionFind(n) for x, y in connect...
60ba0e478c2f267b9ef9c142bb0d9de16cee1678
sandeepkumar8713/pythonapps
/05_heap/08_compute_mean_of_window.py
6,463
3.515625
4
# https://www.geeksforgeeks.org/google-interview-experience-off-campus/ # Question : Given a stream of integers, a value k and a value w, consider the integers in # the window w and chop off greater k and smaller k elements from the window w. From the # remaining elements, compute the average. # # Question Type : Gene...
aaf801ed941de6f3a6819ce8074ce8f8b60ff612
dawtrey/ma314
/stopwatch.py
625
3.953125
4
import time # Remove the sleep function and implement your recursive Fibonacci function here: def fib_recursive(n): time.sleep(2) # pauses 2 seconds # time.time() gives a floating point number which is the time in seconds # since the start of the current "epoch" of the operating system, which # is usually...
f4c3cc8e9dbd58a72e5aa8e90b7bcffe89590ce6
TanMengyuan/For_Program
/20190920_sijie/3.py
1,893
3.671875
4
""" @version: python3.7 @author: ‘mengyuantan‘ @contact: tanmy1016@126.com @time: 2019/9/20 19:55 """ # !/bin/python3 import math import os import random import re import sys # # Complete the 'maxPathSum' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: ...
a55475fe33c5fe80d304ee293a14de98306ffc85
jadewu/kg_jadewu_2021
/main.py
678
4
4
import sys # Read arguments s1 = sys.argv[1] s2 = sys.argv[2] # The function for solving this question def one_to_one(s1, s2): # Use set in python to remove duplicated elements l1 = list(set(s1)) l2 = list(set(s2)) # If there are more or equal unique elements in s1 than in s2, correct mapping if l...
eae33935d7f56b55f37604ec3e96fce8e802004a
subash319/PythonDepth
/Practice9_Control_Structures_if/Prac9_8_Refractor.py
731
4.09375
4
# marks = input('Enter marks - ') # marks = int(marks) # # if marks >= 70: # grade = 'A' # elif marks >= 60: # grade = 'B' # elif marks >= 50: # grade = 'C' # elif marks >= 40: # grade = 'D' # else: # grade = 'E' # print(grade) # Suppose most of the students get E grade or D grade and very less stu...
2d14474cf974a469858465d187a551d1b5363778
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/chapter 7/chapter 7 Randomly Walking Turtles.py
1,822
4.53125
5
'''When we run the program we want the turtle and program to behave in the following way: The turtle begins in the center of the screen. Flip a coin. If its heads then turn to the left 90 degrees. If its tails then turn to the right 90 degrees. Take 50 steps forward. If the turtle has moved outside the...
b59d24d5616bae292356aa032b523c1933cce856
abhatkar1/Python-Program-Solving
/Ch8_02.py
919
4.5625
5
# (Check substrings) You can check whether a string is a substring of another string # by using the find method in the str class. Write your own function to implement # find. Write a program that prompts the user to enter two strings and then checks # whether the first string is a substring of the second string. def c...
8ba6051ae2c9ed8bf9648fbde354be1da9969531
sharpmark/arsenal
/drop_shadows/show.py
787
3.5625
4
import Image import os def paint(left, top, image, mask): background.paste(image, (left, top), mask) background = Image.open("wood.png"); titlebar = 78 left = 83 top = 133 size = 192 index = 0 for file in os.listdir('images/'): x1 = index % 3 x2 = x1 * 2 + 1 y1 = index / 3 y2 = y1 * 2 + 1 ...
f8eebe2674427d689d18bff334faba592f35318a
shhuan/algorithms
/leetcode/easy/Reverse_Linked_List_II.py
1,810
4
4
# -*- coding: utf-8 -*- """ created by huash06 at 2015-04-14 08:27 Reverse a linked list from position m to n. Do it in-place and in one-pass. For example: Given 1->2->3->4->5->NULL, m = 2 and n = 4, return 1->4->3->2->5->NULL. Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list. """ __au...
d08bcb213afb5d7d1efb166a49e73bdb5c21bc00
fiamma66/python-basic
/workplace1220-basic/main4.py
403
3.84375
4
namelist = ["Elwing", "Bob", "Amy", "Elwing"] # list 有順序性 可重複 print(namelist) namelist = namelist + ["Carol"] print(namelist) print(namelist[0]) print(namelist[-1]) print(namelist[1:3]) print(namelist[::-1]) # 忘記 JAVA while 用法 # for in 保證群集內所有東西都拿取一次 for a in namelist : print(" ! ",a) b = 0 for a in range(0,10) :...
475c28177f176870d1ed37242a148aa24a11564a
Bangatto/Data_Cleaning
/initial_clean.py
3,832
4.40625
4
import doctest def which_delimiter(string): """ (str)->s tr Want to return most occuring delimiter(space/comma/tab) in the input string >>> which_delimiter("0 1 2,3") ' ' >>> which_delimiter("hello") Traceback (most recent call last): AssertionError: Should have at least one d...
b7e1a8071f51a69b75dfbcb0cd334bd5dd04977d
adityanain96/Python-basic
/S3-elements.py
978
4.09375
4
""" This program deletes all matching elements from a list. [a, b, c, d, a, d, f, g]. Author: Aditya Nain Date: 01/23/2019 """ """ ********pseudocode******* define function Remove Remove takes a list as an argument initialise a new empty list run a for-loop for each elemen...
c423a0fc11d2e8f6a156603bc9bb3d498b48f045
stefano-ortona/google-kick-start
/python/y2013/roundb/dragon_maze.py
1,674
3.640625
4
def shortest_path(start, end, maze): visited = [[False for j in range(len(maze[0]))] for i in range(len(maze))] visited[start[0]][start[1]] = True to_visit = [[start[0], start[1], maze[start[0]][start[1]]]] while len(to_visit) > 0: next_nodes_size = len(to_visit) next_neighs = [] ...
2ded5316ca58199a61fb6287472a08997eef4f73
shahakshay11/DFS-1
/zero_one_matrix.py
1,675
3.609375
4
""" // Time Complexity : O(m*n) // Space Complexity : O(m*n) // Did this code successfully run on Leetcode : Yes // Any problem you faced while coding this : No // Your code here along with comments explaining your approach Algorithm explanation BFS - Initial conf - Update the 1s to inf and add the values with 0 to th...
f941252ecc30d1666d9631208ab84d6c78d54485
Ahmedhamed77/pytask1.2
/guku.py
484
3.84375
4
words = 'hello big black bug bit a big black dog hello on his big black nose '.split() counts = {} # check if the word exist more than once if yes we add it to counts for word in words: if not word in counts: counts[word] = 1 else: counts[word] += 1 print(counts, 'counts') new_counts = {} # s...
e3126e34f7a0d2dcd459bfa0dd952496e2e3801e
VIXXPARK/pythonAlgorithm
/Princeton_University/PART_1/2WEEK/QueueWithtwoStack.py
598
3.75
4
class queue: def __init__(self): self.stk1=[] self.stk2=[] def push(self,n): self.stk1.append(n) def pop(self): if len(self.stk2)!=0: return self.stk2.pop() else: while len(self.stk1): self.stk2.append(self.stk1.pop())...
595a8bee8afabf4e2af3aa4620002aec3d69dcd4
shweta2425/ML-Python
/Week4/Matplotlib/PythonMatplotlib/draw_line.py
1,120
4.46875
4
# Write a Python program to draw a line using given axis values with suitable label in the x axis , y axis and a title from matplotlib import pyplot as plt from Week4.Matplotlib.Utility.utility import UtilityClass class draw_line: def __init__(self): print() # creates utility class object utili...
0ec8ad0b230fde0734f9ffff6a68091d073ee753
Forcemay/Robot_2020
/object/buoy.py
1,582
3.671875
4
class Buoy(): def __init__(self, color, x,y): self.color=color self.x = x self.y = y self.position="%"#position in the storage self.color_storage="%" self.state="initial" self.order="%" def which_state(self) :#we can direcly apply the function but for...
e0fe6cab05e8e4dfb2603f2b8ee38f50c46c0060
zachs18/loopoversolver
/main.py
591
3.609375
4
#!/usr/bin/env python3 import loopover import time import sys line_count = input("Multiline input? (line count for yes, empty or non-int for no): ") try: s = "" for i in range(int(line_count)): s += ' ' + input() board = loopover.Board(s) except ValueError: boardstr = input("Board (space separated, newline termi...
f50dbd57aec7deaf388a37e77597ed2933f6f296
Tiinchox/python_challenges
/Challenges 31 - 35/Python Dice App/app.py
1,250
4.21875
4
import random # Functions def dice_sides(): # Select sides for dice sides = int(input("\nHow many sides would you like on your dice? ")) return sides def dice_number(): # Select number of rolls number = int(input("How many dices would you like to roll? ")) return number def roll_dice(sides,number): #...
c57d8aef10c9892bda539319f6deb47ea62bdd86
arthurtomas/Codes_git
/desafio017.py
192
3.671875
4
from math import hypot b = float(input('Digite a medida do Cateto Oposto: ')) c = float(input('Digite a medida do Cateto Adjacente: ')) a = hypot(b, c) print('A Hipotenusa vale {}'.format(a))
ceab390a47460161a90f2546eb2aaf82fabc99d9
flx18719887/PythonProgram
/文件1.py
7,644
4.125
4
读取文件: file = "C:\\Users\\Administrator\\Desktop\\hello.txt" # 定义文件路径 My_file = open(file, "r") # 打开文件,返回文件对象 strVar = My_file.read() # 读取文件全部内容 print(strVar) My_file.close() # 关闭文件 file = "C:\\Users\\Administrator\\Desktop\\hello.txt" # 定义文件路径 My_file = open(file, "r") # 打开文件,返回文件对象 line = My_file....
f726f156640a90b18cb5f67370a35bb3e52a6cfc
47AnasAhmed/LAB-05
/LAB5_PROGRAMMING EX07.py
957
4.09375
4
print("Anas Ahmed(18b-116-cs),CS-A") print('Programming Ex#7') print ('Program For Projectile Motion') import math def projectile(initialvelocity,angle): gravity = 9.8 Height = (initialvelocity**2)*((math.sin(angle))**2) / (2*gravity) TotalTime = 2*initialvelocity*math.sin(angle) / gravity Ran...
bbc81730df8dc2c9ea0128e42e9ac485783fd3f5
suminhong/PythonTest
/salary.py
613
3.78125
4
''' 직장인의 연봉을 x라 하고 연봉의 5%는 국민연금으로, 6%는 건강보험으로, 1%는 고용보험으로, 8%는 퇴직연금으로 계산될 때, 월 실수령액은 얼마가 되는지 계산하는 프로그램 작성 각 연금과 보험 금액들도 알 수 있도록 하자 ''' x = input("연봉을 적으시오 : ") x = float(x) t1 = x * 0.05 t2 = x * 0.06 t3 = x * 0.01 t4 = x * 0.08 real = x - (t1 + t2 + t3 + t4) print("실 수령액 : %.2f" %real) print("국민연금 : %.2f" %t1) pri...
da5e319c8a1d78ef8e33a67ddd98351116d3f527
mrkartikkc/snake-using-pygame
/snakepy.py
3,865
3.75
4
import pygame import time import random pygame.init() clock = pygame.time.Clock() #colors black = (0, 0, 0) red = (255, 0, 0) green = (0 ,255, 0) #size of the window display_width = 600 display_height = 600 #display with the help of size dis = pygame.display.set_mode((display_height, display_hei...
fb0b150e3fd39ba99673b51f2f963fdf8adcb13d
SerhijZhenzhera/zhzhs_python
/04 lesson/home_work_4h_Serhij_Zhenzhera.py
1,949
3.75
4
''' Задание 4. В цикле получаем число, потом действие, потом опять число и снова действие, пока не получим Q. Действия "+" или "-". Выполняем действие и выводим результат (если введет не число или не действие - игнорируем и перезапрашиваем снова) ''' import random i = 1 j = 1 while True: a = random.randi...
e09780bf2eae5a4f4c9b8287fbe93dad348caf1d
shubee17/Algorithms
/Array_Searching/del_ele.py
386
3.75
4
# Delete an element from array(Using two traversal and one traversal) import sys def del_ele(Array,k): n = len(Array) - 1 for i in range(len(Array)): if Array[i] == int(k): del(Array[i]) break elif Array[n] == int(k): del(Array[n]) break else: n -= 1 pass print Array Array = sys.argv[1] k ...
d86a3777c58c8f3f668c6b3f2598675434341a8f
ktktkat/cs50-pset
/pset7/houses/import.py
1,113
3.984375
4
from sys import argv, exit from cs50 import SQL import csv # Exit program if number of arguments incorrect if len(argv) != 2: exit("Incorrect number of arguments") # Open provided csv file and import as list of dictionaries with open(argv[1], "r") as characters: reader = csv.DictReader(characters) student...
c73bf6620cd793d7477d205f223d1176d7fde773
maratb3k/lab2
/lab2/13.py
193
3.5
4
abc = list(input().split()) def funct(): for i in range(len(abc)//2): if abc[i] != abc[len(abc)-i-1]: print("No") quit() print("Yes") funct()
c3ab61c4d0778d8470dfa9439cb31bda7d15b781
feizhihui/LeetCode
/page11/main572.py
1,362
3.9375
4
# encoding=utf-8 def create_tree(plist): n = len(plist) if n == 0: return None node_list = [TreeNode(plist[i]) for i in range(n)] for i in range(n): if 2 * i + 1 < n and plist[2 * i + 1] != None: node_list[i].left = node_list[2 * i + 1] if 2 * i + 2 < n and plist[2 ...
7a037c72e73e930d8c69894dfa639fd269caaa0a
sbro0020/sbro0020.github.io
/other/brush-dataTransform.py
625
3.578125
4
import pandas as pd def cleanData(): df = pd.read_csv("C:\\Users\\Sean\\Documents\\School\\Data Vis\\Assignment\\idk\\data.csv",dtype=str) count = 0 resp = "year,num\n" for year in range(-1700,2017): for i in range(0,len(df)): entry = df.loc[i] if int(entry['year of bir...
cbeccd57539ae74208f658e196688eec9b228f30
sonnentag/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/1-last_digit.py
309
3.984375
4
#!/usr/bin/python3 import random number = random.randint(-10000, 10000) last_digit = number % 10 if last_digit is 0: varstr = "0" elif last_digit > 5: varstr = "greater than 5" else: varstr = "less than 6 and not 0" print("Last digit of {} is {} and is {}".format(number, last_digit, varstr))
657852327eb011a079304da0f1323efa7c205de1
vakhnin/geekbrains-algorithms
/lesson08/les08task02.py
3,561
3.59375
4
# lesson 08 task 02 # # Закодируйте любую строку из трех слов по алгоритму Хаффмана. # # Итоговый словарь кодирования сильно зависит от порядка символов с одной частотностью. # Для получения словаря, как в методичке, сортировал символы по увеличению кода ASCII (строка 46) # Онлайн переводчики, для строки "beep boop bee...
cbccc4d6355957292ce5b396022308db15e7dcb6
JerinPaulS/Python-Programs
/TwoSUmIVInputisBST.py
1,407
3.71875
4
''' 653. Two Sum IV - Input is a BST Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: root = [5,3,6,2,4,null,7], k = 9 Output: true Example 2: Input: root = [5,3,6,2,4,null,7], k =...
736897b5532b86b28a19ce972afeeb7be5d625b0
lf2a/Python_Exemplos
/concurrency/multiprocessing/ex7.py
1,166
4
4
""" A classe Pool representa um conjunto de worker processes. Possui métodos que permitem que as tarefas sejam transferidas para os processos de trabalho de algumas maneiras diferentes. """ from multiprocessing import Pool import os def mult(x): return x * x if __name__ == '__main__': # inicia o worker com ...
03303f9cca39dc8d204354349078761076827362
vikas-ukani/Hacktoberfest_2021
/Python/ROT13.py
443
4.1875
4
""" ROT13 is a simple letter substitution cipher that replaces a letter with the 13th letter after it in the alphabet. """ def rot13(phrase): abc = "abcdefghijklmnopqrstuvwxyz" out_phrase = "" for char in phrase: out_phrase += abc[(abc.find(char)+13)%26] return out_phrase x = "xthexrussiansxa...
4fd30b739841f40fd577d4b53444a10aace54ed6
ayush286/AlgoExpert
/firstDuplicateValue.py
200
3.625
4
#O(n) Time | O(1) Space def firstDuplicateValue(array): # Write your code here. for elem in array: if array[abs(elem) - 1] < 0: return abs(elem) array[abs(elem) - 1] *= -1 return -1
e77bf005c7fcab6336c26d439275c382c06fd735
hexinping/PythonCode
/practice/py100lianxi/pyquestion12.py
1,264
4.0625
4
# -*- coding: UTF-8 -*- ''' 题目:判断101-200之间有多少个素数,并输出所有素数。 程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除,则表明此数不是素数,反之是素数。 ''' from math import sqrt def func1(): h = 0 leap = 1 for m in range(101, 201): k = int(sqrt(m+1)) for i in range(2, k+1): if m % i == 0: leap...
72cd7b21666bb400fa81036c525bd6795a4bdb0d
AvaniKale20/BasicOfPython
/Function.py
431
3.8125
4
def myFunction(): print "new function" myFunction() # ----------------------- print def funsum(x,y): print (x+y) funsum(1,2) # ------------------------ print def function(name): print ("name is = "+name) function("avani") # ARBITARY * ARGUMENT # ------------------------- print def functionWithArbitaryArg...
c60d0a049bc01a3591ef93b3fb199e43c94b15e8
ehallenborg/hackerrank
/DaysofCodeChallenges/10daysofStatistics/day1/standard-deviation.py
227
3.609375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) arr = list(map(int, input().split())) mean = sum(arr)/n variance = sum(((x - mean) ** 2) for x in arr) / n print(round(variance**0.5, 1))
ce9516c3f6254729ace304af18c398d210744645
hrueger/slider-tests
/slider_v1/threadtest.py
445
3.515625
4
from threading import Thread import time a = 0 #global variable def thread1(threadname): global a while True: print(a) #read variable "a" modify by thread 2 def thread2(threadname): global a while 1: a += 1 time.sleep(1) thread1 = Thread( target=thread1, args=("Thread-1",...
0bbaa615756a824ce678b06b9e8d77980db1ff19
alexmaryin/python_tests
/simple_factors.py
517
3.625
4
from math import sqrt from random import randint def get_simple_factors(value): factors = [] while value % 2 == 0: factors.append(2) value /= 2 i = 3 max_factor = round(sqrt(value)) while i <= max_factor: if value % i == 0: factors.append(int(i)) value /= i max_factor = round(sqrt(value)) i += 2...
2e6220b9e326375f9dacb0a369f313b6eb5945dc
tybens/architecture-scrape
/scrape/dexigner.py
3,547
3.53125
4
import csv from urllib.error import HTTPError, URLError from urllib.request import urlopen from bs4 import BeautifulSoup from utils import extractEmail, extractEmailNormal def scrape(urls, writing, studios_we_care_about, hunter=False): """ This scrapes the www.dexigner.com/directory type pages for studio data ...
ecb7546b18e3791825d488d7b3b5aa0a5e72894e
ssingh13-rms/Competitive-Coding-Section
/Algorithm/matrixchainmultiplication.py
1,512
3.734375
4
def matrix_product(p): length = len(p) # len(p) = number of matrices + 1 m = [[-1]*length for _ in range(length)] s = [[-1]*length for _ in range(length)] matrix_product_helper(p, 1, length - 1, m, s) return m, s def matrix_product_helper(p, start, end, m, s): if m[...
9231cce7af7d103c82e174b3afbcef6aad4a1575
shabha7092/beautiful-soup
/regression-sqlite.py
6,519
3.515625
4
import sqlite3 as sql import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns matplotlib.interactive(True) def get_conn(): sqlite_file = 'lahman2014.sqlite' conn = sql.connect(sqlite_file) return conn def problem_1(): problem1_query = 'SELECT * F...
b221a224314919119a9786b346b830bd67fcd78d
songbyeongjin/algorithm-study
/data-structure/stack_array.py
1,046
3.859375
4
class Stack: def __init__(self): self.stack = [] self.top = 0 def __str__(self): return ",".join(self.stack) def push(self, data): print(f"< push -> {data} >") self.stack.insert(len(self.stack), str(data)) self.top = self.top + 1 print(self) de...
d8bb9cb2dbd2a843eba1c18319b5c71e761ddd7b
Newton-Figueiredo/PluralsightClass
/Cap 7/bulit_in_collec_tuples.py
1,562
4.75
5
#------- tuples ---------- ''' lista imutavel de objetos arbitrarios os objetos dentro delas nao podem ser substituidos ou removidos tuples tem sintaxe parecida com a das listas exemplo: ''' t=("oi sumida",254,5.58) print(t[0]) print(t[1]) print(t[2]) print(len(t)) #podemos usa-lo no "for" for itens in t : print(i...
6f3753dd37e2bab262cfc49ff02b5ce6491c9ff8
mndarren/Code-Lib
/Python_lib/coding_challenge/rectangle.py
318
3.90625
4
from turtle import Turtle t=Turtle() t.screen.bgcolor("black") t.hideturtle() t.color("red") def slanted_rectangle(length,width,angle): t.setheading(angle) for steps in range(2): t.fd(width) t.left(90) t.fd(length) t.left(90) slanted_rectangle(length=200,angle=45,width=100)
9b9f18e05e793a790983057c02eb773a2875316a
JuanCHerreraPro/Machine-learning
/Feature engineering/Imputation.py
1,676
4.09375
4
""" Rows with missing values is a common problem. There might be many reasons why values are missing: • Inconsistent datasets • Clerical error • Privacy issues Regardless of the reason, having missing values can affect the performance of a model, and in some cases, it can bring things to a screeching halt ...
4ccb00eea4da6a2d8c3a8425a79fcfd92ee2ee73
julianfrancor/holbertonschool-higher_level_programming
/0x0B-python-input_output/7-save_to_json_file.py
558
4.375
4
#!/usr/bin/python3 """function that writes an Object to a text file, using a JSON representation """ import json def save_to_json_file(my_obj, filename): """ Args my_obj: object of any type to be converted to JSON filename: filename where the string representation is going to be writ...
ac731aecaab6014665669703057763e245bc46d2
JaneHQ1/Path-to-Python3-v2
/eight/c1.py
164
3.765625
4
""" 8-2 code """ def add(x, y): result = x + y return result def print_code(code): print(code) a = add(1,2) b = print_code('python') print(a, b)
40a776179b5c53b85b61169fbaeb35fe3576069f
Igor3550/Exercicios-de-python
/mundo3/ex100.py
779
4.125
4
# faça um programa que tenha uma lista chamada numeros[] e duas funções chamadas sorteia() e somaPar(). # A primeira funçao vai sortear 5 valores e vai colocalos dentro da lista e a segunda função vai mostrar a soma entre # todos os valores pares sorteados pela função sorteia() from time import sleep from random impor...
b0d978cd1ac5b39fd38a9200c076282152520db5
germanoso/GeekPythonBase
/Lesson5/task_5_1.py
602
3.8125
4
''' 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об окончании ввода данных свидетельствует пустая строка. ''' FILE_NAME = 'file/stask5_1.txt' with open(FILE_NAME, 'w', encoding='UTF8') as f: while True: s = input('Введите строку и нажмите ENTER. ...
6a176c7d70c03bb10f1594363221f870659e02f4
yogii1981/Fullspeedpythoneducative1
/kagglefunction2.py
1,766
4.5625
5
print(1, 2, 3, sep='<') """ greet function""" def greet(who="Colin"): print("Hello,", who) greet() greet(who="kaggle") """ multiply function""" def mult_by_five(x): return 5 * x def call(fn, arg): """call fn on arg""" return fn(arg) def square_call(fn, arg): return fn(fn(arg)) """cal...
dddeed7b04dd77ef1fdb857e792a9b26e51ce884
vathom/algorithms
/insertionsort.py
354
4.15625
4
def insertionsort(array, length): for i in range(1,length): for j in reversed(range(i)): if array[j+1] > array[j]: break if array[j+1] < array[j]: array[j+1],array[j] = array[j],array[j+1] array = [3,7,5,6,4,2,9,8,1] length = len(array) inserti...
d9330db23cfbd50bbec572c9a8264efc67447c3c
emersonmellado/oop_introduction
/basics/program_1.py
412
3.9375
4
from basics.person_3 import Person class Program: def __init__(self, name, duration): self.name = name self.duration = duration def details(self): print("Course name:", self.name, "Duration:",self.duration) n = input("Enter the program name") d = input("Enter the program duration") cou...
29a6cfe5416a7efc39e03896da8c3ce065897f8b
ryotokuro/hackerrank
/algorithms/.idea/grading.py
712
3.625
4
#!/bin/python3 import os def gradingStudents(grades): i = 0 for grade in grades: if grade > 35: rounded = grade + 5 - int(str(grade)[1]) if int(str(grade)[1]) > 5: rounded = grade + 10 - int(str(grade)[1]) # if grade(1) > 2 and grade(1) < 5 or g...
8ce83c742403d66cb6ec710599808dcdd3625c36
lcgly123/leetcode
/17. Letter Combinations of a Phone Number.py
1,128
4.09375
4
17. Letter Combinations of a Phone Number Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" O...
6a77748aef9718be9023fe1b5e592f1287a28d0c
cristiano250/pp1
/02-ControlStructures/#02-ControlStructures - zad. 34.py
348
3.515625
4
#02-ControlStructures - zad. 34 PESEL=input("Podaj swój numer PESEL: ") x=int(PESEL[:2]) rok=0 p=int(PESEL[9]) płeć="" y=int(PESEL[2]) if y==8: rok=1800+x elif y==2: rok=2000+x elif y==0: rok=1900+x if (p==0)or(p%2==0) : płeć="kobieta" else: płeć="mężczyzna" print('Wiek: ',2018-rok) print(...
e7f86b5a3a413069fd847a96adabdc34e29c81d2
thecodinghyrax/Bible_page_update
/thirdpass.py
7,167
3.640625
4
import json #Run this file third after firstpass.py and secondpass.py has been ran!!! def thirdFunc(): days_of_the_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] with open("secondpassout.json", encoding='utf-8-sig') as json_file: data = json.load(json_file) ...
c9836be3c7298fd28a3ac38f20b88bda3bf42521
RealHomoBulla/Beetroot_Academy_Homeworks
/Lesson_03/Lesson_3_Task_1.py
819
4
4
""" Task 1 String manipulation Write a Python program to get a string made of the first 2 and the last 2 chars from a given string. If the string length is less than 2, return instead of the empty string. Sample String: 'helloworld' Expected Result : 'held' Sample String: 'my' Expected Result : 'mymy' Sample Strin...
e06301611efbd47694d9f745d2e6da5a8dc42a95
andrewObrien98/DataStructures-Algorithms
/SelectionSort.py
235
3.703125
4
list = [5,6,4,7,3,7,3,5,7,1] for i in range(len(list)): for j in range(len(list) - 1): if list[j] > list[j + 1]: tempNum = list[j] list[j] = list[j + 1] list[j + 1] = tempNum print(list)
e8395105ee5b77d60cbbae87ba7bbee6c5c4e911
susmitha-8/basic-programs
/quadratic-equation.py
256
3.78125
4
#to solve quadratic equation import cmath a = float(input('a: ')) b = float(input('b: ')) c = float(input('c: ')) d = (b**2) - (4*a*c) sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('{0}{1}'.format(sol1,sol2))
559f4e4797113070f4da0f12d7cde52c98921e91
ZhaoOfficial/Introduction-to-algorithm
/Part 2/Chapter 9/min_and_max.py
727
3.828125
4
import numpy as np # find the minimum and maximum simultaneously def min_and_max(a): n = len(a) start = 1 if n % 2 == 0: minimum = min(a[0], a[1]) maximum = max(a[0], a[1]) start = 2 else: minimum = a[0] maximum = a[0] for i in range(start, n, 2): if...
9018fdeb2ba93af85e0e8ff991e6b2cd854a5b41
willstauffernorris/csbuild2
/validanagram.py
1,088
3.765625
4
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ print(s) print(t) ### what defines an anagram? #it's just the same number of letters, in a diff order ...
d18cd2e0de9d6c8797d978017d4f08b078283e58
SinnottTM/codeclan_w2_d2_testing
/bus_lab_hw/src/bus_stop.py
530
3.8125
4
class BusStop: # declare data-types name = str queue = [] # Initialise the BusStop Class def __init__(self, name): self.name = name self.queue = [] # adding ppl to the bus stop queue def add_to_queue(self, person): self.queue.append(person) # getting the lengt...
f464ab089272274c68d197106482c495a10a622a
jonasmue/daily-problem
/2020/10/01-largest-bst.py
1,384
3.796875
4
class TreeNode: def __init__(self, key): self.left = None self.right = None self.key = key def __str__(self): # preorder traversal answer = str(self.key) if self.left: answer += str(self.left) if self.right: answer += str(self.righ...
8bb9ffbbb490eab594ea5d72e2f1779a46c11bcc
anaghayn/python
/Basics/compareList.py
2,016
4
4
Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> list_one = [1,2,3] >>> list_two = [1,2,3] >>> if cmp(list_one,list_two) == 0: print "these two lists are equal" else: print "these two strings are not e...
f38192da95779dec2ce767d33a5bb7eb0ffb23b6
dalexach/holbertonschool-machine_learning
/supervised_learning/0x05-regularization/6-dropout_create_layer.py
888
3.640625
4
#!/usr/bin/env python3 """ Create a Layer with Dropout """ import tensorflow as tf def dropout_create_layer(prev, n, activation, keep_prob): """ Function that creates a layer of a NN using dropout: Arguments: - prev is a tensor containing the output of the previous layer - n is the number of no...
526403a24918bae8d7166002b6a54e79b0419459
ASHISH-KUMAR-PANDEY/python
/Look_and_say.py
444
3.734375
4
def look_and_say_term(term): ans = "" last = term[0] cnt = 1 for cur in term[1:]: if last == cur: cnt += 1 else: ans += str(cnt) + last cnt = 1 last = cur ans += str(cnt) + last return int(ans) def look_and_say(start, n): cur = sta...
0fce3dba1567705fcb80247aba750898ebce482b
kakashihatakae/Binary-Search-2
/problem_1.py
2,773
3.84375
4
# complexity O(logN) # solved on leetcode all test cases pass class solution: def __init__(self, array, target): self.array = array self.target = target def binary_search(self): if len(self.array) == 0: return [-1, -1] left = 0 right = len(self....
d0c4fd360cec1a0bff950a7d580b0f70acc53bc0
gbmikhail/pyalg
/lesson_1/task_6.py
338
4.03125
4
# 6. Пользователь вводит номер буквы в алфавите. Определить, какая это буква. n = int(input("Введите номер буквы в алфавите (a-z). Нумерация с единицы: ")) ch_pos = ord('a') + n - 1 ch = chr(ch_pos) print(f"Это буква: {ch}")
8587580b2ef0dfb64a136b4d7e965bbcc13e7e40
brianweber2/project3_work_log
/work_log.py
17,048
3.71875
4
""" Author: Brian Weber Date Created: December 5, 2016 Revision: 1.0 Title: Work Log Description: In order to prepare better timesheets for your company, you've been asked to develop a terminal application for logging what work someone did on a certain day. The script should ask for a task name, how much time was spent...
e37cf54c7d3cd525e57d14ec189506e037ca1067
spicyoil/batch-rename-modify-context-copy-files-dirs-by-rules
/change_name_script.py
1,120
3.5625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- #usage: .py target_keyword replace newword oldword #usage: .py target_keyword delete newword #usage: .py target_keyword add newword import os,sys,shutil if hasattr(__builtins__, 'raw_input'): input=raw_input def searchFile(target): os.chdir(os...
e404837c246d1b41e5f38839af1304d9c335d76f
DenisLaptev/opencv_docs
/app/src/Ch3_core_operations/lesson6_bitwise_operations.py
940
3.53125
4
import cv2 import numpy as np # Load two images PATH_TO_IMAGE1 = '../../resources/opencv_logo.png' PATH_TO_IMAGE2 = '../../resources/mainlogo.png' image1 = cv2.imread(PATH_TO_IMAGE1) image2 = cv2.imread(PATH_TO_IMAGE2) # I want to put logo on top-left corner, So I create a ROI rows, cols, channels = image2.shape roi...
50cc5ccb2ecb9a018cbff1e33efd011d8944ea10
ascrivener/SeniorResearch
/fieldSearch.py
917
3.640625
4
import itertools class Point: def __init__(self,x,y): self.x = x self.y = y def distance(self, p2): return ((self.x-p2.x)**2 + (self.y-p2.y)**2) def __hash__(self): return hash((self.x, self.y)) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __str__(self): return str(se...
8fff20dfa676a68602645b4aa0a9f0bc65000b3d
jasonflatley/musical_structure_generator
/old/harmonica_relationship_calculator (2).py
11,445
3.84375
4
""" Intro Assumptions: -Ignore enharmonic technicalities for now and just use common pitch names -View the circle of fifths mod 12 (ie, don't keep track of where we are) """ # Dictionary that maps English pitch names to the distance in half steps from the nearest lower C # Used to compute half step distances b...
4949d083a93c25efaf418dbfb7221b3955809850
linhnt31/Python
/Competitive Progamming/CodeSignal/Challenges/robotWalks.py
1,193
3.921875
4
#Time complexity: O(n*m) : n is length of a, m is the largest element of array #Space complexity: O(x): x is sum of elements def robotWalk(a): visited = [] currentX = currentY = 0 visited.append((currentX, currentY)) for key, val in enumerate(a): for _ in range(0, val): if key % 4 ...
cedd0688abb1193c85d3657d4f80dc1651c27124
sunshine5688/PythonDemo
/demo/继承.py
507
3.96875
4
class Parent: def hello(self): print('正在调用父类的方法') class Child(Parent): # 集成了Parent python 可以多集成 pass class Child2(Parent): def hello(self): print('调用child2的hello方法,覆盖了父类的hello方法') super().hello() # 调用父类方法 class Child3(Parent, Child2): super().hello() # 调用父类方法 尽量避免多继承 if _...
ce54a10e3ecc730d16543b3f7434af8e92690935
m358807551/Leetcode
/code/questions/221~230_/229_.py
1,163
3.59375
4
""" https://leetcode-cn.com/problems/majority-element-ii/ """ class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: List[int] """ major, count = -1, 0 for num in nums: if num == major: count += 1 ...
d0c3270797aa43280acf503f89243e6820dea763
natesuver/benchmarking
/mapreduce/map.py
1,768
4.03125
4
#!/usr/bin/env python import sys import re def main(): #--- get all lines from stdin --- for line in sys.stdin: #--- remove leading and trailing whitespace--- line = line.strip() #--- split the line into words --- words = line.split() #--- output tuples [word, 1] in tab-d...
55bc173611f38616ef425313b841bea1e1f3e265
RoqueFM/TIC_20_21_1
/11__Cantidad.py
413
3.84375
4
def cantidad(): p=raw_input("Inserte palabra para contar: ") n=input("Inserte nmero de caracteres de la plabara: ") l=len(str(p)) print "Tu palabra tiene", l, "caracteres." if l==n: print "La palabra tiene el mismo nmero de caracteres que el nmero insertado." else: print ...
af9de890e9d7778c72cd1ff334c52fedc81b49fa
everfear/simple_games
/dragons.py
1,171
4
4
import random import time def displayIntro(): print('''You are in dragonland! You see two caves in fron of you. One cave with good dragon, which will give you some of their treasure. Second cave with evil dragon, he will eats you as fast as you will step in his cave!.''') print() def chooseCave(...