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
bcacc85fdc2fde42a3f3636cedd1666adaa24378
Chia-Network/chia-blockchain
/chia/util/significant_bits.py
991
4.125
4
from __future__ import annotations def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int: """ Truncates the number such that only the top num_significant_bits contain 1s. and the rest of the number is 0s (in binary). Ignores decimals and leading zeroes. For example, -0b01111...
75c17af29b676d58e5b8de1a017784be24df6886
Lord-O-Binary/FinalExam
/Problem2.py
863
3.9375
4
#Design and implement a Python program that is based on these requirements: # a) define a class which has at least two methods # o Method 1 – getString: to get a string from console input; and, # o Method 2 - printString: to print the string in upper case. # b) demonstrate code works using three different test input st...
f3d569ebc4192a0e60d95944b91ac33bac1f17aa
chimaihueze/The-Python-Workbook
/Chapter 2/44_faces_on_money.py
1,118
4.1875
4
""" Individual Amount George Washington $1 Thomas Jefferson $2 Abraham Lincoln $5 Alexander Hamilton $10 Andrew Jackson $20 Ulysses S. Grant ...
87a475ae20b4dde09bc00f7ca8f0258ead316aa4
chimaihueze/The-Python-Workbook
/Chapter 1/exercise24_units_of_time.py
670
4.4375
4
""" Create a program that reads a duration from the user as a number of days, hours, minutes, and seconds. Compute and display the total number of seconds represented by this duration. """ secs_per_day = 60 * 60 * 24 secs_per_hour = 60 * 60 secs_per_minute = 60 days = int(input("Enter the number of days: ")) hours =...
621e85bdd3efd63d3d3fccd18e6d77d83ef9d6f3
chimaihueze/The-Python-Workbook
/Chapter 1/exercise29_wind_mill.py
1,266
4.4375
4
""" When the wind blows in cold weather, the air feels even colder than it actually is because the movement of the air increases the rate of cooling for warm objects, like people. This effect is known as wind chill. In 2001, Canada, the United Kingdom and the United States adopted the following formula for computing ...
420c2501440b97e647d1eff05559561e5c5b3869
chimaihueze/The-Python-Workbook
/Chapter 1/exercise23_area_of_a_regular-polygon.py
531
4.46875
4
""" Polygon is regular if its sides are all the same length and the angles between all of the adjacent sides are equal. Write a program that reads s and n from the user and then displays the area of a regular polygon constructed from these values. """ # s is the length of a side and n is the number of sides: import...
61628dc6e1c6d4ba2c8bdc112d25aa1b2d334f96
cheikhtourad/MLND_TechnicalPractice
/question2.py
1,628
4.125
4
# Question 2 # Given a string a, find the longest palindromic substring contained in a. # Your function definition should look like question2(a), and return a string. # NOTE: For quetions 1 and 2 it might be useful to have a function that returns all substrings... def question2(a): longest_pal = '' # Base Case: The...
d17e781a0aad090461d52e85946f736f1232f4e9
Microsongs/Python_WebScrapper_clone
/1.Theory/DataTypesOfPython.py
321
3.78125
4
a_string = "like this" a_number = 3 a_float = 3.12 a_boolean = False # 자바스크립트의 null이랑 비슷-> None은 존재하지 않음 a_none = None # 파이썬은 단어가 길어질 떄 _를 사용한다. print(type(a_string)) print(type(a_number)) print(type(a_float)) print(type(a_boolean)) print(type(a_none))
58e2c9c303e3d243727c81e0c6ac5686e31398d6
allenzhong/UserUpload
/test/test_user.py
2,001
3.765625
4
import unittest from processors.user import User class TestUser(unittest.TestCase): def test_create_user(self): name = 'John' surname = 'Allen' email = "johnallen@email.com" user = User(name, surname, email) self.assertEqual(name, user.name) self.assertEqual(surname, user.surname) self.a...
3c6a3ffb396896360f45c373f871e4e15fafc181
vivekinfo1986/PythonLearning
/Oops-Polymorphism_AbstractClass_Overwrite.py
530
4.46875
4
#Define a base class with abstract method and using inheritence overwrite it. class Animal(): def __init__(self,name): self.name = name #Testing abstract class def speak(self): raise NotImplementedError('Subclass must implement this abstract method') class Dog(Animal): def speak(self)...
46adcf222efdd8eb04e891f16efb105aece04100
G-Gowtham/Programming
/python/Implement_two_stacks_in_an_array.py
1,906
3.625
4
#User function Template for python3 ''' Function Arguments : @param : a (auxilary array), top1 and top2 are declared as two tops of stack. # initialized value of tops of the two stacks top1 = -1 top2 = 101 @return : Accordingly. ''' def pop1(a): global top1 if(top1 !...
73e93114f8cff7c463af7e49855cbf341aa569c6
G-Gowtham/Programming
/python/Detect_cycle_in_a_directed_graph.py
1,301
3.546875
4
# Your task is to complete this function # Function should return True/False or 1/0 # Graph(graph) is a defaultict of type List # n is no of Vertices #white = visited, grey = loop def dfs(i,graph,white,grey,flag): if grey[i] == 1: return 1 grey[i] = 1 if white[i] == 0: ...
db42042e89e33bde554414c038c1882ea42aa06f
Sanuj5895/Design-and-Analysis-of-Algorithms-Part1-Coursera
/Week-5/dijkstra.py
1,348
3.546875
4
def dijkstra(graph,src): global visited, distances for i in xrange(1,201): minW = 1000000 for node in visited: for neighbor in graph[node]: if neighbor not in visited: new_distance = distances[node] + graph[node][neighbo...
7790cf2170ff0f3cd848945e1fa7f2154eabff19
ENADSOFT/pythontut1
/class_student.py
374
3.515625
4
class student: def __init__(self,name): self.name = name self.attend = 0 self.marks = [] print("Welcome {} to the school".format(name)) def addmarks(self,ma): self.marks.append(ma) def attenddays(self): self.attend += 1 def getavg(self): ...
9c56056828d679f074dbf2bff4b96d805eaf2ef5
yogesum/ud120-projects
/svm/svm_author_id.py
2,197
3.59375
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from time import time sys.path.append("../tools/") from email_preprocess import preproce...
649554a6af19f4c16562158e17a24a630a116fcd
arctan5x/jhu
/algorithms/sorting/insertion_sort.py
609
4.1875
4
def insertion_sort(lst): if not lst: return [] for i in range(1, len(lst)): pivot_key = lst[i] position = i - 1 while position > -1 and pivot_key < lst[position]: lst[position + 1] = lst[position] position -= 1 lst[position + 1] = pivot_key return lst if __name__ == "__main__": # some tests lst1...
5a238d5506accfb1e6206ab604780b3bcf8f4fc9
liheyuting/practiceday
/pythonautomation/Chapter 6/validateInput.py
698
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/30 7:07 AM # @Author : Dora # @File : validateInput.py while True: print('Enter your age: ') age = input() if age.isdecimal(): break print('Plese enter a number for your age.') while True: print('Select a new password ...
8fdb47a785b9e154ab5b1eb6c807aef911978776
liheyuting/practiceday
/pythonautomation/allMyCats1.py
436
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/9 10:27 PM # @Author : Dora # @File : allMyCats1.py catNames = [] while True: print('Enter the name of cat '+ str(len(catNames)+ 1 )+' (Or enter nothing to stop.):') name = input() if name == ''...
3e0d512b6e3044bc234e8c8679e87322d5a7e0a3
bisirkin-pv/FileMonitor
/src/utilities/Observed.py
996
3.5
4
import itertools class Observed: """ Класс добавляющий методы для наблюдения """ def __init__(self): self.__observers = set() def observers_add(self, observer, *observers): """ Добавляет наблюдателей и выполняет начальное оповещение :param observer: :param ...
3effac6e0ee49bce8f27e91f881d57f6ab4eda7d
eddy0/algorithm
/python/array/14. Longest Common Prefix .py
1,061
4.03125
4
from typing import List """ Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: ["flower","flow","flight"] Output: "fl" Example 2: Input: ["dog","racecar","car"] Output: "" Explanation: There is no common ...
0b6772f72e55f1eaf0671a9a21c75cd1b398cd55
infexorg/jetstream
/jetstream/calc.py
1,184
3.984375
4
def pathcalc_om(om1, om2, om3, omd): """Calculate the path required to reach a target by anchoring waypoints on orbital markers. Args: om1 (float): Distance in km of closest OM to target. om2 (float): Distance in km of 2nd closest OM to target. om3 (float): Distance in km of 3rd clo...
a7707d9efb9ea36174c6f3e4174b99e8af883925
regisf/geocluster
/geocluster/geobound.py
3,163
3.609375
4
# -*- coding: utf-8 -*- # Geocluster - A simple and naive geo cluster # (c) Régis FLORET 2014 and later # from .geoboundbase import GeoBoundBase from .geoconvertion import * from .geopoint import GeoPoint class GeoBound(GeoBoundBase): """ A Geobound is in fact a rectangle """ def __init__(self, north, w...
b2192799ae5939b966f5224598fddd6d484db93a
17181370591/-
/Q42将牌洗为逆序2.py
2,104
3.515625
4
''' 分析 使用双向的bfs,即从起点找能到达的点,同时从终点找能 到达它 的点, 两个点集有共同元素就找到了。注意点: 1、本来使用list记录牌(set无序),但是list不能通过set快速查找重复项, 所以选择用字符串记录 2、从1234遍历是把中间的牌放上面,反过来从4321遍历要把上面的牌放中间, 而不是中间的牌放下面 3、原本当前牌序和步数组成list一起放进队列,这样无法快速用set找相同的当前牌序, 于是拆开放在不同的队列了 4、坑1:对某一点遍历它所有变换时,一定要遍历完和该点步数相同的所有点的变换, 否则队列查看是否有相同牌序时会出现有些排序需要的步数比其他排序多/少1, ...
3a16c88941a030f5eef9bea771ad4ab45afaa02b
17181370591/-
/Q04切分木棒1.py
756
3.84375
4
''' 假设要把长度为 n 厘米的木棒切分为 1 厘米长的小段,但是 1 根木棒只能由 1 人切分, 当木棒被切分为 3 段后,可以同时由 3 个人分别切分木棒( 图2 )。 求最多有 m 个人时,最少要切分几次。譬如 n = 8,m = 3时切分 4 次就可以了。 ''' #这个题思路的核心就在于尽快让更多的人参与到工作中来, #实际操作时全部对半切,可以不考虑具体切法,按效果来计算 def cut(n,length,nums): global count if nums>=length: return count+=1 if nums<=n: cut(n,length,num...
02f868a8b3f7c50a6424d3eaa100ab62105a4840
17181370591/-
/Q26高效的立体停车场.py
866
3.828125
4
''' 问题描述(有修改) 10*10的棋盘上放了10*10-1的棋子,右下角空白。每次可以交换空白和它相邻的一个棋子, 求将左上角的棋子移动到右下角的最少次数 分析 棋子只能右移或者下移,否则不是最少。则移动棋子前空白在棋子右/下,交换后在左/上。 那么整个移动过程可以分成两步,重复这两步a+b次即可(设棋盘变成是a和b) 步骤1:将空白移动到棋子右/下 步骤2:交换空白和棋子 步骤1一共a+b次,步骤2第一个值是a+b-1,此后每个值都是2或者4, 棋子改变移动方向时是2,不变是4,这说明最短方法就是尽可能多的改变方向 ''' a,b=100,100 def getStep(a,b): if b>a: ...
0fd788b43e81c365f807aa324c749896efabbae2
joshavenue/NumPy-note
/method_basic.py
466
3.71875
4
import numpy as np x = np.arange(50).reshape(5,5,2) x.shape() // To check the shape of the dimension // x.ndim() // To check the number of dimension // x.itemsize() // To check the size in bytes of each element of the array. // x.size() // To check the multiplication num...
fde66e815cf23136da41cd4f973a1704c5f5db3a
gamt89/misiontic2022-ciclo1
/RETO5S67.py
2,271
3.578125
4
def estrellas(): print('*****************************************************************************') import re #TÍTULO DEL PROGRAMA print('') estrellas() print('') print('BIENVENIDO A LA AGENDA DE BENEFICIARIOS DEL PROYECTO MINTIC') print('') estrellas() print('') def crearArchivo(): archivo=open('agenda...
4778bce600fe85ffb472d1458050b15d5d20e01f
ShiekhRazia29/Dictionary
/Q5Duplicate.py
373
4
4
dic={ 'ball':"red", 'bat':4, 'wicket':8, 'ball':'green', "bat":3 } #dic2={} #for k,v in dic.items(): # dic2[k]=v #print(dic2) print(dic) # removes all the duplicates as the dictionaries doesnt contain duplicate values result={} for key,value in dic.items(): if value not in resul...
9dd09c27fa88d56e88778df9bee7ddf4edaa98ca
ShiekhRazia29/Dictionary
/samp7.py
542
4.5
4
#To check whether a key exists in a dictiory or not #For that we use a key word called "in" key_word_exists={'name':"Razia",'Age':22,'Course':"Software Engineering", 'present':"Navgurkul Campus"} if 'name' in key_word_exists: print("Yes the keyword name exists:",key_word_exists['name']) else: print("No t...
4a8a37e917d99a2de4ffea75a4d7136288ac1373
ShiekhRazia29/Dictionary
/debud2.py
138
3.765625
4
#debug to get 14 as output dict1={1:2,2:3,3:4,4:5} sum=0 for i in dict1.values(): sum=sum+i #here 1 is replaced with i print(sum)
d9525df6979523a9904f2cb37bd8aa67960f0531
ShiekhRazia29/Dictionary
/Debug3.py
154
3.84375
4
#To print number as key and its value as square c=dict() for i in range(1,16): c[i] =i**2 #instead of pow * was used and only c was given print(c)
3efc0fc73ac41af9ac77e905c7cf68b82a71a2d5
brayan-mendoza/ejercicios_examen
/L-2.py
357
4.21875
4
# utlizando ciclos (loops) dinujar un triangulo de asteriscos def triangulo(altura): for numero_linea in range(altura): espacios = altura - numero_linea - 1 print("", espacios) asteriscos = 1 + numero_linea * 2 print (" " * espacios + "*" * asteriscos) alt = int(input("int...
d2c5db3ae2cb583212d043216cf5034933675049
ggw12138/hnu-osdesign-ghw
/PYTHON/pythonlearn/listlearn.py
615
3.96875
4
list1 = [] #创建空列表 list1.append('dd') #压入第一个元素 list1.append('pp') #压入第二个元素 list1.append('mm') #压入第三个元素 print(list1) absent = 'dd' #缺席名单 list1.remove(absent) #移除缺席者 list1.insert(0,'cc') #添加新加入者到开头 list1.insert(2,'ff') #添加新加入者到第3号位置 list1.append('gg') #添加新加入者到末尾 print(list1) while len(list1)>2: #当人数大于2的时候就弹...
8425833fc9d1830f9a1cd54a5220e63f374a5b89
willl4/eulerprog
/prog.py
1,966
3.953125
4
from math import * if __name__ == '__main__': data = {} data['coefficients'] = '' data['derivative'] = '' print('If there is a sinx function input it as sin(x)') print('If there is a cosx function input it as cos(x)') print('If there is a tanx function input it as tan(x)') print('If there is a cotx functio...
fff26b9c1ea0febd057858efd0d1fa8dd8c38199
htothehilla/100DaysPython
/Module1/Day14/challenge.py
1,240
4.0625
4
from typing import List, Any, Union, Tuple content = ["Wayne is the toughest guy in Letterkenny.", list(range(0,101,10)), ("Wayne", "Dan", "Katy", "Daryl"), 10.4] print(content) for word in range(0, len(content)): if type(content[word]) is tuple: print("{} is a {}".format(content[i], type(content[word])))...
5422b33a82ede43c87814d876af135852a815488
htothehilla/100DaysPython
/Module2/Day18/day18.py
1,977
3.796875
4
#display all built in functions in package from turtle import Turtle for func in dir(__builtins__): print(func) #call that function ( need understand import random num = random.randint(0, 100) for i in range(0, 100): try: guess = int(input("Guess a number between 0 and 100: ")) except: print("...
994d5881206a5f11d085c4cbdbaa347f34977760
andrewtong0/twitterUpdates
/twitterUpdates.py
1,252
3.578125
4
import twitter # API for handling Twitter import time # Delaying subsequent API calls # Authentication for use of API api = twitter.Api(consumer_key="CONSUMER_KEY", consumer_secret="CONSUMER_SECRET", access_token_key="ACCESS_TOKEN_KEY", access_token_secret="ACCESS_...
75a754c480e7113c2c0719cc9909d97b2956fdd0
buicaochinh/simple_assistance
/understand.py
254
4.03125
4
you = "hello" if you == "": robot_brain = "I can't hear you, try again" elif you == "hello": robot_brain = "Hello Chinh" elif you == "today": robot_brain = "7/22/2020" else: robot_brain = "I'm fine thank you and you" print(robot_brain)
da6a8f37002b61d01a8a35dfe49a730dfa8a0d3f
AndyWheeler/project-euler-python
/sum_even_fib.py
491
3.546875
4
debug = False def sum_even_fib(limit): total = 0 term1 = 1 term2 = 1 while term2 < limit: if debug: print "term1: %d, term2: %d" % (term1, term2) #check term for evenness if term2%2 == 0: total += term2 if debug: print "--found...
cd4f7ca00ff3f3336e8899c75f10fc5d69fedc7e
AndyWheeler/project-euler-python
/project-euler/5 Smallest multiple/smallestMultiple.py
1,105
4.15625
4
import primeFactors #primePower(num) returns True if num is a prime power, False otherwise def primePower(num): factors = primeFactors.primeFactorsOf(num) #print "prime factors of " + str(num) + ": " + str(factors) isPrimePower = not factors or factors.count(factors[0]) == len(factors) return isPrimePo...
8b0b0256d8cd20a75c32f078e48e8926a976bfea
Vasu-Eranki/10daysofStats
/Binomial_Distribution_1.py
765
3.71875
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import os import math import statistics def binomial(b_prob,g_prob): sum1 =0 total = 6 for i in range(int(total/2),total+1): temp = math.factorial(total) temp1 = math.factorial(i)*math.factorial(total-i) temp ...
05520b054e5115faf1487b889a0830f28f777ebd
Vasu-Eranki/10daysofStats
/Poisson_Distribution_1.py
368
3.53125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import os import math if __name__=="__main__": mean = float(input()) x = float(input()) fact = math.factorial(x) e = math.e p = (mean**x)*(e**(-mean)) p = p/fact p = round(p,3) fptr = open(os.environ['OUTPUT_PATH'],'w...
3fce72544a36955d033e93ea1634bc9fb6c4e2d9
sanyco86/learn
/lesson_2/2_files.py
1,331
3.609375
4
""" Домашнее задание №2 Работа с файлами 1. Скачайте файл по ссылке https://www.dropbox.com/s/sipsmqpw1gwzd37/referat.txt?dl=0 2. Прочитайте содержимое файла в перменную, подсчитайте длинну получившейся строки 3. Подсчитайте количество слов в тексте 4. Замените точки в тексте на восклицательные знаки 5. Сохраните ре...
2773ab261ca90fb7e5486361ec9132519b6689e3
frangiaverini/pythopn
/loop.py
129
3.671875
4
for i in range(3) : print("This in a loop, but...") for j in range(2) : print("There is this other llop inside of it.")
d3b77f4266344dd5cf63a07a64282fea509bb49e
tirmisula/A-star-search
/binary_heap.py
5,749
3.9375
4
class Heap: """ Remember to use validate() method to check order's correctness """ def __init__(self,oldlist): ''' node is a cell in maze, nodelist is a list of node, sort nodelist by node.f @type oldlist:nodelist @type newlist:nodelist ''' # Heap...
d4f22a597bf8a556e57a10784330b3d0f87b01c1
jwcunha/test
/well_conversion.py
1,928
3.515625
4
""" Print out the new well number of a 24 well plate's wells after pooling into a 96 well plate, or the index of a 384 well plate based on a 96 well's location. """ #import sys alpha = 'ABCDEFGHIJKLMNOP' ## Rows of a 96 well plate alpha384 = { 'A' : ['A','B'], 'B' : ['C','D'], 'C' : ['E','F'], 'D' : ['G','H'], 'E'...
4630a68bdab302f7f65943b457f508ec9c5f6c6c
hectorip/CentraalIntroPython
/numeros.py
312
3.640625
4
# Números age = 90 # entero tall_m = 1.74 # float # doble precision tall_cm = 174 complex_number = 9 + 7j # completjo print(age) print(tall_m) print(complex_number) # Convertir de cadenas o hacia cadenas number_str = str(age) + " numero" print(number_str) str_number = int("98") print(str_number)
e915c6a504a2b31ae304c74acb0265d6f542e06f
devdjan/Basic_python
/matrix.py
5,277
4.1875
4
#Для начала попробую создать список и просумировать его по циклу a = [[1,2,3,4], [5],[6,7],[8,9]] s = 0 # Переменная глобальная в которую будем записывать сумму for row in a: # Выберется [1,2,3,4] for elem in row: #Выберем первый элем списка [1,2,3,4] s += elem print(s) # --------------------------...
b004491f2683a5bff859068b5537b1b7af4a6d1c
devdjan/Basic_python
/Games/tic_tac_toe.py
3,797
4.03125
4
# Игра крестики нолики # Stage 1 # Draw board, make main loop. # Stage 2 # How to win - Write combinations # Stage 3 # Make another player # Write combinations for player O. The same as player X # Stage 4 # reuse code, where we check winning combinations # Write two functions to check if o winner or X # Function to ...
85e64062628075c05ce7b3a44080919205442149
devdjan/Basic_python
/book_course/2 Functions and modules/local_scope.py
1,104
4.09375
4
# # # def init_values(): a = 100 # Локальная видимость, # вне функции значение равно нулю a = 0 init_values() # print(a) # 0 # Принимает аргумент # Передаем значение "б" # При вызове функции, переменная а будем локально связана со # значением т.е - нулем # Можем изменять и тд. но это все просходит с локал...
f89cb8fb2a5e0e1b157f2785d3349658640fa9e3
scottnuma/robotext
/robotext.py
5,728
4.34375
4
"""A small world explorer to teach python functions Online version here: https://repl.it/BsmV """ # Background varaibles WEST = 0 NORTH = 1 EAST = 2 SOUTH = 3 DIRECTION_STRINGS = ["WEST", "NORTH", "EAST", "SOUTH"] LEFT = -1 RIGHT = 1 class World: """A world of text to explore""" def __init__(self, width=1...
74eed8c3c2ff6b78cc59fac8e409c4ad2f3d0339
My-Students/Python-robotics
/Robot_e grafi_solutions/giavelli.py
952
3.671875
4
matrix=[] n=int(input("numero di righe")) d={} j=1 for i in range(0,n): riga=[] for k in range (0,n): b =input("Inserire situazione") if(b=='f'): riga.append(False) if(b=='t'): riga.append(j) j=j+1 matrix.append(riga) k=1 for r i...
1d6e057a9c893c88ed6813027db93b9905f952f2
billgoo/LeetCode_Solution
/Top Interview Questions/348. Design Tic-Tac-Toe.py
1,733
3.96875
4
class TicTacToe: def __init__(self, n: int): """ Initialize your data structure here. """ # self.grid = [[0 for i in range(n)] for j in range(n)] self.row = [0 for i in range(n)] self.col = [0 for i in range(n)] self.diagonal = 0 self.anti_diagonal = ...
fbd62da28d5e5572f97a679a817f5a004421ec4f
billgoo/LeetCode_Solution
/Related Topics/Binary Search/[LintCode]458.Last Position of Target.py
972
3.640625
4
""" 原题 在一个排序数组中找一个数,返回该数出现的最后一个位置,如果不存在,返回-1 给出数组 [1, 2, 2, 4, 5, 5] 对于 target = 2, 返回 2. 对于 target = 5, 返回 5. 对于 target = 6, 返回 -1. 解题思路 二分法,对于找最后一个位置的要求:只有target大于A[end]才会end = mid """ class Solution: # @param {int[]} A an integer array sorted in ascending order # @param {int} target an integer # @retu...
9f0c1aa920a1558c9cc712bea46d97108014e72b
billgoo/LeetCode_Solution
/412. Fizz Buzz.py
458
3.625
4
class Solution: def fizzBuzz(self, n: int) -> List[str]: if n == 0: return [] result = [str(i) for i in range(1, n+1)] i = 1 while i <= n: if i % 3 == 0 and i % 5 == 0: result[i - 1] = "FizzBuzz" elif i % 3 == 0: re...
913806f288c81ea8432ccf27a53bbc150dbc3324
billgoo/LeetCode_Solution
/Related Topics/Greedy/678. Valid Parenthesis String.py
1,838
3.53125
4
class Solution: def checkValidString(self, s: str) -> bool: # use two stack O_n time and O_n space """ # to check if ), pop from left or star # if nothing to pop, return False # if after loop, we then use a loop to check the # top of left and star, if we encou...
3f166583bf3b00195ab411cc7d70654c2bfd5f43
billgoo/LeetCode_Solution
/Related Topics/Two Pointers/27. Remove Element.py
724
3.515625
4
# 27. Remove Element # 1. 左右指针 class Solution: def removeElement(self, nums: List[int], val: int) -> int: curr, tail = 0, len(nums) - 1 while curr <= tail: if nums[curr] == val: nums[curr], nums[tail] = nums[tail], nums[curr] tail -= 1 else: ...
3e411bf5fe628204dc63747103811358465cfe8c
billgoo/LeetCode_Solution
/Related Topics/Tree/Traversal/230. Kth Smallest Element in a BST.py
1,156
3.609375
4
# 230. Kth Smallest Element in a BST # 框架 # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def kthSmallest(self, root: Optional[TreeNode], k: int) -> int: ...
12ace5ca1c5ac8d99c10243eb730252e1732bffd
billgoo/LeetCode_Solution
/Related Topics/Tree/Traversal/543. Diameter of Binary Tree.py
670
3.859375
4
# 543. Diameter of Binary Tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: self...
0edda83daa61c3b3ae751db06a8003a61dde37d6
billgoo/LeetCode_Solution
/Related Topics/Sort/python/SelectionSort.py
580
3.796875
4
# -*- coding: utf-8 -*- #--------------------------------------- # 程序:选择排序 # 版本: # 作者:WuChong # 日期:2014-02-08 # 语言:Python 3.3 # 说明: #--------------------------------------- def select_sort(ary): n = len(ary) for i in range(0,n): min = i #最小元素下标标记 for...
0cab96ed7d17fd9960390f30f4b2ad19bc15689f
billgoo/LeetCode_Solution
/Related Topics/Linked List/25. Reverse Nodes in k-Group.py
1,291
3.75
4
# 25. Reverse Nodes in k-Group # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: if not head: retu...
f35cbf5f59c01d3fbc96bffd058a84203e190ecb
billgoo/LeetCode_Solution
/Related Topics/Array/Rotate Array/48. Rotate Image.py
1,814
3.71875
4
# 48. Rotate Image class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Do not return anything, modify matrix in-place instead. """ n = len(matrix) # 沿对角线(i, i)反转 for i in range(n): for j in range(i + 1, n): matrix[i][j], ...
810cffaefe8896d30f927770b57dc2f3724fbd48
RYUAIN96/HONG
/graph1.py
234
3.640625
4
import matplotlib.pyplot as plt # conda install matplotlib x = [10, 20, 30, 40, 50, 60, 70, 80, 90] y = [2, 3, 4, 9, 2, 5, 3, 4, 7] plt.bar(x,y) plt.title("AGES & PERSON") plt.xlabel("AGES") plt.ylabel("PERSON") plt.show()
eed308ec3ec4f5d352f55a0c820aad2f069bcb22
nikithasake/Python
/Amulya/pattern2.py
275
3.8125
4
#Pattern Program ''' 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5''' n=int(input("Enter row:")) for i in range(1,n+1): for j in range(1,i+1): print(i,end=" ") print() '''In python2.7 n=int(input("Enter row:")) for i in range(1,n+1): for j in range(1,i+1): print i, print " " '''
5a67a93072cb14c533ffb6dfe202cd50d990b94e
nikithasake/Python
/Amulya/prime[interval].py
319
3.984375
4
#Prime number within interval lower=int(input("Enter the lower interval:")) upper=int(input("Enter the upper interval:")) for num in range(lower,upper+1): if num>1: for i in range(2,num): if(num%i)==0: break else: print(num) ''' o/p: Enter the lower interval:5 Enter the upper interval:15 5 7 11 13 '''
542f7e17e5a57e538346f5cb7ea9a2837a072a51
nikithasake/Python
/python coding(prep)/11.py
113
3.90625
4
num = int(input()) if(num%2==0): num = num // 2 print(3**(num-1)) else: num = num // 2 + 1 print(2**(num-1))
d1e72d190a2962396b9856a1905e7263ce42e9b9
nikithasake/Python
/python coding(prep)/palindrome.py
183
4.0625
4
#Palindrome or not n=int(input("Enter number:")) i=n print(i) r=0 while n>0: a=n%10 n=n//10 r=r*10+a if(i==r): print(i,"is a palindrome") else: print(i,"it is not palindrome")
4ca1429fa78294b81f05a18f22f23a5bad106c73
jammilet/PycharmProjects
/Notes/Notes.py
2,014
4.1875
4
import random # imports should be at the top print(random.randint(0, 6)) print('Hello World') # jamilet print(3 + 5) print(5 - 3) print(5 * 3) print(6 / 2) print(3 ** 2) print() # creates a blank line print('see if you can figure this out') print(5 % 3) # taking input name = input('What is your name?') print('...
913c32d9e646df2896c156e1a8b88608cc463c4f
Tassneem04Hamdy/AUG-Problem-Solving-For-Bioinformatics-Level-1-
/Session 3/Dictionaries/Dictionary functions.py
1,258
3.953125
4
my_dictionary = {'type': 'Fruits', 'name': 'Apple', 'color': 'Green', 'available': True, 'number': 25} # copying new_dic = my_dictionary.copy() my_dictionary['color'] = 'Red' new_dic['available'] = False print(my_dictionary) print(new_dic) # having same reference new_dic = my_dictionary my_dictionary['color'] = 'Red'...
7f655637ffa75791787527ff1b0a843994d711ed
Tassneem04Hamdy/AUG-Problem-Solving-For-Bioinformatics-Level-1-
/Session 3/Files/Read from & write in text file.py
1,010
3.796875
4
# Reading from a file: myFile = open('input.txt', 'r') # using read() print(myFile.read()) # using readline() print(int(myFile.readline()) * 2) print(myFile.readline()) # using readlines() print(myFile.readlines()) # using for...in for line in myFile: print(line) myFile.close() ##############################...
48e61decc9b0a445f2c4f281631c910d47350c28
MarkusEngsner/project-euler-solutions
/p067 max path sum 2.py
2,543
3.8125
4
# Maximum path sum II, Problem 67 # Problem description: # By starting at the top of the triangle below and moving to adjacent numbers on the row below, # the maximum total from top to bottom is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # That is, 3 + 7 + 4 + 9 = 23. # Task: Find the maximum total from top to bottom i...
3e31fdba6f12c716797c32a1806877ddd90e6113
asmialek/cbk_mail_time
/main.py
3,231
3.703125
4
#!/usr/bin/env python # # Very basic example of using Python 3 and IMAP to iterate over emails in a # gmail folder/label. This code is released into the public domain. # # This script is example code from this blog post: # http://www.voidynullness.net/blog/2013/07/25/gmail-email-with-python-via-imap/ # # This is an up...
0bab159a9d513b08dafc6ee803deb12553355856
MoonDav/coursera-python
/week6/bubblesort.py
349
3.65625
4
a = list(map(int, input().split())) b = list(map(int, input().split())) def merge(A, B): newList = A + B for passnum in range(len(newList)-1, 0, -1): for i in range(passnum): if newList[i] > newList[i + 1]: newList[i], newList[i + 1] = newList[i + 1], newList[i] return ...
1a8adb22d33d184f0ac7f4f3a4b6af2856cf28ab
MoonDav/coursera-python
/week7/Словарь синонимов.py
1,141
3.765625
4
# Вам дан словарь, состоящий из пар слов. Каждое слово является синонимом к парному ему слову. Все слова в словаре различны. Для одного данного слова определите его синоним. # # Формат ввода # # Программа получает на вход количество пар синонимов N. Далее следует N строк, каждая строка содержит ровно два слова-синонима...
1c5da17ffaf4a23e237821fa9bcf5a0b42742412
MoonDav/coursera-python
/week7/Количество слов в тексте.py
646
3.828125
4
# Во входном файле (вы можете читать данные из sys.stdin, подключив библиотеку sys) записан текст. Словом считается последовательность непробельных символов идущих подряд, слова разделены одним или большим числом пробелов или символами конца строки. Определите, сколько различных слов содержится в этом тексте. fin = op...
976d7a598201141e0a1b4ae033be763da80fd5b2
Genyu-Song/LeetCode
/Algorithm/BinarySearch/Sqrt(x).py
1,003
4.15625
4
# -*- coding: UTF-8 -*- ''' Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. ''' class Solution(object): def mySqrt(se...
0fecfed5290f9c7aea36d242caa4085ca4559464
Genyu-Song/LeetCode
/Algorithm/Searching/Backtracking/WordSearch.py
1,516
3.890625
4
# -*- coding: UTF-8 -*- ''' Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. ''' class Solution: d...
d188291d13c688c3fd3404e49c785336f160a075
Genyu-Song/LeetCode
/Algorithm/Sorting/SortColors.py
1,598
4.15625
4
# -*- coding: UTF-8 -*- ''' Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are...
6464a732f2b237abad4e21165fb153b4a705bf27
Genyu-Song/LeetCode
/Algorithm/Searching/Backtracking/CombinationSum.py
4,105
3.515625
4
# -*- coding: UTF-8 -*- ''' Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates unlimited number of times. Note: All numbers (inc...
9786d8b3a7df08639b43c3a8f8b478b49c4d5ffe
Genyu-Song/LeetCode
/Algorithm/BinarySearch/FindMinimumInRotatedSortedArray.py
1,570
3.65625
4
# -*- coding: UTF-8 -*- ''' Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Find the minimum element. You may assume no duplicate exists in the array. ''' class Solution(object): def findMin(self, nums): ...
da2c67952945df05adf3f2535e72e35001d3cbd6
Genyu-Song/LeetCode
/Algorithm/DynamicProgramming/CombinationSumIV.py
890
4.09375
4
# -*- coding: UTF-8 -*- ''' Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. Example: nums = [1, 2, 3] target = 4 The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) ...
eaf43eaf2e7896539470e4523e99b321e26b92bd
Genyu-Song/LeetCode
/Algorithm/Sorting/KthLargestElementInAnArray.py
7,235
3.734375
4
# -*- coding: UTF-8 -*- ''' Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. ''' from random import randint class Solution(object): def method1(self, nums, k): """ :type nums: List[int] :type k: i...
ddba5805c57a8d6fb51c3c78b54d99a2e564cb04
Genyu-Song/LeetCode
/Algorithm/Searching/BFS/PerfectSquares.py
2,691
3.59375
4
# -*- coding: UTF-8 *- ''' Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. ''' class Solution(object): def numSquares(self, n): """ :type n: int :rtype: int """ # TODO: use list.pop() instead of lis...
3a5464bba723c4779dab392c41da6faebdbb0d9e
Genyu-Song/LeetCode
/Algorithm/GreedyAlgorithm/BestTimeToBuyAndSellStockII.py
1,174
3.921875
4
# -*- coding: UTF-8 -*- ''' Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple tr...
1458bb489434be62e275c4c55aacf0688a629afc
Genyu-Song/LeetCode
/Algorithm/DynamicProgramming/LongestIncresingSubsequence.py
1,554
3.703125
4
# -*- coding: UTF-8 -*- ''' Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may be more than one LIS combination, it is only ...
aad98fb847091aa5ce9b5b07a350a0dedb04af1f
Genyu-Song/LeetCode
/Algorithm/Searching/BFS/WordLadder.py
6,562
3.796875
4
# -*- coding: UTF-8 -*- ''' Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the word list. Note that beginWord is not a transfo...
faadb1f9b0dafb001d41104505d2707fc85a80b9
chrismojekwu/CS50
/py-seminar/guess.py
530
3.921875
4
import random # defining hame into function def game(): answer = random.randint(1,10) result = False for i in range(3): user = int(input("Guess a number between 1 & 10: ")) if user == answer: print("Correct!") result = True break else: ...
bf6a536df49b5ec64fd87818fbba2b95c019aa9c
AlexSongh/W21_HW5
/hw5_cards_ec2.py
9,126
4.15625
4
import random import unittest VERSION = 0.01 class Card: '''a standard playing card cards will have a suit and a rank Class Attributes ---------------- suit_names: list the four suit names in order 0:Diamonds, 1:Clubs, 2: Hearts, 3: Spades faces: dict ...
869e58ea09486b6f629f395bbca553782c34f3d7
Avchhikara/moneycontrol
/moneycontrol/utils/DateParser.py
273
3.75
4
from datetime import datetime # from time import strptime def parse_date(datetime_string): return datetime.strptime(datetime_string, "%B %d, %Y/ %I:%M %p %Z").__str__() if __name__ == "__main__": out = parse_date("APRIL 02, 2021 / 04:39 PM IST") print(out)
a755a6224bc11d5f5ef0cd3c4e24e077e9dad264
luis705/tic-tac-toe
/game.py
361
3.75
4
import time from auxiliary_functions import * while True: choice = menu() if choice == '1': game() elif choice == '2': show_table([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print("Type the number of the place you want to pay") time.sleep(2) elif choice == '3': print("Th...
d1ff79f67f13e194fe1d1f21852399eacea4465c
santiagopintus/cse210-tc03
/greetings/main.py
1,451
3.703125
4
from pintus import pintus_presentation from Chamorro import chamorro_presentation from Quarshie import quarshie_greetings def main(): print('\nWelcome to our collaborative program.\n') #Everybody's functions while True: try: presentation_chosen = int(input('\nYou have to choose what nu...
629ce9b801339ad67bcc7d0bc70b621f2720c6a2
isaiahray92/hangman
/hangman.py
2,243
4.03125
4
''' Hangman.py ''' import sys import random class Hangman: ''' Initializes the words list ''' def __init__(self): file = open('words.txt','r') self.words = [] self.wordguess = [] for line in file: self.words.append(line.rstrip()) ''' Outputs the cu...
fa0ca392f0ac6f6fffda5eb0b001c8c32ebcf868
dnsfaccini/dio-bootcamp-data-engineer-carrefour
/Introdução à Programação com Python/Projetos/11 - Gerenciando e criando exceções customizadas com try, except, else e finally/aula11.py
471
3.546875
4
lista = [1,10] arquivo = open('teste.txt','r') try: x = a numero = lista[3] divisao = 10 / 0 except ZeroDivisionError: print('Não é´possivel realizar uma divisão por 0') except IndexError: print('Erro ao acessar uma indice invalido da lista') except BaseException as ex: print('Erro ...
6126d2436c44bdf55d30c902eabb6a3bc50d2b56
darthbeep/Stack
/draw.py
9,854
3.5
4
#This is not a comment #It's a cry for help from display import * from matrix import * from math import * def add_polygon( points, x0, y0, z0, x1, y1, z1, x2, y2, z2 ): add_point(points, x0, y0, z0) add_point(points, x1, y1, z1) add_point(points, x2, y2, z2) def draw_polygons( points, screen, color ): p2 = [] i...
78681fc725f524adb6f7981542ca92a6dd1227be
Camkilpat/Data_Class_Homework
/Python - API/WeatherPy.Final.py
6,669
3.890625
4
#!/usr/bin/env python # coding: utf-8 # # WeatherPy # ---- # # #### Note # * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. # In[2]: # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd imp...
4d99d89291184000a1a7df4084120e2f638bff76
s9uarepaper/PatternWall
/color_calc.py
638
3.734375
4
import numpy as np def interpolate(color_arr, mul): pat_num = int(color_arr[:, 1].size) #初期色数 print("pat_num: "+ str(pat_num)) ret_arr = np.empty((0,3), int) for i in range(pat_num-1): dif = (color_arr[i+1] - color_arr[i] )/mul print(dif) for j in range(mul): col_tm...
401a601d052fd4ed80f1e703dacfa1ca13ba2515
EdAndradeF/HackerRankSolves
/strings/sWAP cASE.py
432
4.0625
4
def swap_case(s): invert_letra = '' for letra in s: if letra == ' ': invert_letra = invert_letra + letra elif letra == letra.lower(): invert_letra = invert_letra + letra.upper() elif letra == letra.upper(): invert_letra = invert_letra + letra.lower() ...
f13838e403245f0e5e00dd3db6d7cdd4a3425631
driscollis/Python-101-Russian
/code/Chapter 2 - Strings/string_slicing.py
248
4.25
4
# string slicing my_string = "I like Python!" my_string[0:1] my_string[:1] my_string[0:12] my_string[0:13] my_string[0:14] my_string[0:-5] my_string[:] my_string[2:] # string indexing print(my_string[0]) # prints the first character of the string
2c0d9a6f232bfa5fe23660ca5da195555b247dd0
driscollis/Python-101-Russian
/code/Appendix A/csv_reader.py
407
3.5625
4
import csv def read_csv(path): """""" try: with open(path) as csv_file: reader = csv.reader(csv_file) for line in reader: name, email = line print(name) print(email) except IOError: print("Error reading file: %s" % path...
3e882b954c14ab39e27861e65f62fa274b581836
driscollis/Python-101-Russian
/code/Chapter 8 - Working with Files/catching_errors.py
426
3.75
4
# catching errors the old school way try: file_handler = open("test.txt") for line in file_handler: print(line) except IOError: print("An IOError has occurred!") finally: file_handler.close() # catching errors when using the with operator try: with open("test.txt") as file_handler: ...