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
482f4189285f2c1d93341c439558ad5121469b06
cyrnicolase/leetcode
/231/231.py
466
3.65625
4
# https://leetcode.com/problems/power-of-two/description/ class Solution(object): def isPowerOfTwo(self, n): """ :type n: int :rtype: bool """ items = self.powerOfTwo() if n in items: return True return False def ...
4b9a884371e57689f5c2cbe0f52434e54cbab86a
cyrnicolase/leetcode
/448/448.py
609
3.65625
4
#!/usr/bin/python # https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/description/ class Solution(object): def findDisappearedNumbers(self, nums): """ :type nums: List[int] :rtype: List[int] """ nums.sort() length = len(nums) re...
2cecec963499079fec53de8ba9476c34b96dc335
cyrnicolase/leetcode
/1189/1189.py
480
3.640625
4
import math class Solution: def maxNumberOfBalloons(self, text): chars = {"b": 1,"a": 1, "l": 2,"o": 2,"n": 1} max = math.inf for (char, count) in chars.items(): charCount = text.count(char) times = charCount // count if times < max: max =...
3c72755faaa5c4e0e3ee20d262064bfc9c4091dc
cyrnicolase/leetcode
/169/169.py
652
3.6875
4
#!/usr/bin/python class Solution(object): def majorityElement(self, nums): """ :type nums: List[int] :rtype: int """ count_values = {} for num in nums: if count_values.has_key(num): count_values[num] += 1 else: ...
f16e75835389e5a6d70b718dc092d860f17637da
RookAaron/Project-Euler
/P3 Largest prime factor.py
448
3.640625
4
''' The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? ''' def isPrime(n): for i in range(2, int(n/2)+1): if n%i == 0: return(False) return(True) factors = [71, 839, 1471] for j in range(1472, 600851475143): if 600851475143%j == 0: break ...
df13f7117fd3e73c7283afa1bb3fa647aeefac39
RookAaron/Project-Euler
/P2 Even Fibonacci numbers.py
477
3.796875
4
''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. ''' ...
921cf7dd4edb55f2ff50c3211d4432640c5c0f21
RookAaron/Project-Euler
/P6 Sum square difference.py
612
3.71875
4
''' The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Fi...
095b8b5c8cb9a59c6afaabe0c54a36cbcf83c0e4
RookAaron/Project-Euler
/P16 Power digit sum.py
226
4.0625
4
''' 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? ''' power = 1000 digits = str(2**power) summ = 0 for d in digits: summ += int(d) print(summ)
07147c4c9d5e749bd66d89e58dd285425046f364
bajpaiNikhil/SPOJ-
/SPOJ-12.py
701
3.75
4
#PIR - Pyramids from math import * t=int(input()) for t in range(t): def tetrahedrons(a,b,c,d,e,f): a1=(pow(a,2)) a2=(pow(b,2)) a3=(pow(c,2)) a4=(pow(d,2)) a5=(pow(e,2)) a6=(pow(f,2)) a = (4 * (a1 * a2 * a3) - a1 * pow((a2 + a3 - a4), 2) ...
327e629772475511c8ab871e065eb94d3f6a7a26
shanekim93/retirement33
/crawling_210427.py
639
3.5625
4
List_table = [] Champion = input("챔피온을 입력하시오") import requests from bs4 import BeautifulSoup url = 'https://lol.fandom.com/wiki/Special:RunQuery/PickBanHistory?PBH%5Bpage%5D=LCK+2021+Spring+Playoffs&PBH%5Btextonly%5D=Yes&pfRunQueryFormName=PickBanHistory' response = requests.get(url) if response.status_code == 20...
d4c1b4e64302f1f0a851ed7fa7061142b687320d
chisoftltd/PythonFilesOperations
/PythonWriteFile.py
1,443
4.375
4
# Write to an Existing File import os f = open("demofile2.txt", "a") f.write("Now the file has more content! TXT files are useful for storing information in plain text with no special formatting beyond basic fonts and font styles.") f.close() myfile = open("Tutorial2.txt", "w") myfile.write("Python Programming Tutor...
8c78a6d557e54e7356f5ca85aaf64fd4d824df6a
im57/Study_Lang
/Python/Practice3_2.py
725
3.71875
4
#실습2 score=[0,0,0,0,0] max=0 min=0 sum=0 for i in range(5): score[i] = int(input('성적을 입력하시오: ')) if i==0: max=score[i] min=score[i] else: if score[i]>max: max=score[i] elif score[i]<min: min=score[i] sum+=score[i] avg=sum/5 print() print('입력한 ...
c4577304736a94e81b6dfe6f727da2becfd7c43d
im57/Study_Lang
/Python/Practice1_2.py
266
3.8125
4
#실습2 radius=int(input('반지름을 입력하시오 : ')) print('반지름 : ', radius) pi=3.141592 area=radius*radius*pi # area = pi * pow(radius, 2) -제곱 circum=2*radius*pi print('원의 넓이 : %7.3f'% (area)) print('원의 둘레 : %.3f'% (circum))
f211d1c232e3c8308484a9647de60bc09acb7b47
im57/Study_Lang
/Python/String.py
2,098
3.953125
4
#긴 문자열에서는 엔터필요할 때 \ 입력필요 sentence = 'Pthon is the \ most popular programming \ language in these days.' print(sentence) #''' """ 은 모양 그대로 사용 가능해짐 print("""Dear Alice, Hi! How R U?? Bye~ From IM""") ''' 에러 print("Dear Alice, Hi! How R U?? Bye~ From IM") ''' #문자열 인덱싱 ''' h e l l o w o r l d 0 1 2 3 4 5 6 7 8 9...
9d83fb07fdd6b5af5ac9a5609b879bec48c489c0
TurenK/csci561-AI
/Go_Game/my_Go.py
8,324
3.625
4
from copy import deepcopy class GO: def __init__(self, n): self.board = None self.previous_board = None self.size = n self.piece_type = 1 self.died_pieces = [] self.move_num = 0 self.max_move = n * n - 1 self.KOMI = n / 2 self.whetherManual =...
0ca2b79b42f80fbaa4c5912a6d8cfdbedc3e6256
RenanTashiro/URI
/code/Matemática/p-level-2/2033.py
620
3.53125
4
/* Nome: Juros Sobre o Empréstimo ID: 2033 Resposta: Accepted Linguagem: Python 3 (Python 3.4.3) [+1s] Tempo: 0.016s Tamanho: 451 Bytes Submissao: 06/01/18 16:18:08 */ # -*- coding: utf-8 -*- ''' URI - 2033 ''' while True: try: valor = float(input()) except: break juros = float(inp...
3774cf411ce412a4a7d403e345659775ccd84f31
RenanTashiro/URI
/code/Iniciante/p-level-5/2633.py
459
3.625
4
/* Nome: Churras no Yuri ID: 2633 Resposta: Accepted Linguagem: Python 3 (Python 3.4.3) [+1s] Tempo: 0.020s Tamanho: 290 Bytes Submissao: 10/09/17 10:18:30 */ # -*- coding: utf-8 -*- while True: try: N = int(input()) except: break meat = [] for i in range(N): ...
71676a052aa2717b761d74ac030f985911bacc9b
RenanTashiro/URI
/code/Estruturas e Bibliotecas/p-level-5/2593.py
518
3.578125
4
/* Nome: Eachianos I ID: 2593 Resposta: Accepted Linguagem: Python 3 (Python 3.4.3) [+1s] Tempo: 0.016s Tamanho: 349 Bytes Submissao: 11/01/18 12:55:06 */ # -*- coding: utf-8 -*- def main(): text = input().split() n_words = int(input()) # useless words = input().split() for word in words:...
a0eff238f0fc9ad696bf3af30c6003d1974b9d1d
RenanTashiro/URI
/code/Ad-Hoc/p-level-3/1327.py
1,324
3.53125
4
/* Nome: Drop Out ID: 1327 Resposta: Accepted Linguagem: Python 3 (Python 3.4.3) [+1s] Tempo: 0.052s Tamanho: 1,13 KB Submissao: 06/03/16 08:13:57 */ # -*- coding: utf-8 -*- def lowerslist(cards, start, end): minimum, lowers = 15, [] for i in range(start, end): if cards[i] < minimum: mi...
5c16c70f4a46fcb2ec2c1fecdbc2f54ea9e23b87
RenanTashiro/URI
/code/Iniciante/p-level-1/2031.py
843
3.6875
4
/* Nome: Pedra, Papel, Ataque Aéreo ID: 2031 Resposta: Accepted Linguagem: Python 3 (Python 3.4.3) [+1s] Tempo: 0.072s Tamanho: 666 Bytes Submissao: 02/04/16 10:45:33 */ # -*- coding: utf-8 -*- """ URI - 2031 """ for caso in range(int(input())): player1 = input() player2 = input() if pla...
63fb0ab53b5be9751347aa277be1bce52e7f0bcc
beginstudy/python_newstudy
/input(lianxi).py
364
3.640625
4
kehu = input("请问你们有多少人用餐?") kehu = int(kehu) if kehu >= 8: print("我们现在没有空桌了!") else: print("欢迎!") zhengshu = input("请输入数字,让我看看这个数字能不能被10整除。") zhengshu = int(zhengshu) if zhengshu %10 == 0: print("能被10整除!") else: print("不能被10整除!")
42bd8abe464d4ef051101edb03e052c2b0fd6db7
beginstudy/python_newstudy
/even_or_odd.py
330
3.9375
4
number = input("输入一个数字,让我判定这是一个奇数还是偶数:") number = int(number) if number %2 == 0:#如果这个数字被2整除等于0,没有余数,那么... print("\n这个数字:" + str(number) + "是偶数。") else:#否则... print("\n这个数字:" + str(number) + "是奇数。")
659f4a17d0ffbdd552f4cf0b06594e9cb24887e4
Jasam2020/Python_Exercise
/CRON.py
214
3.625
4
import tkinter as tk root = tk.Tk() canvas1= tk.Canvas(root, width = 300, height = 300) canvas1.pack() label1 = tk.Label(root,text='Hello World!') canvas1.create_window(150, 150, window=label1) root.mainloop()
8c4c459aaed845e15420fe3d47a516d42452ee3a
bizbunny/HW3_ITP
/hw3.py
2,352
3.734375
4
#Collaborator: Linh Nguyen import csv ##### Problem 1 ##### #Answer def cheer(mascot): print('How do you spell winner?') print('I know, I know!') mC=mascot.upper() mCap=mascot.capitalize() for mL in list(mC): print(mL, end=' ') print('!\nAnd that\'s how you spell winner!') print('Go '+mCap+'!') ##...
951474371ab9365eb369c80da53b549239ee93f5
luciferchase/advent-of-code
/2020/python/day-06.py
1,070
3.515625
4
with open("input.txt") as input_file: _input = input_file.read().splitlines() # Add EOF newline _input.append("") # Format input groups = [] temp_group = [] for i in _input: if (i == ""): groups.append(temp_group) temp_group = [] else: te...
91b06210d811c8fa150aad3ba27ca95850ae8b2f
rmacapobre/LeMur
/main.py
1,536
3.703125
4
import random import subprocess def HowManySoldiers(): ok = False while not ok: try: # How many soldiers? answer = input("How many soldiers? ") count = int(answer) ok = True return count except ValueError: print("Please ent...
ea4ec6286039c177db9b7ef2bbf62e7ea3453a2a
alfonsbano/alfonsbano.github.io
/main.py
970
4.09375
4
import turtle import math screen = turtle.Screen() screen.title('Squares Circle - PythonTurtle.Academy') screen.setworldcoordinates(-1000,-1000,1000,1000) turtle.speed(0) turtle.hideturtle() def draw_square(x,y,length,direction,color): turtle.up() turtle.goto(x-length/(2**0.5)*math.cos(math.radians(direction+4...
b46a6bce71aa7260cba881616d33d2d0720e7a62
Brechard/TVA
/src/Main.py
6,159
3.53125
4
from random import sample from Model import Model from voting_scheme_option import VotingSchemeOption def get_random_preferences(): preferences = {} for voter in range(int(n_voters)): preferences[voter] = sample(candidates, len(candidates)) return preferences def ask_for_preferences(): prefe...
d300886988517359a3d872464e43c778c2abd252
nshutijonathan/python_exercises
/python_exercices/samples.py
173
3.8125
4
a=int(input("enter first range you want")) b=int(input("enter second range you want")) for m in range(a,b): if all(m%n!=0 for n in range(2,m)): print(m)
12965a730bfaa49d293ecaa2c42b9a005d79cb49
richapatil/Array
/Spiral_Order_Matrix_I.py
1,179
3.671875
4
# T = [[1,2,3], [4,5,6], [7,8,9]] # len(T) = 3 #len(T[0]) = 3 i.e 1,2,3 def spiralOrder(self, A): q = [] #list to store answer row = 0 #Top col = 0 #left n = len(A) - 1 #bottom #"2" m = len(A[0] - 1) #right #A[0] as each time one list #"2" dir = 0 #direction initialize to 0 # if dir =...
4412cabe34259f9f7e41fadfa7cd77769274dd3d
vineethk96/F2018-HW2
/P2/Problem2.py
3,512
3.8125
4
#Problem 2 ECE 4984 #!/usr/bin/python3 import argparse def minimum(edges, neighbors, i): sortedList = [neighbors[0]] minimum = neighbors[0]["wij"] for newVertex in neighbors: if minimum > newVertex["wij"]: sortedList.insert(0, neighbors) return sortedList[0] def dijkstra(edges, start, end, n): cost...
937fd7ed313414abdcf79356bd51f06a2571f0e2
EvelynMC/intro-python
/intro-python/controlFlujo.py
1,101
4.40625
4
# ----IF Control de Flujo----- # if 2 < 5: # print('2 es menor que 5') # a == b # a < b # a > b # a != b # a <= b # a >= b # if 2 == 2: # print('2 es igual a 2') # if 2 ==3: # print('2 es igual a 3') # if 2 > 5: # print('2 es mayor que 5') # if 5 > 2: # print('5 es mayor a 2') # if 2 != 2: # ...
81980248ad55408dee8bb4b3d2603a74143d8bc4
backtrunck/learning_python3
/forward_reverse.py
1,778
3.703125
4
#!/usr/bin/env python # Foundations of Python Network Programming - Chapter 4 - forward_reverse.py # Checking whether a hostname works both forward and backward. import socket, sys if len(sys.argv) != 2: print( 'usage: forward_reverse.py <hostname>',file=sys.stderr) sys.exit(2) hostname = sys.argv[1] ...
270c6ebf2a07c7c4f4116a41740b694c092332b8
backtrunck/learning_python3
/jornada_trabalho.py
6,480
3.921875
4
#coding=utf-8 import datetime def obter_horario(mensagem): """ Obtem, do terminal, um horario no formato hora:minuto. Ex. 15:30 ################################################################## parametros: - mensagem (string), mensagem a ser mostrada no terminal solicitando o horá...
1ae53542003ca4d3815e8dc361f1668ba950b087
paolocaraos/Coding-problems
/paintFill.py
2,797
3.90625
4
#-------------------------------------------------------------------------------- # Problem: # # Implement the "paint fill" function that one might see on many image editing programs. # That is, given a screen (represented by a two-dimensional array of colors), a point, and a new color, # fill in the surr...
e076f8b1f62651d5908d1fab22230bb533c0e3c6
kikihiter/LeetCode
/Contest/iNo878.py
448
3.625
4
#必然的超时超界,没来得及想后续 class Solution(object): def nthMagicalNumber(self, N, A, B): """ :type N: int :type A: int :type B: int :rtype: int """ i,k = 1,0 while k < N and i <10**9+8: if i%A == 0 or i%B == 0: k += 1 a...
28d8e4e2cb3c284af3d964d5f44b1d7f074e1e03
kikihiter/LeetCode
/iNo107.py
993
3.75
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 levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ...
10aa1cd421da8e9c821f15281f1b3bdca4fe32d4
xs2pranjal/data_structures
/linear/linkedlist.py
1,701
4.4375
4
class LinkedList(object): """ This is an implementation of a LinkedList in python. """ def __init__(self): self.head = None def print_ll(self, node=None): if not node: node = self.head print(node.value) # Calling the print_ll recursively if nod...
c1191b2e81dbfc3ec35da47356a324b46196ae50
divprnc/python_programs
/list.py
557
3.71875
4
if __name__ == '__main__': lst = list() N = int(input()) for i in range(N): a,*b = input().split() if a == "print": print(lst) elif a=="reverse": lst.reverse() elif a == "append": lst.append(int(b[0])) elif a =="sort": ...
256e5b0b37db2d7810eaeb438215af23146db7f2
divprnc/python_programs
/DoorMat.py
871
3.953125
4
# if __name__ == '__main__': s = input() # The any() method returns True if any element of an iterable is True. If # not, any() returns False. print(any(i.isalnum() for i in s)) print(any(i.isalpha() for i in s)) print(any(i.isdigit() for i in s)) print(any(i.islower() for i in s)) print(any(i.isupper() for i ...
d632d4643926624cc3a4ff0fb09b7e1703ac19a9
AndrewEveld/python-word-cross
/Scrabble.py
6,345
4.125
4
############################## # CSC 150 Fall 2018 # Andrew Eveld # Project 2 ############################## from typing import * from random import randint from Word_Board import WordBoard # Prompt user for a difficulty and return their choice def choose_size() -> int: print('Choose the size of the board:') ...
7aacc6d64efd12afaaa3d11c37b71c6b4c532ecf
wizeline/AI-DataScience-cc
/Complete/utility.py
3,827
4.03125
4
import matplotlib.pyplot as plt import numpy as np def normalize(array): """ Rescale images values to 0 to 1 """ min_ = np.min(array) max_ = np.max(array) return (array - min_)/(max_ - min_) def hot_encode(N, array): """ For each element in the array tranlate a number category into a ...
9fecaeb375a231c3a1703209a9050113931b3670
ravijha334/Python
/triple.py
371
3.578125
4
def triple(n): if(n==2): return 1 if(n==3): return 3 s=triple(n-1) c=0 for i in range (1,n): if(n%i==0): c+=1 else: a=n%i if(i%a==0): c+=1 return (s+c) t=int(input()) while t: n=i...
b01e11ca62c190af069345e0387c53b3c8c77c92
SergioGomez1/Final-Project
/leastSquares.py
929
3.6875
4
def leastSquares(vectorX, vectorY): """Compute the least squares of the 2 vectors. Import the basicFunctions file for the subalgorithms that are being used in this process. We first need to construct the degree 4 vandermond matrix with the inputed VectorX. After we have that matrix, we are going to construct Matri...
a62bd25f73728deda1f00122b370b4c26d0dfe45
pavi-ninjaac/HackerRank
/Python_challege/list_methods.py
742
3.6875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 12 20:58:38 2020 @author: ninjaac """ if __name__=='__main__': t=int(input()) result=[] for _ in range(t): a=list(input().split()) if a[0]=='insert': result.insert(int(a[1]),int(a[2])) elif a[0]=='print'...
b7d5e9f75bca687f7451c5d154787feef6fdc9c4
pavi-ninjaac/HackerRank
/Python_challege/set_update_diffrerence_intersection.py
1,690
3.828125
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 23 14:49:05 2020 @author: ninjaac """ ################################################################################### #set intersection function n= input() A = set(input().split()) b = input() B = set(input().split()) print(len(A.intersection(B))) pri...
9aa1b3db08b5767cee5bc91786c90fe80d00d9fb
tilaboy/xml-miner
/xml_miner/xml/base_xml.py
1,447
3.78125
4
"""XML class: render xml file or xml strings to xml tree object""" import xml.etree.ElementTree as ET class XML: ''' XML: general xml class, xml tree object can be generated from - xml file - xml string ''' def __init__(self, top_level_obj=None): self.top_level_obj = t...
a2dd47edaaf963cbfe2ef4cb4adad7120c92c85d
krikit/teach_your_kids_to_code
/daniel/2020.01.19/홀로로로로로 인성질 임x호 바보 colin foolish men.py
331
3.6875
4
# dongdong.py import turtle t = turtle.Pen() turtle.bgcolor("black") t.speed(0) sides = 7 colors = ["red", "blue", "purple", "gold", "pink", "orange", "green" , "brown" , "yellow" , "white"] for x in range(200): t.pencolor(colors[x % sides]) t.forward(x * 3 / sides + x) t.left(360/sides + 90) t.width(x*...
b9982f9c2d83aa4ccf1f7f4270c45ed0292766c3
krikit/teach_your_kids_to_code
/colin/2020.01.28/colin giant.py
415
3.8125
4
# dongdong.py import turtle t = turtle.Pen() turtle.bgcolor("black") t.speed(0) colors = ["red", "yellow", "green", "blue", "red", "blue", "red", "blue"] your_name = turtle.textinput("Enter your name", "What is your name?") for x in range(100): t.pencolor( colors[ x % 4] ) t.penup() t.forward( x * 4 ) t...
2c7eb8eb870e1ff11aa906a934b0c83ada31bdd1
tanya217/Python-Framework
/user.py
136
3.6875
4
print("hello world") a=2 b=3 c=a+b if(2): pass if(3) pass while(2) pass if(3)): pass wile(3): pass print("Goodbye")
f87d9f225270d321c7cdb2cdf16c65aec5f03171
qianlv/learning
/python/python-cookbook-2nd/chapter4/building_a_dict_from_a_list_of_alternating_keys_and_values.py
589
3.75
4
#!/usr/bin/python #encoding=utf-8 # 使用列表中的元素交替作为键值和对应值创建一个字典 def dictFromList(keysAndValues): return dict(zip(keysAndValues[0::2], keysAndValues[1::2])) # 适用于可迭代对象 def pairwise(iterable): itnext = iter(iterable).next while True: yield itnext(), itnext() # 效率比较低 def pairwise_slow(iterable): it...
3819898a677cc8da8f5d68de0e144a1e7774f31e
qianlv/learning
/python/python-cookbook-2nd/chapter2/reading_from_a_file.py
1,591
3.875
4
#!/usr/bin/python #encoding=utf-8 import os # 在不确定文本用什么换行符, 'rU' 指定通用换行符, 这样无论什么平台下的各种 # 换行符都被映射成'\n' file_object = open("thefile.txt", 'rU') # 不要把 open 的调用放入到 try/finally 语句的 try 子句中 # 因为如果在打开文件的时候就发生错误,那就没什么东西需要关闭, # 没有什么东西绑定上去 try: all_the_text = file_object.read() file_object.seek(0, os.SEEK_SET) # ...
0301541977bc29e6dfb4d88a7edf3fd6f83e31aa
qianlv/learning
/python/python-cookbook-2nd/chapter4/creating_lists_of_lists_without_sharing_references.py
1,054
3.953125
4
#!/usr/bin/python #encoding=utf-8 # 在无须共享引用的条件下创建列表的列表 # 避免隐式的引用共享 multi = [ [0] * 5 ] * 3 print multi multi[0][0] = 'oops' print multi # [ [ 'oops', 0, 0, 0, 0 ],[ 'oops', 0, 0, 0, 0],[ 'oops', 0, 0, 0, 0 ] ] # 等价方式 row = [0] * 5 # row 列表中的5个子项都是引用0 multi = row * 3 # multi 列表中的3个子项都是引用row # 解释: 在row创建中, 有无引用被复制完全...
a794f5e954f89aa64500c6e212ab566e4ea41f68
qianlv/learning
/leetcode/find_the_duplicate_number.py
528
3.609375
4
# encoding=utf-8 class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ low = 1 high = len(nums) - 1 while low <= high: mid = low + (high - low) / 2 lte_sum = sum(x <= mid for x in nums) ...
2ac3948d001f717b92f4e1ac7435b13add3b4548
qianlv/learning
/python/python-cookbook-2nd/chapter4/extracting_a_subset_of_a_dictionary.py
1,287
4.03125
4
#!/usr/bin/python #encoding=utf-8 # 获取字典子集 def sub_dict(somedict, somekeys, default = None): return dict((key, somedict.get(key, default)) for key in somekeys) # 获取字典子集且删除原字典 def sub_dict_remove(somedict, somekeys, default = None): return dict((key, somedict.pop(key, default)) for key in somekeys) # 如果键值不存在抛...
73540697a45b312292306166b6504be2be7cd4ad
qianlv/learning
/python/python-cookbook-2nd/chapter1/simplifying_usage_of_strings_translate_method.py
733
3.609375
4
#/usr/bin/python #encoding=utf-8 import string # 封装translate # delete 和 keep 尽量不要同时指定 def translator(frm='', to='', delete='', keep=None): if len(to) == 1: to = to * len(frm) table = string.maketrans(frm, to) # 当 keep 被指定设置 delete 为除去keep为的所有字符, # 如果delete也指定, delete优先 if keep is not None:...
8c2035389bee962cd81c58f710e21d5f5e15d5cd
artorious/simple_scripts_tdd
/test_longer_string.py
998
4.15625
4
#!/usr/bin/env python3 """ Tests for longer_string.py """ import unittest from longer_string import longer_string class TestLongerString(unittest.TestCase): """ Test cases for longer_string() """ def test_invalid_input(self): """ Tests both arguments are strings """ self.assertRaises( ...
1f384325237061f0fc42bcbed23ca2d76007a1d7
JUANPER-GITHUB/Taller-Clase-13-de-Abril
/Clase_13_abril_funcionesbuscadas.py
264
3.65625
4
# FUNCION POW print(pow(38, -1, mod=97)) # Se calcula la inversa de 38 modulo 97 print(23 * 38 % 97 == 1) # Se comprueba que el resultado es correcto # FUNCION ROUND print(round(10.89655)) # Se redondea el numero # FUNCION BIN print(bin(50))
4447e31fe2820d52184acb7c00a65b0e8c516369
JessBrunker/euler
/euler10/euler10.py
416
3.796875
4
#!/usr/bin/python3 ''' Find the sum of all primes below two million. ''' import math upper_limit = 2000000 primes = [2] total = 2 for i in range(3, upper_limit, 2): is_prime = True for prime in primes: if prime > math.sqrt(i): break if i % prime == 0: is_prime = Fals...
d92409344ec18cfc85e3203d3f05e11b737784b3
JessBrunker/euler
/euler06/euler6.py
289
3.90625
4
#!/usr/bin/python3 ''' Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. ''' sum_of_squares = 0 sums = 0 for i in range(1, 101): sum_of_squares += i**2 sums += i sums = sums**2 print(sums - sum_of_squares)
e4a9b2f2f3c847ea444f2380217eca63adf7ffd3
JessBrunker/euler
/euler23/euler23.py
2,576
4.125
4
#!/usr/bin/python3 ''' A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1+2+4+7+14=28, which means 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and...
8ffa90066929fb6ada2524fedba217edd785c2e4
jorge-jauregui/guess-the-number-game
/guess the number.py
587
4.125
4
print("Welcome to Jorge's 'guess the number' game!") print("I have in mind a number between 1 and 100. Can you guess what it is?") import random random.randrange(1, 101) number_guess = random.randrange(1, 101) chances = 0 while chances < 100000: user_guess = int(input("Type your guess: ")) if user_guess == n...
44b46d01f8dc9128cc2adb1b097c93c845943103
surajang/py-drill
/scratch.py
797
3.625
4
# -*- coding: UTF-8 -*- # Just for test & memo... Nothing related to actual project. def fib(n): """print a Fibonacci series""" a, b = 0, 1 while a < n: print a, a, b = b, a + b # class bcolors: # """testing color formatting""" # PURPLE = '\033[95m' # BLUE = '\033[94m' # GR...
2c989d8e0b8fbbc1dcb612172aa4352fdbd84814
solafishes/ants
/InitWorld.py
1,433
3.671875
4
#The function initialize a directed network for ants. import numpy as np import networkx as nx import matplotlib.pyplot as plt def InitWorld(length=10,height=10,scale=1): G=nx.DiGraph() pos={} for x in range(int(length/scale)): for y in range(int(height/scale)): G.add_node((x,y)) #G[(x,y)]['pos']=(x,y) p...
15ed63c134548fe242353b0f5460e93fcc1ca1a6
DaiJitao/py365_tf2_2
/src/multi_task/mmoe_code_3/hub-recsys/Classic/CollaborativeFiltering/UserBasedCF.py
3,123
3.59375
4
import pandas as pd from math import sqrt import numpy as np """ user-based CF 关注点,必须要使用用户都有评价的数据 基本步骤如下所示: 基于物品计算用户相似度 取与用户相似度最高的五个用户的物品进行推荐 """ def cosine_sim(x, y, norm=False): """ 计算两个向量x和y的余弦相似度 :param x: 向量x :param y: 向量y :param norm: 是否进行归一化 :return: """ assert len(x) == len(y)...
8dbefa73236a567099e3f59b619f5de6df7ff4e8
vallenov/RoadGraphs
/main.py
14,975
3.59375
4
# python C:\Prog\Python\NIR\P\Road_Graphs-0.6.py import os import random import math from tkinter import * import numpy as np import time # Размеры окна HEIGHT = 500 WIDTH = 1000 root = Tk() # Инициализация окна root.title("Road Graph") # Название окна mainmenu = Menu(root) root.config(menu=mainmenu) c = Canvas(ro...
0af99efc80c1a242a2695a7dcac3bfcdd8da30a3
jokojeke/Python
/week3/test005.py
633
3.84375
4
print("\t เลือกเมนูเพื่อทำรายการ") print("#"*50) print("\t กด 1 เลือกเหมาจ่าย") print("\t กด 2 เลือกจ่ายเพิ่ม") c = int(input("")) km = int(input(" Enter your distance : \n")) if c == 1: if km <=25 : print("จ่ายทั้งหมด 25 บาท") elif km > 25 : print("จ่ายทั้งหมด 55 บาท") if c == 2: if km <= 2...
6ceb85208048a5c0b1311b7ea2209685a5a48503
jokojeke/Python
/test004.py
1,843
3.875
4
print("\tโปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์") print("-"*50) print("\tรถยนต์ 4 ล้อ กด 1") print("\tรถยนต์ 6 ล้อ กด 2") print("\tรถยนต์มากกว่า 6 ล้อ กด 3") car1list =["ลาดกระบัง-->บางบ่อ:25 บาท","ลาดกระบัง-->บางประกง:30 บาท","ลาดกระบัง-->พัสนิคม:45 บาท","ลาดกระบัง-->บ้านบึง:55 บาท","ลาดกระบัง-->บางพระ:60 บาท"] car2list =[...
cb58f4a9eead8bd0a0700eade3dfa22645196427
shirleyxting/leetcode
/quoraOA/maxArithLen.py
2,816
3.734375
4
__author__ = ' Zhen Wang' from typing import List class Solution: def checkDiff(self, diff: int, a: List[int]): for num in a: if (num - a[0]) % diff != 0: return False return True def countMaxArithLen(self, a: List[int], b: List[int]): """ find the...
301514def4ff401ab559c34fc946f26568a58ed6
SpecialScene2/BOJ
/Python/Judge_1003.py
505
3.671875
4
# judge_1003 final = [0,0] def fibonacci(element): if element == 0: return [1, 0] elif element == 1: return [0, 1] elif 0<=element<=40: # if len(element) a, b = 1, 0 c, d = 0, 1 for i in range(element): a, b = b, a+b c, d = d, c+d ...
063ba054f997a4126403bbedb247688656fd807d
SpecialScene2/BOJ
/Python/2751_sort2.py
931
3.703125
4
# N = int(input()) # # container = [] # for i in range(N): # element = int(input()) # container.append(element) # # result = [] # for j in range(N): # Min = container[j] # for k in range(j+1, N): # if Min > container[k]: # Min, container[k] = container[k], Min # container[j] = Mi...
5289398156ac28b120441ed9158c132411d511da
bennettokotcha/python_start
/hello_world.py
1,503
4.53125
5
# print ('Hello World') # print ('new language means creating new pathwyas in my brain...alot of learning!!') # x = 'Hello Python' # print (x) # y = 42 # print (y) # print (x, y) # print('this is a sample string') # name = '`Bennett` the Don!' # print('My name is ' + name) # first_name = "Bennett" # last_name = "Okotch...
6f451d5b835cc29b8fe8ec2fefbc7e137fcf2d8f
world137/ML
/lenear_regression_scatter.py
735
3.515625
4
# y = ax + b # x = ตัวแปรอิสระ # y = ตัวแปรตาม # a = ความชัน # b = ระยะตัดแกน y import numpy as np import matplotlib.pyplot as plt ran = np.random a = ran.rand(50)*10 b = ran.rand(50)*10 # rand(x) ==> สุ่มเลขมา x ตัว โดยเป็นจำนวนบวก x = ran.randn(50)*10 # randn(x) ==> สุ่มเลขมา x ตัว โดยเป็นจำนวนลบ y = a*x + b plt.sca...
0cebb192e67cc41b29b313e1de3261b8f703666e
AidanStack/Leetcode.com_Problems
/Deci-Binary Numbers.py
740
4
4
# A decimal number is called deci - binary if each of its digits is either 0 or 1 without any leading zeros.For example, # 101 and 1100 are deci - binary, while 112 and 3001 are not. # # Given a string n that represents a positive decimal integer, return the number of positive deci - binary numbers neede # so that the...
acb966bebc46c66e4a6d7c046797b248de7a5865
xiebohust/python_study
/learn/函数/wk_13_列表排序.py
355
3.71875
4
name_list = ["zhangsan", "lisi", "wangwu"] name_num = [1, 5, 4, 12, 3] # 升序 name_list.sort() name_num.sort() print(name_list) print(name_num) # 降序 name_list.sort(reverse=True) name_num.sort(reverse=True) print(name_list) print(name_num) # 逆序(反转) name_list.reverse() name_num.reverse() print(name_lis...
3de034b38ec84d72c935ca34057c1a3484dd1de8
xiebohust/python_study
/learn/字典/wk_16_for循环.py
142
4
4
items = [1, 2, 3] for item in items: print(item) if item == 2: break else: print("123") print("循环结束")
aa7f52b1ffebebe3693bae11c8a06a129903f80a
xiebohust/python_study
/learn/语法基础/wk_05_苹果升级.py
214
4.03125
4
# 价格 price_str = input("香蕉的价格: ") # 重量 weight_str = input("香蕉的重量: ") # 转换成浮点数 price = float(price_str) weight = float(weight_str) # 总价 print(price*weight)
b028d08157c02a5702474df5e01a85f5a3e1ecd7
xiebohust/python_study
/learn/py2.py
444
3.71875
4
# coding:utf-8 try: # 尝试执行的代码 num = int(raw_input('输入一个整数:')) result = 2/num except ValueError: print '输入了非整数' except Exception as msg: print msg try: # 尝试执行的代码 except 错位类型1: # 捕获异常时执行的代码 except Exception as msg: # 捕获未知错误 else: # 没有异常时的代码 finally: # 无论有没有异常都执行
41e9169c4d879ca12e913f906f61b3506aea2e63
miladyousefi/python-course
/2/main_1.py
164
4.0625
4
sum_of_nums=1 n=int(input("Enter value for n :")) x=int(input("Enter value for x :")) for i in range(1,n+1): sum_of_nums=sum_of_nums + x**i/i print(sum_of_nums)
316688cfd723a90690b103add5d1b582ca75bbf9
akshay-1993/Python-HackerRank
/Staircase.py
574
4.40625
4
# Problem # Consider a staircase of size : n = 4 # # # # ## # ### # #### # Observe that its base and height are both equal to n, and the image is drawn using # symbols and spaces. The last line is not preceded by any spaces. # # Write a program that prints a staircase of size n. #!/bin/python3 im...
98252ac6f14ab113df87184bef2102f7f71bc93a
YannMjl/Coding-Interview-Problems
/hash_table.py
2,017
4.09375
4
# Dictionary in python are also refered to as hash table in other languages like java # initialize a dictionary a_dict = {'FirstName': 'Yann', 'LastName': 'Mulonda', 'age': 177, 'year': 2018} print(a_dict) # retrive value from a key print("We are in the year: ", a_dict['year']) # add a new key and value a_dict['city...
7f66c79430347b8f040c6491e625bdf697e9f1a9
audreyolafz/gwc
/11042020.py
2,394
3.9375
4
favorite_word = "compassionate" print(favorite_word) favorite_fruit = "blackberry" print(favorite_fruit[0]) print(favorite_fruit[3:8]) first_name = "Rodrigo" last_name = "Villanueva" # new_account = last_name[:5] def account_generator(first_name, last_name): return first_name[:3] + last_name[:3] ...
7daccffa3a9bfb0ece4c147d18d9155af18e9ff7
zhi-sh/leet-code
/records/116.填充每个节点的下一个右侧节点指针.py
1,024
3.78125
4
# # @lc app=leetcode.cn id=116 lang=python3 # # [116] 填充每个节点的下一个右侧节点指针 # # @lc code=start """ # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right sel...
83338738da87bdcc5cd4ef0522b5eb70c913046a
yokohamaH/deeplerninglen
/test.py
462
4.21875
4
def accumulate_list(iterable): current = 0 lst = [] for element in iterable: current += element lst.append(current) return lst def accumulate_generator(iterable): current = 0 for element in iterable: current += element yield current # ジェネレータイテレータ gen = accumul...
272470f47bd4c525369e615ea3b8346e2d525488
yoheiMune/Python-LectureNote
/day2/common.py
984
4.3125
4
# # 共通処理 - Python Lecture Day2 # import numpy as np import matplotlib.pyplot as plt def load_data(): """線形回帰に利用するデータを読み込みます""" X = np.loadtxt("./automobile.txt", delimiter=",") return X.tolist(), X[:,0].tolist(), X[:,1].tolist() def show(data, x_vals=None, y_vals=None, Theta=None, hypothesis_func=None): ...
71c162e23b67fe6d054954919028ac3abaadbd90
sergwert/lesson1
/answers.py
641
3.8125
4
# question=input("Введите Ваше приветствие ") # answers={"HI": "И тебе Привет!", "доброе утро": "Здрасьте", # "hi": "И тебе Привет!"} answers={} def set_answer(): q=input("Введите приветствие в словарь: ") a=input("Введите ответ бота в словарь: ") answers[q]=a def get_answer(question, answers): prin...
621e7056d4dccb90268c0c4142984cbe88c4566d
shailey-chawla/Sandbox1
/oddname.py
184
4.21875
4
"""Input a name and print alternate characters""" name=input("enter name") #error check for name to be blank while len(name)<1: name=input("Enter longer names>> ") print(name[::2])
3d6a7d2f07548edde3a95a163f647bb010ca9028
santhiagosdp/MatematicaDiscreta-operacoes-algebra_conjuntos
/algoritmos.py
3,385
3.640625
4
#METODOS PARA SEREM USADOS NO MENU #INSERIR NO VETOR SE NÃO EXISTIR def insere(A,a): for item in A: if(item == a): return A #Se exisitir, retorna A sem add A.append(a) #se n entrar no If, add a e retorna A return A #FIM-INSERE #UNIÃO def uniao(A,B): u = [] for item in A: u=insere(u,item) #c...
482ef17dc638670edcad67dabcce3002dd1af375
odonfrancisco/Learn-New-Stuff
/python/learn-the-hard-way/ex18-names_variables_functions.py
513
3.84375
4
# this one is like your scripts with argv def print_two(*args): arg1, arg2 = args print "arg1: %r, arg2, %r" % (arg1, arg2) # but apparents up top is pointless. we can do this insntead def print_two_again(arg1, arg2): print"arg1: %r, arg2: %r" % (arg1, arg2) # This only takes one argument def print_one(ar...
cbd794bec7ff53238f8741711903da31a9b6c342
Ankitkumar7/Smart-Home-With-Integrated-Security-Features-And-Support-For-Deaf-and-Elderly-People
/Module 1 (Vibrating Band)/repositories/Python/dateTime.py
600
3.9375
4
from time import gmtime, strftime def dateFormat(): #getting time and date and storing in current_time current_time = strftime("%a, %d %b %Y %H:%M:%S", gmtime()) #converting time into lists lists = current_time.split() date = lists[:-2] getDate = ' '.join(date) return getDate def ...
f593fcc6565e2802a21999e8b0e8a55dc66cb8e1
lizhen-tbc/PythonProgramming
/5-numbers2text.py
339
3.953125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 15:47:36 2019 @author: Zhen.Li """ def main(): instring = input("please enter the unicode-encoded message: ") message = "" for numstr in instring.split(): codeNum = int(numstr) message = message + chr(codeNum) print(m...
04d2439992ff86e17854bd0ef878407dc92dae98
lizhen-tbc/PythonProgramming
/6-happy2.py
372
3.5
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 15 15:40:09 2019 @author: Zhen.Li """ def happy(): return "Happy Birthday to you !\n" def verseFor(person): lyrics = happy() * 2 + "Happy birthday, dear " + person + ".\n" + happy() return lyrics def main(): for person in ["Fred", "Lucy", "Elmer"]: ...
ab1fd6b462cedede9f84df78802c954c639eec6a
lizhen-tbc/PythonProgramming
/8-average4.py
435
3.65625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 27 11:01:26 2019 @author: Zhen.Li """ def main(): total = 0.0 count = 0 xStr = input("Enter a number (negative to quit) >> ") while xStr != "": x = float(xStr) total = total + x count = count + 1 xStr = input...
7b0167f032954ea2e2da1bb62c9e5e0a85e8f236
asya20/homeworks
/строки15.py
91
3.875
4
str1=input() str2=str1[::-1] if 'eno' in str2: print ('yes') else: print('no')
348d10c3c66c5521d2c2ee033c3c8a68115fc246
asya20/homeworks
/условия10.py
215
3.90625
4
a = int (input()) b = int (input()) c = int (input()) if a>b>c: print(a) elif a>c>b: print (a) if b>a>c: print (b) elif b>c>a: print (b) if c>a>b: print(c) elif c>b>a: print (c)
36d0406ea682acc2c1847191849ac889a75d75c9
dagamargit/absg_exercises
/04_changing_the_line_spacing_of_a_text_file.py
1,063
4.125
4
#!/usr/bin/python # Write a script that reads each line of a target file, then writes the line back to stdout, #+but with an extra blank line following. This has the effect of double-spacing the file. # # Include all necessary code to check whether the script gets the necessary command-line argument (a filename), #+and...
3dbe33fc272a732cf33aa776d85730fec29ff22d
shivirajput008/mycaptask1
/task1.py
181
4
4
# mycaptask1 Developed by Shivangi radius=1.1 print("input the radius of the circle=",radius) pi=3.141569 area=pi*radius*radius print("The area of circle with radius 1.1 is:",area)
e50a6236b2a0743ce5b3655c1f44f218a6baa499
serdardoruk/Bloomberg-Common-DS-Algo-Python-Solutions
/levelOrderTraversal.py
442
3.578125
4
''' ''' def levelOrder(root): if not root: return queue = [root] levels = [] while queue: newQueue = [] level = [] for node in queue: level.append(node.val) if node.left: newQueue.append(node.left) if node....
2696998c4c7091a376d668ac44aa2ad5a24285d8
serdardoruk/Bloomberg-Common-DS-Algo-Python-Solutions
/subwaySystem.py
1,647
3.875
4
''' Implement the class UndergroundSystem that supports three methods: 1. checkIn(int id, string stationName, int t) A customer with id card equal to id, gets in the station stationName at time t. A customer can only be checked into one place at a time. 2. checkOut(int id, string stationName, int t) A customer with ...
8b1d94ce6116fb5cdda6379b6980bffbad59d2ce
serdardoruk/Bloomberg-Common-DS-Algo-Python-Solutions
/killProcess.py
1,553
3.890625
4
''' Kill Process Medium 455 11 Add to List Share Given n processes, each process has a unique PID (process id) and its PPID (parent process id). Each process only has one parent process, but may have one or more children processes. This is just like a tree structure. Only one process has PPID that is 0, which mean...