blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
76c14c8ca786ac0f40738da70f939b975403f197
p-singh/CTCI
/1-Arrays-Strings/1_1_isUnique.py
227
3.8125
4
def is_unique(s: str): char_set= set() for c in s: if c in char_set: return False else: char_set.add(c) return True if __name__ == "__main__": print(is_unique("ab22s"))
ce01964b645a71b25c2b332b742abbc725b6a579
LuciaIng/TIC_20_21
/ejercicio19.py
414
3.59375
4
'''Escriba una funcin que reciba una cadena de caracteres que represente una fecha (formato 04 de Febrero de 2009) y devuelva un nmero que represente el mes (en el ejemplo anterior devolvera un 2).''' def ejercicio_19(): from datetime import datetime str = '9 de 15 de 18' date_object = datetime...
064f091b537c6f49d3a7951497a2c995fb71287e
ashwini91098/Space-Invaders
/game4.py
4,496
3.609375
4
import math import turtle import os import random #setup screen wn=turtle.Screen() wn.bgcolor("black") wn.title("space invaders") wn.bgpic("bg.png") wn.setup(width=650,height=650) #register shapes turtle.register_shape("invader.gif") turtle.register_shape("player.gif") #draw border border_pen=turtle.Turtle() border_p...
0fb39e0fef3b1769dfe6f353f4b0aa8709522210
lwd19861127/LeetCde-TopInterviewQuestions-Easy
/IntroToAlgorithms/Wenda_bonus.py
1,054
4.21875
4
""" Bonus Question """ def gcd(n1, n2): while n2 != 0: n1, n2 = n2, n1 % n2 return n1 def gcd_of_strings(str1: str, str2: str): """ For strings S and T, we say "T divides S" if and only if S = T + ... + T (T concatenated with itself 1 or more times) return the largest string that di...
4b1b58af6260b22b444df310c5462a9ffe0eecb7
idan1ezer/LeetCode
/26 - Remove Duplicates from Sorted Array.py
344
3.71875
4
def removeDuplicates(nums): if (not nums): return 0 curIndex = 0 for i in range(1, len(nums)): if (nums[i] != nums[curIndex]): curIndex += 1 nums[curIndex] = nums[i] return curIndex + 1,nums print(removeDuplicates(nums = [1,1,2])) print(removeDuplicates(nums =...
7137a4ca710acb1e42f1df61d19807f9620dc80c
vadimsavenkov/Miscelaneous
/untitled7.py
933
3.765625
4
class BankAccount: def __init__(self): self.name = name self.no = 0 self.balance = initial_amount def withdraw(self, amount): self.balance -= amount return self._balance def deposit(self, amount): self.balance += amount return...
59b5945f6e638b8d8ecd48db8486d3d85f5a8e51
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/5d80afb6ecc04de294ea702d65bb54b7.py
205
3.625
4
def difference(i): return square_of_sum(i) - sum_of_squares(i) def square_of_sum(i): return sum(xrange(1, i + 1))**2 def sum_of_squares(i): return sum(i**2 for i in xrange(1, i + 1))
ed994b7f564c63c6ad75e88bcdf5dd07e23a3542
Aftabkhan2055/Python
/fsum.py
163
3.578125
4
def test(n,m): c=n+m print(c) #------------------------------------------------- p=int(input("enter the no")) q=int(input("entr the no")) test(p,q)
8849e4a0e1616c76fb3b2d66eca5493edabba4dd
Jacquesvdberg92/SoloLearn-Python-3-Tutorial
/09. Pythonicness and Packaging/01. The Zen of Python/The Zen of Python/The Zen of Python/The_Zen_of_Python.py
2,321
3.734375
4
# The Zen of Python # Writing programs that actually do what they are supposed to do is just one component of being a good Python programmer. # It's also important to write clean code that is easily understood, even weeks after you've written it. # One way of doing this is to follow the Zen of Python, a somewhat tong...
99b92f0ca990ebfab634c7eb863ad94df067a8c9
PedroPK/PythonAlura
/AluraInvest/date.py
345
3.984375
4
class Date : def __init__( self, day, month, year ) : self.day = day self.month = month self.year = year def format(self) : date = "{:02}/{:02}/{:04}".format(self.day, self.month, self.year) return date d = Date(13, 6,...
0c78953d452de1b922a7fe5fb41c8891efc0faf1
johndurde14/Python_Learn
/10.4.1.py
885
3.609375
4
#coding = utf-8 import json class ReadAndWrite(): def __init__(self, numbers): self.numbers = numbers self.fileName = "D:\\1etrip系统\\tmp.txt" self.msg = "Successfully!" def number_write(self): try: with open(self.fileName, 'w') as file: ...
cba28bdd66b754c0935d5b6ea3ab3c6e124081b9
wafindotca/pythonToys
/leetcode/ugly_number.py
1,170
4.1875
4
# https://leetcode.com/problems/ugly-number/ # Write a program to check whether a given number is an ugly number. # # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7. # # Note that 1 is typically tre...
7289db0d72680d8238ca1d1f9207e3327cb3d0b4
SparshJohri/Kepler_Data_Analysis
/Put_final_data_in_csv.py
3,034
3.640625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 8 22:37:18 2019 @author: bhata """ import pandas campaign_2_targets = pandas.read_csv("Campaign_2_EPICS.csv") #gets all of the Campaign 2 targets campaign_2_targets.set_index(campaign_2_targets .columns[0], inplace=True, drop = True) #sets up the EPIC ID as the index o...
d83663b762c21f9e232d886eac460cc8163b52cf
benlands/isat252
/lec6.py
613
3.90625
4
""" lec 6 """ demo_str = "this is my string" #for str_item in demo_str: # print(str_item) #for word_item in demo_str.split(): # print(word_item) #print(word_item.title()) #for str_item in word_item: # print(str_item) #if word_item != "my": #print(word_item) for each_num in...
9d39514fd61d814b54efad20b4ba89512d9b5d35
mowangdk/worthtowrite
/two_sum.py
903
3.5
4
import bisect class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ # if numbers is not None or target is not None: # return -1 total_size = len(numbers) for i in ra...
23e026a4f1183e127d0760f69fd24c0d204355c4
masmedia/mips
/rearrange.py
663
3.859375
4
#!/usr/bin/env python def rearranger(): #a_string = raw_input("Enter a string:") #for indices in range(1,2): file1 = open("mips.src","r") file2 = open("mips2.src", "w") newLine = '\n' for filerange in file1: a_string = filerange arran = a_string.strip() ...
528d45afc72300c10950e39c987891f041089fe2
alexfaley/pythonhardway
/exercise6/step1.py
452
3.609375
4
x = "There are %d types of people ."%10 binary = "binary" do_not = "don't" y = "These who know %s and those %s" % (binary, do_not) print x print y print "I said : %r" % x print "I also said : '%r'" % y hilarious = False joke_evalution = "Isn't that joke so funny?! %s" print joke_evalution % hilarious ...
6b5c9ec6f8ac072e3486db1b84f4ad3c213b4010
MEng-Alejandro-Nieto/Python-3-Udemy-Course
/16. list comprehensions in python.py
253
4.34375
4
name="alejandro" mylist=[] for letter in name: mylist.append(letter) print(mylist) print("") # we can rewrite the same above as below mylist2= [letter for letter in name] print(mylist2) print("") mylist3=[num for num in range(5)] print(mylist3)
fd48c75d58487692ab73a05511e5cc1cd402e72c
xuyonghui6512/My_notes
/Python简单练习/条件判断.py
278
3.953125
4
a=[1,3,5,7,9,11,13] if(2 in a): print("DAGE") if(3 in a): print("dage") if(2 not in a): a.insert(1,2) print(a) age1=[1,15,18,19,25,13,5,7] for age in age1: if(age>18): print("you are too old") elif(10<age<19): print("you are so young") else: print("you are a baby")
ca39abc56f8000b4ac85564db9f60b8a37b6c93b
QuentinDuval/PythonExperiments
/dp/EditDistance_Hard.py
1,107
3.890625
4
""" https://leetcode.com/problems/edit-distance Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2. You have the following 3 operations permitted on a word: * Insert a character * Delete a character * Replace a character """ from functools import lru_cache cl...
43fe197667c87c7d1a9a6d166196c8e748e876c8
neal-o-r/questions
/only_unique.py
602
4
4
# find the only unique element in an array # in a sorted array def unique_sorted(arr): x = arr[0] for i, a in enumerate(arr[1:]): if x != a and a != arr[i + 1]: return a x = a return x # given that everything else appears twice def find_double(arr): x = arr[0] for a ...
a85f464f6f75e0e824e6385a7c69ca6831b90cff
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_199/335.py
631
3.609375
4
def all_happy(pancakes): return all(pancake == '+' for pancake in pancakes) n = int(raw_input()) for i in range(n): tmp = raw_input().split() pancakes = list(tmp[0]) k = int(tmp[1]) nflip = 0 for j in range(0, len(pancakes) - k + 1): if pancakes[j] == '+': continue ...
6cc8b07138b418809e923d0820f98111ed3ea1f2
rAndrewNichol/oldrepo
/Python/monty_hall/monty_hall.py
619
3.640625
4
#monty_hall.py import random def gen_doors(): doors = [0,1,2] car = random.randrange(3) doors[car] = "Car" goats = list(range(3)) del goats[car] for i in goats: doors[i] = "Goat" return doors def random_play(doors = ["Goat","Car","Goat"], switch = True): goats = [...
a9eeb2522af895dee72f78b10a8539b502799dba
SalvatoreRaia/Salvorra
/scratch_3.py
2,004
3.65625
4
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.animation as animation import pandas as pd ''' # First set up the figure, the axis, and the plot element we want to animate fig, ax = plt.subplots(ncols=1, nrows=1) ax = plt.axes(projection='3d') line...
c4b7e00e39aa92fbe99bfe5d2d620b24999f9e88
Dearyyyyy/TCG
/data/3922/AC_py/508734.py
147
3.609375
4
# coding=utf-8 while True: a,b=input().split() a=int(a) b=int(b) if b==0: print("error") else: m=a/b+0.5 m=int(m) print(m)
4a191e882e1216ddf78667e322289a103dd5ca49
huangchen1996/Python_Base
/PythonBase/IfAndOr/If_Nest_03.py
291
3.703125
4
ticket = 1 knife = 9 if ticket == 1: print("你可以进入车栈") if knife > 8: print("不好意思,您携带的工具太过于危险,不能上车") else: print("祝您旅途愉快") else: print("不好意思,您缺少相关物件不能进入车站")
ee423771b495161e5671e232ae8dccc9f743ee72
wilcokuyper/cs50
/pset6/credit.py
1,752
4.21875
4
def sumOfDigits(number): sum = 0 length = len(number) val = int(number) # creditcard is only valid if it contains 13, 15 or 16 digits if length == 13 or length == 15 or length == 16: # calculate the sum of the digits by adding the individual numbers to each other, every other number should a...
8eeb5596b794f70153512fb051f34c72a97fae53
chinacharlie/demo
/f.py
168
3.71875
4
import functools @functools.lru_cache(maxsize=100) def fibonacci(n): if n < 2: return n return fibonacci(n-2) + fibonacci(n-1) print(fibonacci(40))
6c994564ba68112d97d5b3f81be3e256947f4d79
pknipp/permutations
/tennis.py
2,164
3.5625
4
import math from itertools import permutations dx1 = 27 dx2 = 36 dy1 = 36 dy2 = 78 ## Python code for finding the least-distance travel-path when sweeping the lines on one side of a Hartru court. ## This is a modified traveling-salesman problem. Below are descriptions of the lines. All positions are ## e...
97888b17bc6aad0e4344567aaa4188827ebe795e
newtonsart/wordlistgenerator
/wordlistgenerator
1,426
4.21875
4
#!/usr/bin/env python3 from itertools import product import string, sys def generate_characters(): characters = [char for char in string.printable.replace("\t\n\r\x0b\x0c","")] return characters if __name__ == '__main__': try: min_characters = int(sys.argv[1]) max_...
19fd7e1061cf3119f8b921d59ab172b9b113119e
PetosPy/hackbulgaria_python
/week06/game_of_frogs_tree.py
2,929
3.71875
4
FROG_DIRECTION = {'>': 1, '<': -1} class TreeNode: def __init__(self, value: tuple, parent: 'TreeNode'=None): self.value = value self.parent = parent # self.children = children def number_of_frogs(count: int): root_value = tuple(['>'] * count + ['_'] + ['<'] * count) expected_val...
f9b275c8403497898992c8bcdde4c71199a5b929
mollinaca/ac
/code/practice/abc/abc056/c.py
151
3.8125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- x = int(input()) i = 0 while True: if i*(i+1)//2 >= x: print (i) exit () i += 1
6a6356af7e9e47f48a161594c6a8dcada8219577
kathirvelgounder/SharkSpotting
/metadata/extract_metadata.py
2,635
3.546875
4
#we are going to be provided a .srt file, as well an interval #range that sharks are found in the video. Extract the other #pertinent information that is present at that time class DroneInfo(): """ Stores information logged into a given entry of the SRT file created in the drones flight. Contains useful ...
f02999e1fcb8a6a37d3151929eee0ef350334b71
bielevan/a_sintatico
/table.py
2,950
3.890625
4
# Representa a tabela de simbolos ja definidos pela linguagem inicialmente # Possui uma estrutura de dados em tabela hash, onde as colisões são resolvidas # Implementando uma lista para cada posição. Assim, se houver dois elementos # para a mesma posição, então eles estaram inseridos em formato de lista na # mesma pos...
577797a27b6cda56a60ee5f9cce039bdb94d25c6
beboptank/the-self-taught-programmer-challenges
/ch6.py
2,459
4.375
4
# print every character in the string "Camus" lets_print = "Camus" print ( lets_print[0], lets_print[1], lets_print[2], lets_print[3], lets_print[4] ) # write a program that collects two strings from a user, inserts them into the string "Yesterday I wrote a [response_one]. # I sent it to [respons...
815b522a7834747c8186b8e419e0722fc8612777
minseunghwang/algorithm
/TEST/TOSS/Server delveloper - 2.py
303
3.609375
4
user_input = input() def solution(user_input): lotto = user_input.split() if len(set(lotto)) != 6: return False if int(lotto[0]) < 1 or int(lotto[-1]) > 45: return False if sorted(lotto) != lotto: return False return True print(solution(user_input))
131f45f30ce56f3b34f458292af1b2e97e8827f2
HeywoodKing/mytest
/MyPractice/class_domain.py
889
3.859375
4
# Filename:class_domain.py class Person: population = 0 def __init__(self,name): self.name = name print("(Initializing %s)" % self.name) Person.population += 1 def __del__(self): print("%s says bye." % self.name) Person.population -= 1 if...
f55816c447fd808580c896ab68e564487fa33c53
twymer/project-euler
/python/p17.py
969
3.515625
4
onesPlaceDict = { 0: "", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" } teensDict = { 0: "ten", 1: "eleven", 2: "twelve", 3: "thirteen", 4: "fourteen", 5: "fifteen", 6: "sixteen", 7: "seventeen", 8: "eighteen", 9: "nineteen" } tensPlaceDict = { ...
e48f030e8dde581675b9bcde6e98e9074a922047
infixsrf/Trash
/programmer.py
3,565
3.890625
4
import people class Programmer(People): # кол-во языков программирования _i_language_prog = 0 # опыт работы _i_experience = 0 # скил прокраммировани в % _i_progr = 0 # пропишим getter's и setter's def set_langauge_prog(self, n): # запрос на кол-во языков которые вы знаете x = 0 n = int(n) while(x == ...
551b2ac66bf7ef1986e311353af32bb1b5c88fab
rhkaz/Udacity_IntroComputerScience
/Lesson_3_Problems/greatest2.py
502
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 20 10:06:58 2016 @author: RashidKazmi """ # Define a procedure, greatest, # that takes as input a list # of positive numbers, and # returns the greatest number # in that list. If the input # list is empty, the output # should be 0. def greatest(lis...
d89b92a5c3b300c2d5e9168484d0242ee097b21f
gloomyline/ML
/python/demos/2048/screen.py
1,216
3.609375
4
# -*- coding: utf-8 -*- # @Author: Administrator # @Date: 2018-05-18 13:37:45 # @Last Modified by: Administrator # @Last Modified time: 2018-05-18 16:26:00 class Screen(object): help_string1 = '(W)up (S)down (A)left (D)right' help_string2 = ' (R)Restart (Q)Exit' over_string = ' GAME OVER' win...
cc7db316caafe3cf5e2d0d7d66ba41dc7e5e24d4
rhian-bottura/ExCursoGuanabara
/ex052.py
306
3.59375
4
s = 0 n = int(input('Digte um numero:')) for c in range(1,n+1): if n % c == 0: print('\033[34m', end='') s += 1 else: print('\033[m', end='') print('{}'.format(c), end='') if s == 2: print(' \n \033[mPrimo') else: print(' \n \033[mNão é primo')
fbc79e8174fc13a75c696c899d52735dd6b68d6e
enmyj/cryptopals
/set1/uno.py
549
3.609375
4
import codecs from binascii import unhexlify from base64 import b64encode def hex_to_b64(h: str) -> str: return codecs.encode(codecs.decode(hex, 'hex'), 'base64').decode() # https://www.reddit.com/r/learnpython/comments/2vj4o5/cryptography_bytes_vs_encoded_strings/ def hb64(h: str) -> str: return b64encode(...
940c9cd56b5d3b04a404149b13391dab785920fc
xumaxie/pycharm_file-1
/Algorithma and Data Structures/python数据结构与算法分析/第二章/demo01(前n数之和).py
207
3.8125
4
#@Time : 2021/10/3110:48 #@Author : xujian #计算前前n个数的和 def sum(n): sum_num=n*(n+1)/2 return sum_num if __name__=="__main__": n=int(input("请输入数字")) print(sum(n))
ef9cd811318072f8235c8a5c58f0867d5f520133
arnet95/Project-Euler
/Python/euler125.py
1,051
4.0625
4
#Project Euler 125: Palindromic sums def sum_of_squares(n, m): """Returns the sum of i**2 for n <= i < m""" return ((2*(m-1)**3 + 3*(m-1)**2 + (m-1)) - (2*(n-1)**3+3*(n-1)**2+(n-1))) // 6 def is_palindrome(n): return str(n) == str(n)[::-1] def max_num(N): """Returns the n such that any sum of > n con...
7c782ec40a308029eea80944492a68717a8a53ba
younkyounghwan/python_class
/lab3_1.py
2,301
4.28125
4
""" 쳅터: day3 데이터형 연습 주제: 데이터형 연습 작성자: 윤경환 작성일: 18.09 04 """ f = 3.4 #f의 데이터타입은 float 왜냐하면, 3.4가 실수이기 떄문이다 print(f) i = 3 #i의 데이터타입은 int. 왜냐하면, i에 정수인 3이 저장되었으므로 print(i) b = True #b는 boolean type. 왜냐하면, b에 true가 저장되었으므로.(boolean type은 true 또는 false를 저장한다 print(b) s="안녕하세요" #s는 문자열 str 문자열은 " "로 묶는다. 또는 ''로 묶는다. print...
9862a682811ff5eef3b19e4723b6607d9adc6727
kashikakhatri08/Python_Poc
/python_poc/python_strings_program/string_execute_code.py
260
3.6875
4
def exec_method(): string_container = """ def sum(a,b): print("first number: {} , second number: {}".format(a,b)) c= a +b print("sum of first and second number : {}".format(c)) sum(1,2) """ exec(string_container) exec_method()
791570978e8bcf8b2e36bd64aaaeaab0e6fabd54
Kalpavrikshika/python_modules
/list1.py
233
3.5
4
#list squared = [x**2 for x in range(10)] print(squared) #dict mcase = {'a': 10, 'b': 34, 'A':7, 'Z':3} mcase_frequency = { k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys() } print(mcase)
0ec3fb8af7eb622ee322169e99c201faf770a4fd
Mr-alan9693/cursoemvideopython
/venv/Qual é o maior e o menor.py
277
3.984375
4
A = int(input('Digite o primeiro numero: ')) B = int(input('Digite o segundo numero: ')) C = int(input('Digite o terceiro numero: ')) if A>B and A>C: maior = A if B>C and B>A: maior = B if C>A and C>B: maior = C print('O maior valor digitado foi {}'.format(maior))
a9e5df68ae94c64c2aafa0aa21a1751d70786798
ksarthak4ever/Competitive-Programming
/Algorithms/Search/Find First Duplicate Entry/find.py
841
3.921875
4
""" Write a function that takes an array of sorted integers and a key and returns the index of the first occurrence of that key from the array. Example: idx 0 1 2 3 4 5 6 7 8 9 A = [-14, -10, 2, 108, 108, 243, 285, 285, 285, 401] target = 108 Returns index 3 since 108 appears ...
38278c93d68206abb5d4c5356593504de29044e0
RishabhGoswami/Algo.py
/Delete n node from end list.py
1,070
3.703125
4
class Node: def __init__(self,data): self.data=data self.next=None class Linke: def __init__(self): self.head=None def push(self,data): newp=Node(data) newp.next=self.head self.head=newp def printl(self): temp=self.head ...
cc3fbf43ccd352586452f2dac5dffac8c3f9cd2b
anand-prashar/python-code-practice
/005_Longest_Palindrome.py
1,253
4.03125
4
''' Given a string s, find the longest palindromic substring in s. Input: "babad" Output: "bab" Note: "aba" is also a valid answer. ''' def longestPalindrome(s): """ :type s: str :rtype: str """ lowLimit = 0 highLimit = len(s) palindrome = '' for index in range(0,highLimit):...
03ead92cbf2457d60b0d6a7cefc2f51c58f091c9
Yennutiebat/Noeties_repo
/TICT-VIPROG-15/Les07/Practice files/7.1.py
180
3.53125
4
invoer=1 totaal=0 som=0 while invoer !=0: invoer=eval(input('geef een getal: ')) totaal+=1 som=som+invoer print('er zijn',totaal,'getallen ingevoerd, de som is: ',som)
c26992815978d34b56390776266e11d80a172d45
wangluolin/Algorithm-Everyday
/tree/98-Validate_Binary_Search_Tree.py
1,456
3.84375
4
""" https://leetcode-cn.com/problems/validate-binary-search-tree/ 98. 验证合法的二叉搜索树 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None """ 方法一:中序遍历的方式 1. 注意题目,节点间严格大于小于,所以在排序时要转换为set进行判断 2. 列表之间可用+来连接 """ class Solut...
e3985929a8e53c42fc524dafb21635987aacfd0a
HanYouyang/GameSoftware
/project/Algorithm/t1/8+9链表/9.3.py
529
3.890625
4
def mergeTwoLists(l1, l2): dum = cur = Node(0) while l1 and l2: if l1.value < l2.value: cur.next = l1 l1 = l1.next else: cur.next = l2 l2 = l2.next cur = cur.next cur.next = l1 or l2 return dum.next def mergeTwoLists2(l1, l2): i...
7882a508587a172706a1dbfa55dffd225d0a1206
beidou9313/deeptest
/第一期/深圳--NLJY/生成器.py
306
3.5625
4
l = [x * x for x in range(10)] # 这是一个列表 g = (x * x for x in range(10)) # 这是一个生成器 # g.next() 通过g.next() 来调用生成器 for n in g: print(n) def fib(max): n = 0 a = 0 b = 1 while n<max: print(b) a,b = b,a+b n= n+1 print(fib(6))
ad4e7ee49c517608e23d73e126cb8a04e777fd9b
yuhao600/project-euler
/src/012. Highly divisible triangular number/012.py
401
3.609375
4
def num_of_factors(num): n = 0 factor = 1 while factor * factor < num: if num % factor == 0: n += 1 factor += 1 if factor * factor > num: return n * 2 else: # perfect square return n * 2 + 1 triangle = 0 i = 1 while True: triangle += i if ...
eb4b2ca5d2bfc4f491fb9a17f30c74ff75ce41c7
jkpr/advent-of-code-2020
/advent/day2/__init__.py
906
3.65625
4
from collections import Counter import re from typing import List def part1(lines: List[str]): count = 0 for line in lines: found = re.search(r"(\d+)-(\d+) (\w): (\w+)", line) if found: start, stop, letter, password = found.groups() counter = Counter(password) ...
c4d96ec8677f2d7960c7d968dfe35a5661780e3a
hoyeongkwak/workspace
/python/pythonProject/day2_2/pythonPart/pEx15.py
236
3.6875
4
for i in range(10): try: result = 10/i except ZeroDivisionError: print('숫자는 0으로 나눌 수 없습니다') else: print('result:',result) finally: print('한 번 연산 종료')
56bff1e63496eb77623feae2dd1ab46dd6ea5a86
AkshayManchanda/Machine_Learning_with_Python_Training
/day1/123.py
946
4.46875
4
"""tuple = ('rahul',100,60.4,'deepak') tuple1 = ('sanjay',10) print(tuple) #print tuple print(tuple[2:]) #0,1,2 wale se end tak (slice operator) print(tuple1[0]) #0th index wala print(tuple+tuple1) #concatenate tuples a=10; b=10; print(type(a)) print(id(a)) #...
69adf4ce95be93ac97cd7b6ba5f32d4be533455b
tumugip/chibi
/parser.py
1,009
3.734375
4
from exp import Val,Add,Mul,Sub,Div ''' def parse(s: str): num = int(s) return Val(num) #e = parse("123") #print(e) #s = "123+234" #pos = s.find('+')  #記号を探す #print('pos',pos) #s1=s[0:pos] #s2=s[pos+1:] #print(s,s1,s2) #+記号で分割 ''' def parse(s:str): if s.find('+') >0: ...
b69978209334f59c2823c45f4a787a952f1de06f
dblarons/Choose-Your-Own-Python
/spaceadventure.py
8,334
3.9375
4
from sys import exit def chapter_three(): print "\nCHAPTER THREE: FRENEMIES\n" print "You ask the group what is going on." print "Shocked, they ask you if you remember anything." name = raw_input("They say that your name is ") print "The ship you are on is called the ENDEAVOR and you were recently ...
e04e3566aa851acaa56ef5a5e29eac4b603af493
rahuladream/LeetCode
/April_LeetCode/Week_1/Queue/sorting_queue.py
391
3.578125
4
import queue q = queue.Queue() q.put(14) q.put(27) q.put(11) q.put(4) q.put(1) # using bubble sort algorithm n = q.qsize() for i in range(n): x = q.get() for j in range(n-1): y = q.get() if x > y: q.put(y) else: q.put(x) x = y q.put(x)...
50b2ed2fe7e3218c4e23b5f6b9a388a9c0788826
nahaza/pythonTraining
/ua/univer/HW02/ch04AlgTrain08.py
287
4.59375
5
# 8. Write code that prompts the user to enter a positive nonzero number and validates # the input. num = int(input("Enter a positive nonzero number: ")) while num <= 0: print("Warning: it is not a positive nonzero number") num = int(input("Enter a positive nonzero number: "))
88697500560cc5bf479e7a4801f6f19e4adf3f08
UMComp4140ATeam/Raymond
/src/simple_error_distribution.py
983
3.859375
4
#!/bin/python import math import random MIN_ODD_MODULUS = 0 ''' A simple error distribution class. That returns a small error relative to the odd modulus. This is a temporary class that will be used until we have time to look into making a better error distribution. ''' class SimpleErrorDistribution(object): def ...
123b4d63062b675e4615d7d70184f9a4e05e9e4c
TiagoRodriguesskt/Aprendendo-Python
/adivinhação.py
435
3.890625
4
from random import randint from time import sleep computer = randint(0, 10) print('=' * 50) print('\tLet s play guessing? ') print('\tTry to hit the number I am thinking! ') print('=' * 50) player = int(input('Enter an integer from 0 to 10! ')) print('YOU...') sleep(3) if player == computer: print('CONGRATULATIO...
a8cf52b6682772397c1e46736b301f30ce01d5d2
T1h0can/2d-platformer-pygame
/lib/vector.py
3,325
3.609375
4
class Vector2d: # @type_check(tuple, 2) def __init__(self, coords): """ input a tuple of (x,y) """ # Type check # if not ((isinstance(coords, tuple)) and (len(coords) == 2)): # raise TypeError("{} isn't a tuple of length 2".format(coords)) self.coords...
b92fa06d7d91f75370ae601cff9cc768cb1f215c
Weiguo-Jiang/alien_invasion_project
/alien_invasion.py
1,572
3.5
4
import pygame from settings import Settings from game_stats import GameStats from scoreboard import Scoreboard from button import Button from ship import Ship from alien import Alien import game_functions as gf from pygame.sprite import Group def run_game(): # initialize game and create a screen object pygame.init(...
7f0dbbfce00c1d8239771665b61a682730abf8e1
y56/leetcode
/694. Number of Distinct Islands.py
4,703
3.53125
4
""" 694. Number of Distinct Islands Medium Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Count the number of distinct islands. An island is considere...
9ca9191cf6729688724725f225cfea55a09cc4f6
rctorr/desarrollo-web-python-cdmx-20-01
/Sesion-01/pares_nones.py
346
3.6875
4
# 1. Leer el valor de N cad = input("Dame un número entero mayor que cero:") n = int(cad) # 2. Generar una lista de N números lista = range(n) # 3. Determinar cuales son pares y nones y asignar la palabra correcta # 4. Imprimir el resultado for i in lista: if i % 2 == 0: # par print(i, "par") else: ...
a70fd09a71c18c65319b4c4739bc8151bc3ce82a
bruce-szalwinski/lpthw
/ex3.py
640
4.1875
4
# prints print "i will now count my chickens:" # division before addition print "Hens", 25+30 / 6.0 # modulo first, then multiplication, then subtraction print "Roosters", 100-25 * 3 % 4 # 4%2 = 0, integer division (1/4 = 0) print "Now i will count the eggs" print 3+2+1-5+4%2-1/4+6 # addition and subtraction before ...
a02d068b153208c49aa6881685eb550acd2320f1
zhengjiani/pyAlgorithm
/leetcodeDay/April/prac23.py
2,802
4.03125
4
# -*- encoding: utf-8 -*- """ @File : prac23.py @Time : 2020/4/26 9:37 上午 @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm """ # Definition for singly-linked list. from queue import PriorityQueue from typing import List class ListNode: def __init__(self, x): self.val = x ...
196eadac08ba78e9a5cd446b363e429aee2958b4
yeboahd24/Python201
/default program/class2.py
1,856
4.09375
4
#!usr/bin/env/python3 """use plain attribute instead of setter and getter methods""" class OldResistor(object): """using these setters and getters is simple but not pythonic""" def __init__(self, ohms): self._ohms = ohms def get_ohms(self): return self._ohms def set_ohms(self, ohms): self._oh...
87ddb62ebf1a0e29466247b4874f0733b86927f0
davidjmstewart/DependencyInversion-DependencyInjection
/IoC/python/python_ioc_tkinter.py
1,189
3.625
4
# Run with python ./python_ioc_tkinter.py from tkinter import * window = Tk() window.title("IoC example") window.geometry('600x300') first_name_label = Label(window, text="First name") first_name_label.grid(column=0, row=0) first_name_txt = Entry(window,width=10) first_name_txt.grid(column=1, row=0) # Lambda callba...
22612544a898bdf9ee3bdf45ab6ded5ba9e32d13
vzhng/python_practice
/python_learn1/factor.py
210
3.78125
4
a=input("Please input a number:") #a=30 # m=int(a) def factorize(n): b=[] for i in range(1,n+1): if n % i ==0: b.append(i) return b x=factorize(int(a)) print(x)
b7fd40f7cf3b28676618e12c34734fb563f62fef
laithadi/School-Work---Data-Structures-Python-
/Adix5190_a03/src/t05.py
719
3.9375
4
''' ................................................... CP164 - Data Structures Author: Laith Adi ID: 170265190 Email: Adix5190@mylaurier.ca Updated: 2019-02-01 ................................................... ''' from functions import has_balanced_brackets BALANCED = 0 MORE_LEFT = 1 MORE_RIGHT = 2 MIS...
c49d72cef8ea6b16beae7c1ec695c32ee8e59c40
GloriaWing/wncg
/打印乘法表(不同排列方式).py
913
3.796875
4
''' #完整格式输出九九乘法表 for i in range(1,10): for j in range(1,10): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') ''' ''' #左上三角格式输出九九乘法表 for i in range(1,10): for j in range(i,10): print("%d*%d=%2d" % (i,j,i*j),end = ' ') print('') ''' ''' #右上三角格式输出九九乘法表 for i in range(1,10): for k ...
80e181f8b75ffcb822b0f1aaa61d26632c190007
SketchwithTejOfficial/TexttoSpeechSoftware
/TexttoSpeech.py
469
3.671875
4
import pyttsx3 #To install module enter pip install pyttsx3 in terminal engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') engine.setProperty('voice', voices[0].id) #For female voice enter 1. engine.setProperty('rate', 150) #To make the voice slow and fast decrease and increase the values h...
d610a795b627460112c49e9b328de7c1973f1753
hattoryha/Python
/find_question.py
975
3.53125
4
import requests import bs4 import argparse def get_questions(N, tag): # tag = 'python' url = 'https://api.stackexchange.com/2.2/questions?order=desc&sort=votes&tagged={}&site=stackoverflow'.format(tag) r = requests.get(url) api_data = r.json() api_item = api_data['items'] # N = 1000 question...
53f74cafb1e31ae278a4b33b91984d1791cb2f6c
EmlynQuan/Programming-Python
/JZOffer/JZOffer36.py
2,021
3.90625
4
# coding=utf-8 # Definition for a Node. class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right class Solution(object): def treeToDoublyList(self, root): """ :type root: Node :rtype: Node """...
8aa4e6c66c6b6e1bbed93846899fa796a3b7b2ce
cligs/toolbox
/analyse/make_freqslist.py
7,007
3.671875
4
#!/usr/bin/env python3 # Filename: make_freqslist.py # Author: #cf # Date: 2016 """ Creates an overall relative frequency list for items in a text collection. Items can be raw word tokens, lowercase word tokens, or lemmata (using TreeTagger). Data can be relative frequency per 1000 words or proportion of texts contai...
f80d47fdecbd93953dba21d9194e5a695d7259e5
MarioPezzan/ExerciciosGuanabaraECurseraPyCharm
/Exercícios curso em video/Exercicios/ex002.py
424
3.796875
4
nome = input('qual seu nome? ') print(f'Muito bem vindo {nome} prazer em te conhecer!') sexo = input('qual seu sexo? ') nacionalidade = input('qual sua nacionalidade? ') dia = input('Dia do Nascimento: ') mes = input('Mês do Nascimento (Ex:Janeiro): ') ano = input('Ano do Nascimento: ') print(f'Nome:{nome}. Sexo:{sexo}...
3f6ed96b7b580570ab4bf4af5fbe925ac0048833
GuilhermeUtech/Python
/intro/ex15.py
194
3.875
4
a = str(input("Digite uma frase\n")) b = a.count('A') print(b) c = a.find('A') print("O primeiro A começa em: {}".format(c)) d = a.rfind('A') print("A última ocorrência é em: {}".format(d))
6579f3df53d81400e77a1b14654130a55d235ff4
DeviantBadge/spheremail.ru
/1sem/intoToDataAnalisys/practice/hw2/taskH.py
2,615
3.734375
4
class Node: left = None right = None parent = None value: int = None def __init__(self, val, parent): self.value = val self.parent = parent def next(self, val: int): if val > self.value: return self.right else: if val != sel...
03efc485c1336e1786c44190c301aba5c423df33
Bl4ky113/clasesHaiko2021
/check_vocales.py
990
3.75
4
VOCALES = ('a', 'e', 'i', 'o', 'u') class word (): def __init__(self) -> None: self.word = input("Ingresa una palabra: ") self.info = self.getInfo(self.word) def getInfo (self, word): info_dict = {} has_vocals = False num_vocals = 0 vocals = [] for char in word: if char.l...
db72261115a1ebe40b8ebf78e11fb39f45fb31cf
YasinEhsan/developer-drills
/twoPointers/pairWithTargetSum.py
420
3.640625
4
# may 29 20 def pair_with_targetsum(arr, target_sum): # init pointers left = 0 right = len(arr) -1 # loop until pair found while left < right: # get sum currSum = arr[left] + arr[right] if currSum == target_sum: return [left, right] elif currSum < target_sum: # need bigger number...
00f3091b6a05c7ede5800e9468385189e3236734
cuimin07/LeetCode-test
/133.最长和谐子序列.py
613
3.75
4
''' 和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。 现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。 示例 1: 输入: [1,3,2,2,5,2,3,7] 输出: 5 原因: 最长的和谐数组是:[3,2,2,2,3]. 说明: 输入的数组长度最大不超过20,000. ''' #答: class Solution: def findLHS(self, nums: List[int]) -> int: ans = 0 d = collections.Counter(nums) for num in nums: ...
360b9485c6627e37c7a94d97fab41bd5a2ba7520
benfatehi/cs114
/Volume_in_gallons.py
154
3.953125
4
print("Please give me a volume in gallons. I will then convert it into liters.") gallons=int(input()) liters=(gallons * 3.78541) print("liters: ",liters)
fc0b92d7fef715eb235a38397556eae2051741dd
qwert19981228/P4
/课件/0228/9问题.py
925
3.609375
4
import threading g_num = 0 def task1(): global g_num for i in range(1000000): # 上锁 mutexFlag = mutex.acquire(True) # 检测是否获得资源 如果得到 mutexFlag True if mutexFlag: g_num += 1 # 释放锁 mutex.release() print('task1',g_num) def task2(): globa...
8c449ae9a3ef50d9e09acc515a55ab68f1b20664
Anindyadeep/CNN-from-scratch
/conv_test.py
3,220
3.578125
4
from keras.datasets import mnist import numpy as np import matplotlib.pyplot as plt from conv3x3 import Conv3x3 from maxpool import MaxPool2D from softmax import Softmax (X_train, Y_train), (X_test, Y_test) = mnist.load_data() X_train_now = X_train[0:1000] Y_train_now = Y_train[0:1000] X_test_now = X_test[...
8eb8d03953e7ed71598715af93170224e7cfa274
eboladev/Study
/ProgrammingLanguage/Python/Source/LeapYear.py
174
3.640625
4
def leap_year(n): return (n%4==0) and n%100 or n%400==0 def main(): for n in range(1990, 2001): if leap_year(n): print n if __name__ == "__main__": main()
3a848c420e0aea16fdd18572c418127c9233044e
xulleon/algorithm
/leetcode/Chapter6_DFS_on_Combination/Word_Ladder_II.py
2,924
3.71875
4
# https://leetcode.com/problems/word-ladder-ii/submissions/ from pprint import pprint class Solution: def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: if not beginWord or not endWord or not wordList or endWord not in wordList: return [] ladde...
becc6a966f455b1d32d7633c9f7cfb53e110b033
kelvinng2017/chat1
/test2.py
225
3.890625
4
while True: print("請輸入密碼:", end='') password = input() if int(password) == 1234567: print("歡迎光臨!敬請指教") break else: print("密碼錯誤!請在重新輸入")
fcb3cfcc1d4cc6d40a3bf55b42324c8b25d44071
armspkt/Hacktoberfest2021-2
/Python/simple_calculator.py
2,711
4.125
4
####### A Simple Python Calculator ####### ####### Made by: Anish Shilpakar (github: juju2181) ####### """ A Simple Python Calculator that will do addition, subtraction, multiplication, division and modulo operations on two entered numbers. """ #function to add two numbers def addTwoNumbers(x,y): return f"Sum of {...
119aea0c6ea10902a592343390116095ca9c6919
darkcode357/rfclist
/rfc-list.py
1,310
3.5
4
from os import system import sys, urllib.request criador = "by darkcode 14/7/2017\nsite:https://www.darkcode0x00.com" versao = "1" def rfclist(): try: numero_rfc = int(sys.argv[1]) except (IndexError, ValueError): print("Deve fornecer um numero de RFC para a busca...") sys.exit(2) s...
4a8e8942d9e1ad9beabefb8ca6a3cba6b13f9070
yibei8811/algorithm
/codingInterview/006/solution.py
655
3.640625
4
class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def __str__(self, data=None, next=None): return self.data class Solution: @staticmethod def solve(var_node): if var_node.next is None: print(var_node) else: ...
af5c712e4e55878f4034b70735235a60656b4b78
kurazu/pycon_quiz
/solutions/poss1.py
299
3.84375
4
import itertools digits = '2', '4', '6', '8' s = 0 for perm in itertools.permutations(digits): num = int(''.join(perm)) print num s += num print 'SUM', s digits = '1', '2', '3', '4' s = 0 for perm in itertools.permutations(digits): num = int(''.join(perm)) print num s += num print 'SUM', s
eba10d3b1d250b11d0d27c55a23739783b92f44b
idkosilov/RSA_encrypting
/pictogramcoding.py
2,510
3.5
4
def rle_algorithm(string_code): rle_string = '' count = 1 for i in range(1, len(string_code)): if i <= len(string_code): if string_code[i - 1] == string_code[i]: count += 1 else: rle_string += str(count) count = 1 rle_string...
36363799a699f6fd976cbae2541a43c88376a352
alukinykh/python
/lesson2/4.py
566
4.03125
4
# 4. Пользователь вводит строку из нескольких слов, разделённых пробелами. # Вывести каждое слово с новой строки. Строки необходимо пронумеровать. # Если в слово длинное, выводить только первые 10 букв в слове. my_str = input('Введите строку из нескольких слов: ') str_list = my_str.split(' ') for key, item in enumer...
cc9d8dbd76e1b3d00a9f6fc7fa795bcfe3652263
vmk0102/PIAIC-AIC
/stringmethods.py
551
4.03125
4
#**************ASSIGNMENT 1*************** a = "my name is Wali" b = "PYTHON IS GREAT!" c = "Hello World" num = "6789325" print(a.capitalize()) print(c.lower()) print(b.casefold()) print(a.find("is")) print(a.count("")) print(b.istitle()) print(a.isalnum()) print(a.endswith("li")) print(b.replace("GREAT", "BAD")) p...