blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a5c38b65f7450f72e062fb15a553e0fdb873ad58
AP-Skill-Development-Corporation/SRIT-Python-Workshop_-31-05-2021-to-12-06-2021-
/lambda-fn-examples.py
922
4.1875
4
''' lambda fun- An anonymous function means function without name It can take any no.of arguments at a time but contain only single expression used to return fun objects restricted to only single exp. syntax:lambda arg(s): exp rem= lambda num:num%2 print(rem(9)) num=int(input()) print("remain...
3f5a2a6a7799d9aa62c4fd4df133ffc96e0a6deb
billgoo/LeetCode_Solution
/Top Interview Questions/146. LRU Cache.py
782
3.671875
4
class LRUCache: def __init__(self, capacity: 'int'): self.capacity = capacity self.hashmap = dict() def get(self, key: 'int') -> 'int': if key not in self.hashmap: return -1 else: self.hashmap[key] = self.hashmap.pop(key) return self.hashmap...
a9679cfdeb41f3a5afa1ecc834030c96e99c3e5e
globalize9/mfe2020
/timedelta.py
596
3.84375
4
# -*- coding: utf-8 -*- """ Created on Sat Dec 21 14:55:29 2019 @author: yushi """ import math import os import random import re import sys import datetime as dt # Complete the time_delta function below. def time_delta(t1, t2): t1aa = dt.datetime.strptime(t1, '%a %d %B %Y %H:%M:%S %z') t2aa = dt.datetime.st...
c9e17382c139b97f5f578cb9a548e784b272a0f2
OneChoose/python
/start/disct_method.py
151
3.5625
4
new_list = ["bobby1", "bobby2"] new_dict = dict.fromkeys(new_list, {"company":"immmm"}) for key, value in new_dict.items(): print(key,value)
fb027dd407a92b38c0de5ac211b6e00e501d091d
SimonFans/LeetCode
/Array/L56_merge interval.py
1,070
4.15625
4
Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are cons...
c352aaa6deb28fc9e85e95c859a9f49462f70869
IvAlyosha/Python_Ivanov_main
/Основы Python/dz4.4.py
602
3.671875
4
person_1 = { 'name': 'Elf', 'health': 100, 'damage': 50, 'armor': 4 } person_2 = { 'name': 'orc', 'health': 120, 'damage': 80, 'armor': 1.1 } print(f'{person_1["name"]} {person_1["health"]}, {person_2["name"]} {person_2["health"]}') def defence(defence, damage): return damage / d...
a9c90a67cec243f825a195a472d896ac3148f42e
salvador-dali/algorithms_general
/interview_bits/level_6/06_dp/04_matrix_dp/05_max-rectangle-in-binary-matrix.py
777
3.65625
4
# https://www.interviewbit.com/problems/max-rectangle-in-binary-matrix/ def largest_rect(arr): stack, maximum, pos = [], 0, 0 for pos, height in enumerate(arr): start = pos while True: if not stack or stack[-1][1] < height: stack.append((start, height)) ...
dbd1d0663d153bddb455880734443fb2952ac0b1
MerlYanez13/c98
/swap.py
284
3.75
4
def swap(): file1=input("please enter first file: ") file2=input("please enter second file: ") a=open(file1,'r') data1=a.read() b=open(file2,'r') data2=b.read() a=open(file1,'w') a.write(data2) b=open(file2,'w') b.write(data1) swap()
dd62c31a15bedad609aa7c5dbb64649708c8252e
ElizabethRoots/python_practice
/jupyter_practice/create_and_run_cells.py
1,237
4.0625
4
# Practicing Jupyter welcome_message = 'Hello, Jupyter' first_cell = True if first_cell == True: print(welcome_message) result = 1200/5 second_cell = True if second_cell == True: print(result) # ----------------------------- ''' Ctrl + Enter: run selected cell Shift + Enter: run cell, select below Alt + ...
ba4aeff2c6ec66b5b865ddb5d57b8d3deb86fea3
QuincyWork/AllCodes
/Python/Codes/Practice/LeetCode/211 Add and Search Word - Data structure design.py
1,913
3.9375
4
 # define const variable _MAX_LETTER_SIZE = 27; _STRING_END_TAG = '#'; class TireNode(object): def __init__(self,x): self.value = x self.childNodes = {} class WordDictionary(object): def __init__(self): """ Initialize your data structure here. """ self.root =...
f660be1425aacda6f26ae4197bbe8a1c7367dcd3
gabriellaec/desoft-analise-exercicios
/backup/user_257/ch25_2020_09_30_12_37_34_054037.py
235
3.65625
4
import math v = float(input(" Qual a velocidade? ")) a = math.radians(float(input("Qual o angulo? "))) g = 9.8 d=(v*v math.sin(2*a/g) if d < 98: print("Muito perto") elif d > 102: print("Muito longe") else: print("Acertou!")
4318f101afa3e5b77e7086e2fc08668bbd6b330b
cfleur/MazeNav
/Maze0.py
1,778
3.765625
4
#!/usr/bin/python import random def randObsticals(blockedCells, grid): i = 0 while i < blockedCells: for y in range(len(grid)): for x in range(len(grid[y])): rx = random.randint(0, len(grid[y])) ry = random.randint(0, len(grid)) if y == ry: ...
172e39e4b88d1cf2d46f31e532cc1bad1d05cbfc
kmlsim/30DaysOfCode-Python
/day6.py
871
4.0625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- testCase = int(raw_input()) if (testCase >= 1 and testCase <= 10): loop = 0 while (loop < testCase): # informa uma string para ser testada. string = (raw_input()) # verifica se a string obedece uma das constraints strSize...
04fbd6af93d9d8a504230a3679e2a7c52c929ab1
GauravSharma531/DS_ALGO_BOOTCAMP
/01_getting_started/CommonElements/CommonElements.py
1,020
3.8125
4
from random import randint class CommonElements: size = 0 arr1 = [] arr2 = [] def init(self): print("Size of arrays") # take input from console self.size = int(input()) print(self.size) # Initialize two same size array and asign some random values self....
6f98a56dd52d5ad54ca52d6046a8022e8bd197df
startFromBottom/programmers_problems_renewal
/coding test practice/Full Search/소수 찾기.py
768
4.1875
4
""" problem link : https://programmers.co.kr/learn/courses/30/lessons/42839?language=python3 """ import math from typing import List from itertools import permutations def is_prime_number(n: int) -> bool: if n == 1 or n % 2 == 0: return False k = math.sqrt(n) i = 3 while i <= k: if ...
9c70e9f7e9fb171752a67d909b5f96762fee9ec2
TangDL/python100days
/leetcode/isMatch.py
437
3.578125
4
class Solution: def isMatch(self, s: str, p: str): if not p: return not s firstmatch = len(s)>=1 and (s[0]==p[0] or p[0]=='.') if len(p)>=2 and p[1] == '*': return self.isMatch(s, p[2:]) or (firstmatch and self.isMatch(s[1:], p)) else: return firstmatch and sel...
e2b836f5351599909a45e9d67d5b3f44009587c8
companyabab/Dhanu
/fib.py
339
3.515625
4
import datetime mydate = datetime.date(1943,3, 13) #year, month, day print (mydate.strftime("%A")) print ("dhanu") print ("auto triggring this time") print ("lets try this time") print ("one more time ") print ("success") print ("CI CD") print ("testing") print ("test1") print ("testing slack") print ("testing") prin...
4431bc1ff29c1756cadfe72deb800d517b0dc6c5
vinaysannaiah/Python-
/Simple/Write_to_File.py
936
4.65625
5
# This code is about how to write to a file: #there are many ways: #To replace the existing lines in the File #to append the lines in the file # Write to a file: Rewrite the existing lines text = "Writing to a file" #Create a file if there is none or use the existing file. #The file can be of any format saveFile = o...
41403e637d790297d3fc1045af4b7f33e4acf3be
Vital-Fernandez/vital_tests
/security_checks/pandas_saving_txt.py
416
3.96875
4
import pandas as pd from pandas_indexing import modifying_df, XY # Initialize data of lists data = [{'a':4, 'b': 2, 'c': 3}, {'a': 10, 'b': 20, 'c': 30}] # Creates pandas DataFrame by passing df = pd.DataFrame(data, index=['first', 'second']) print(df) modifying_df(df) print(df) x, y = None, 1 my_values = XY(x, y)...
63ad64496277f084a53971581d97cf584ad21d5c
weih201/code-repos
/python repo/Mapreduce/join.py
723
3.625
4
import MapReduce import sys """ Word Count Example in the Simple Python MapReduce Framework """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # key: id mr.emit_intermediate(record[1], record) def reducer(key, list_of_record): # key: id ...
6af7ebbac45dbc01feb2c313b898b716a81d888a
subham1994/Algorithms
/Graphs/connectivity.py
1,172
3.984375
4
from Graphs.graph_builder import build_undirected_graph ''' connectivity in undirected graphs - Vertices V and W are connected if there is a path between them. - Preprocess graph to answer queries of the form `is V connected to w` in constant. - `is connected to` relation is an Equivalence relation(Reflexive, S...
3b8aa06942b7e1b01a10315ed6d12f51e9553378
Yao-9/LeetCode150
/Python/stringMani/lengthOfLastWord.py
236
3.578125
4
class Solution: # @param s, a string # @return an integer def lengthOfLastWord(self, s): l_split = s.split() if not l_split: return 0 else: return len(l_split[-1]) A = Solution() print A.lengthOfLastWord(" ")
6800825a0ee932fc8ac3c8461a1b1e9cd8995cf2
germandouce/Computacion
/Exámenes/Parcialito 3.2 4-12-20 Estructuras de datos simples 2.py
1,633
3.78125
4
'''Realizar un programa en PYTHON que permita generar aleatoriamente 20 números pares entre 0 y 100 y determinar cuántos vinieron repetidos (se considera repetición desde la segunda aparición del número en adelante), cuántos fueron por debajo del número 50; cuántos mayores o iguales a 50 (estos últimos incluyendo rep...
9de69d1312d7d5c638086613345931084b173328
kaashdesai1/Data-Structures
/A3/bst.py
2,326
3.96875
4
#!/usr/bin/python import random #Node for tree class Node: def __init__(self, x): self.element = x self.leftchild = None self.rightchild = None class Dictionary: def __init__(self): self.root = Node(None) #to count number of nodes to a node self.path = 0 d...
abc704d0fd64f84192510f8e87b8b967d8217adf
thevur0/Python
/Practice/DataStruct.py
1,801
3.828125
4
edward = ['Edward Gumby', 42] print (edward) john = ['John Smith', 50] database = [edward, john] print(database) #索引 greeting = 'Hello' print(greeting[0], greeting[-1]) #切片 months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October...
25519e2ec15e3633a406009d1a2805950d0f3873
Gfuqiang/obj
/compute/sort/mergesort.py
1,235
3.90625
4
""" 归并排序: 分治思想 https://mp.weixin.qq.com/s/YY63D6ZkC4Jhon2H6-ZAKw https://www.cnblogs.com/shierlou-123/p/11310040.html """ def merge_sor(list_data: list) -> list: # 将列表拆分为只有一个元素 if len(list_data) <= 1: return list_data meddle = len(list_data) // 2 # 这里递归将列表一分为2,直到无法继续分割 left_lis...
fa5dba2ea418df59a20c12ffd2e1d5a2881f37eb
abhishekdesai1990/python-oops
/oop4-class-inheritance.py
1,588
3.578125
4
class Employee: hike_percent = 0.4 # This is a class variable and can be shared acrross all the instance def __init__(self, first, last, pay): self.first = first #this are instance variables self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' ...
194d8baac99a81715d8b835f0383a329749f5a03
paulsavoie/wikiwsd
/wsd/wikipedia/wikipediapreprocessor.py
12,560
3.71875
4
import threading import Queue import logging WAIT_QUEUE_TIMEOUT = 2 # in seconds class WikipediaPreProcessor(threading.Thread): '''The WikipediaPreProcessor class preprocesses text and removes tags, unnecessary links and other information and keeps the text only ''' '''constructor @param i...
fa205f354edd95df53c7dcfa2078e405b8be2e07
shahpriyesh/PracticeCode
/SlidingWindow/SlidingWindowMaximum.py
1,274
3.875
4
from collections import deque class SlidingWindowMaximum: def slidingWindowMaximum(self, nums, k): # This queue maintains indices of elements from biggest to smallest qi = deque() # insert the first biggest element in first k elements for i in range(k): while qi and num...
5b736d700f1fbbccce8a46e40a1bc3aa58e29503
07160710/PythonPractice
/shurushuchu/shuchu_test_py3.py
831
3.53125
4
# pyhon3.x 输出 import sys from time import sleep # 输出一个值 print(123) #输出变量 num = 10 print(num) # 输出多个变量 num2 = 66 print(num, num2) # 格式化输出 name = "kf" age = 20 # 我的名字是xxx,年龄是xx print("我的名字是" ,name , ",年龄是",age) print("我的名字是%s,年龄是%d"%(name,age)) print("我的名字是{0}",",年龄是{1}".format(name, age)) # 输出到文件中 f = open("test3.txt","...
9064201584aed56deaaaca90dfa7a40d2f0bc871
GeekyBoy13/Mandelbrot
/fun.py
1,321
3.734375
4
import itertools import matplotlib.pyplot as plt # Takes the square of a complex number x + yi. def complexy(x,y): a=x b=y x=a**2 - b**2 y=2 * a * b return x,y # Determines whether the point x + yi is in the Mandelbrot Set def run2(x,y): count = 0 c=x d=y try: while count <...
8c31296e32503cb92e745f5187cec4699f42756b
MrHamdulay/csc3-capstone
/examples/data/Assignment_5/rmlden001/mymath.py
470
4.15625
4
#DENISHA RAMALOO #mYMATH #ASSIGNMENT5 def get_integer(x):#creating function to apply to either variable n or k t = input ("Enter "+x+":\n")#for input use + instead of , while not t.isdigit (): t =input ("Enter "+x+":\n") t= eval(t) return t #return the value you are working with d...
c255d3cc0745bce4a552ed90c94ffe7c048e9dda
shenhaizhumin/myrepository
/application/util/date_util.py
879
3.578125
4
from datetime import datetime, timedelta # value 为 python 中的 datetime 类型数据 def released_time(value): """自定义发布时间过滤器""" created_time = value.timestamp() # 把发布时间转换成秒级时间戳 now_time = datetime.now().timestamp() # 获取当前时间戳(秒级) duration = now_time - created_time if duration < 60: # 小于一分钟 display...
728863cf9a4bcfabbe4834d2a0d3772f15cb09f6
vaibhavg12/Problem-Solving-in-Data-Structures-Algorithms-using-Python3
/Algorithms/2 Version/treeLevelOrderSpial.py
5,869
3.609375
4
from collections import deque class Tree(object): class Node(object): def __init__(self, v, l=None, r=None): self.value = v self.lChild = l self.rChild = r def __init__(self): self.root = None def levelOrderBinaryTree(self, arr): self.root =...
837e24ecd7f156750ff70729363fca6340616d16
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/48_11.py
3,523
4.125
4
Python – Extract ith Key’s Value of K’s Maximum value dictionary Given Dictionary List, extract i’th keys value depending upon Kth key’s maximum value. > **Input** : test_list = [{“Gfg” : 3, “is” : 9, “best” : 10}, {“Gfg” : 8, > “is” : 11, “best” : 19}, {“Gfg” : 9, “is” : 16, “best” : 1}], K = “best”, i >...
efe7bd94af4e287bb5a7f6dbd19e64def60bc250
VincentDion/Project3OC
/classes.py
5,473
3.984375
4
# -*- coding: Utf-8 -* """Classes for the game MacGyver escapes !""" import pygame from pygame.locals import * from constants import * class Level: """ Creation of level class """ def __init__(self, file): """ Initialization of the Level class """ self.file = file ...
dbb18d8bf587a07c7b4948d240c5a4165de8e764
zachRudz/60-425_a1_miningFrequentItemsets
/pcy.py
6,835
3.609375
4
import datetime import my_hashmap as hm from collections import defaultdict DEBUG = True def a_priori(input_file, num_baskets, support_threshold): min_required_occurrences = num_baskets * support_threshold if DEBUG: print("Minimum number of occurrences to be considered frequent: {}".format(min_require...
641ee69833689bc8716ff8b1d6349f0589456423
jason12360/AID1803
/pbase/day03/day03practise03.py
193
3.75
4
# 1.输入一个数,用变量x绑定,根据x的值打印x行,hello world # 用while语句来左 x = int(input('请输入一个数')) while x > 0: x -= 1 print('hello world')
ceefd6cc5551cfce0ba12bb3f3ab2dfae991d17f
aaron0215/Projects
/Python/HW4/primes.py
970
4.1875
4
#Aaron Zhang #CS021 Green group #This is a program to check whether input number is prime #Lead user to input a number is more than 1 #Use modulus symbol to defind whether a number is prime #When finding the number is not prime, the calculation will be terminated #If there is no number can be divided, output prim...
27a875a9d4c411a9e50a180663df270d00f2790f
TvBMcMaster/gsa_election_validation
/validate_election_results.py
8,248
3.515625
4
''' Validate GSA Election Results from Google Forms with verified student lists provided by university ''' import os import sys import csv from datetime import datetime DEFAULT_OUTPUT_DIR = "validation_results_{}".format(datetime.now().strftime('%Y%m%d')) class InvalidCSVFileError(Exception): pass class StudentLis...
c0130afe62bc6752d68640c1000ce22f2c2785ed
rodneycagle/hello-world
/TurtleNuminput.py
525
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 28 10:43:01 2020 @author: cagle_restricted """ import turtle turtle.bye() t = turtle.getturtle() t.color("green", "red") t.width(5) size = int(turtle.numinput("Triangle Size","What size triangle do you want?",300,100,560)) # intitialize turtle ...
7aa0a393be321bc1f7ab7b7a246018f2d472db81
yurisimao/PYTHON-INIT-PROJECTS
/enumerate.py
121
3.765625
4
any_list = ["bola", "acabate", "cachorro"] for i, nome in enumerate(any_list): #Trás o indice e o valor print(i, nome)
9c84ba4f7d53940ca2a8f0e35204579e17e1915f
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/68_2.py
2,886
4.5
4
Python – Change Datatype of Tuple Values Sometimes, while working with set of records, we can have a problem in which we need to perform a data type change of values of tuples, which are in its 2nd position, i.e value position. This kind of problem can occur in all domains that include data manipulations. Let...
30881807f0a8abe800313c8afb956ac0aa23d7ff
coolboy-ccp/PythonLearn
/Base/Base1.py
1,754
4.09375
4
# 高级特性 #切片 def testSlice(): nums = [1,2,3,4,5,6,7] print(nums[:3]) print(nums[1:3]) print(nums[-2:]) #前六个数,每两个截取一个 print(nums[:6:2]) #迭代 def testIteration(): dict = {'a':1, 'b':2, 'c':3} keys = '' values = '' kvs = '' for key in dict: keys = keys + key + ',' fo...
9c496cfadc8c3bdb5ed6dea52977adccd8ff62ac
eurisko-us/games-cohort-1
/tic-tac-toe/strategy.py
986
3.5625
4
import random from game import Game from minimax import Minimax class TestStrategy: def __init__(self,player_num): self.player_num = player_num def move(self,current_game): for x in range(len(current_game)): for y in range(len(current_game[0])): if current_game[x][y...
fbb71f5944888557b27d1876debe2dcf5550f010
dixit5sharma/Learn-Basic-Python
/Ch3_Functions_2.py
158
3.984375
4
def avg(a,b): av=(a+b)/2 return av p=int(input("Enter number 1 : ")) q=int(input("Enter number 2 : ")) r=avg(p,q) print("Average of",p,"&",q,"=",r)
7b2c4bc7489f836c4e8f9c1801d1c184059ca393
cfezequiel/ai-project1-main
/Road.py
3,393
3.984375
4
#!/usr/bin/python # # # # /file Road.py # # Copyright (c) 2012 # # Benjamin Geiger <begeiger@mail.usf.edu> # Carlos Ezequiel <cfezequiel@mail.usf.edu> from math import cos, sin, atan2 import GraphUtil class Road (object): """Represents the connection between two City objects.""" def __init__ (self, or...
7bd2a2193914cf222db6810fa16a61f07820957c
anjalirmenon/sierpinski
/sierpfract.py
849
3.5625
4
# sierpinski using any coordinates of screen import pygame black = (0,0,0) screen = pygame.display.set_mode((1000,1000)) screen.fill(black) def midpoint(x,y): midx = (x[0] + y[0])/2.0 midy = (x[1] + y[1])/2.0 return (midx,midy) #line_draw(screen,(x1,y1),(x2,y2)) # centrx = x2 # centry = y2 def tri(screen,red,x,y,...
b0b45d5251c9abc315cb1f78d474e645d9ee6a0f
artemiygordienko/itmo-python
/lesson-01.py
2,476
3.71875
4
who = 'Python' print('Hello,',who) # простые (Скалярные) типы данных """ - целые числа - int - дробные числа - float - комплексные числа - complex - логические флаги - bool - строки - str, bytes """ i1 = 1 i2 = -2 i3 = 0b010101 # двоичная i4 = 0o455 # восьмеричная i5 = 0xaa # шестн...
d790e69d3cc0748e5082013bae119a15be23c7fe
adamhartleb/python_workout
/2_strings/exercise_7.py
210
3.71875
4
def translate(letter): vowels = 'aeiou' if letter in vowels: return 'ub' + letter return letter def ubbi_dubbi(word): return ''.join(map(translate, word)) print(ubbi_dubbi('elephant'))
6f633d3cadca4aa24dfdbf28424410295d1691da
yashshah4/Data-Science-Projects
/Miscellaneous/Collatz.py
390
4.1875
4
def collatz(number): if number%2 == 0: print (number//2) return (number//2) else: print (number*3+1) return (number*3+1) try: n = int(input("Enter a number : ")) p=n while True: p = collatz(p) if p == 1: break else: co...
665996f24ef2a1258a51c11eaacada885b331752
Supriyapandhre/Test-Repository
/OOPS_concepts/data_hiding.py
1,870
4.375
4
""" Data hiding in python is to show the intention to hide the data, but actually we don't hide the data. _ : (single underscore) __ : (double underscore) """ class student: # Write class documentation """ This class contains all information about the student, which includes name, phone, email, address ...
f4033b1246f8b2843f400c162433b8f55bd993b5
anweshachakraborty17/Python_Bootcamp
/P66_Check if a key exists.py
261
4.21875
4
#Check if a key exists thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary") #Yes, 'model' is one of the keys in the thisdict dictionary
061eb67854c629786d82b2c0eedcd77240448f22
ABHIINAV12/project-euler
/Summation of primes.py
251
3.859375
4
def isprime(a): if a==2: return 1 if a%2==0: return 0 curr=2 while(curr*curr<=a): if a%curr==0: return 0 curr+=1 return 1 def main(): ans=0 for i in range(2,2000000): if isprime(i): ans+=i print(ans) main()
1c7bf5132ff29eba70a4ad350fb5bf11e9b6dbeb
david-xander/Algorithms-Practice-python
/sorting/sort_the_hard_way.py
634
3.890625
4
def main(): data=[5,4,1,8,7,2,6,3] print('HARD WAY SORTING ', data, ': ', hardway(data)) def hardway(data): # # INPUT (list) # O(n**2) # res=[] for item in data: if len(res)==0: res.append(item) else: inserted=False for index, subitem...
687d11173a44690ba38f568ed163dc0d9fa9fe19
Katsiarynka/Algorithms
/tree.py
740
3.53125
4
# coding:utf-8 from collections import deque class TreeNode(object): def __init__(self, val): self.val = val self.left, self.right = None, None def __repr__(self): return '%s (%s %s)' % (self.val, self.left or '', self.right or '') def constructTreeFromList(nodes): print nodes if not nodes: return r...
35fac3e7a78031f4637ee6dc3762ba5a64c706fb
raymondhfeng/raymondhfeng.github.io
/data_structures_and_algorithms/moderate.py
1,370
3.609375
4
def swap(): # swaps two elements in place without using a temprorary variable a = 10 b = 15 a = a+b b = a-b a = a-b def countZeroes(n): # computes the number of trailing zeros in n factorial currPower = 1 counter = 0 while pow(5,currPower) <= n: multiple = 1 while multiple*pow(5,currPower) <= n: counter...
5e2137abdb3a2d23e265f1a965347d4a0d0767e6
JPogodzinski/RSA
/RSA.py
1,512
3.859375
4
import random import time def isPrime(n): for i in range(2, int(n ** 0.5) + 1): if n % i == 0: return False return True def GCD(x, y): while y != 0: pom = y y = x % y x = pom return x def isCoPrime(x, y): if GCD(x, y) == 1: return True re...
bcd7fdf86ac33a625f369e33a68c610ba9e3b8d8
mayconkwutke/Python-Fundation-26-Abr-a-06Mai
/AT-DIA-02/Aula2.py
4,778
3.765625
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 27 19:17:10 2021 @author: Maycon """ import os # Exercicio 1 - Escreva um programa python que escreva na tela o texto abaixo # com a saída de exemplo, usando somente 1 comando print: ## Twinkle, twinkle, little star, How I wonder what you are! Up above the ## wo...
54acadc2fb5af27b386dd4ead0cbfcdd62492a53
kirane61/letsUpgrade
/Day3/ContactBook.py
526
3.796875
4
#Contact Book howManyContact = int(input("Enter the number of contacts you want to add: ")) contactDictionary = {} for i in range(0,howManyContact): name = input("Enter Name:") number1 = input("Enter number1:") number2 = input("Enter number2:") imageurl = input("Enter imageUrl:") email = input("Enter emai...
3ddfecb6576243b6a361e7583d7f4e68a76ea73c
whywhs/Leetcode
/Leetcode127_M.py
1,478
3.65625
4
# 单词接龙。这个题目是典型的广度优先搜索题目。值得学习的地方有两个,一个是双向BFS,另一个是set操作。 # 双向BFS。即从前往后,从后往前均进行BFS,当一方的BFS结果大于另一方,则改从小的一方继续进行。 # set操作。a={'ccc'}这个定义就是一个set变量。然后set是有len的操作,同时set的加是add,set的减是remove,set的update是迭代的加入变量。 class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str...
161d7c4aa979390dc29d03ca6a7a87f2093cd1a9
shankar7791/MI-10-DevOps
/Personel/AATIF/Assesment/01-MAR/nummatch.py
236
3.671875
4
li = numberList print("Given list is ", numberList) firstElement = numberList[0] lastElement = numberList[-1] if (firstElement == lastElement) return True else return False numList = [10, 20, 30, 40, 10] print("result is", li(numList))
354b81f408c0b2aac776b55920f1252c9155ba21
nitsas/py3datastructs
/dict_heap.py
2,527
4.125
4
""" A pseudo-heap implemented using a dictionary. Operations: - __len__ - insert - pop / pop_min - peek / find_min - decrease_key I use this until I find the time to implement a Fibonacci heap. Author: Christos Nitsas (nitsas) (chrisnitsas) Language: Python 3(.4) Date: August, 2014 """ __all__ ...
a201c66eac73e8c930465612672dbcfdac138ebe
Aditi1203/CMPE-295
/Dataset_CYBHi/SegmentedScalogramFromCSV.py
3,805
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: """ Script to generate Scalograms from CSV files. 1. Change variable path to folder loacation of the dataset. 2. Change variable path1 to path+/Scalogram 3. Change number of items Tip: If program crashes, and ...
14fa5284e40a1e254b709e0e5d44202d3b61be59
dylcruz/Python_Crash_Course
/chapter 7/whileDictionaries.py
928
3.703125
4
unconfirmed_users = ['alice', 'brian', 'candace'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() print("Verifying user: " + current_user.title()) confirmed_users.append(current_user) print("\nThe following users have been confirmed:") for user in confirmed_users: print(user.t...
87f5f7f5da418e8d1dfb0413229658e668e5eee9
pisces0009/PythonProgram
/hamburger7.py
2,572
4.1875
4
############################################################## # fILE: humberger7.py # Author: Prasad Kale # Date: january.24,2018 # Purpose:Calculating cost or burgers, drinks and french fries ############################################################## # print headings print("\n ... Hamburger 7 ....") print("====...
c125e75056756b38768472bc67e1094603be5453
carlosmontoyargz/Introduction-to-Algorithms
/Foundations/Find-Maximum-Subarray-Lineal.py
1,104
4
4
#!/usr/bin/python """Programa que encuentra la mayor subsecuencia dentro de un arreglo. A diferencia de la version recursiva, este algoritmo se ejecuta en tiempo lineal. """ def FindMaximumSubarray(A): """Encuentra la mayor subsecuencia dentro de la lista A. Si se recibe una lista vacia se lanza una excepci...
d985eb10992757ffe787a228ccf70c8536a2dd4e
yuuuhui/Basic-python-answers
/梁勇版_6.5.py
985
4.15625
4
num1,num2,num3 = eval(input("Enter three numbers as x,y,z:")) def sort(num1,num2,num3): if num1 <= num2 and num1 <= num3: print(num1,end = " ") if num2 <= num3: print(num2,end = " ") print(num3,end = " ") elif num3 < num2: print(num3,end = " ") ...
93ad90574a520db5c75ad77c773bd45f9bf3801b
MaryanneNjeri/pythonModules
/.history/robort_20200727110140.py
550
3.890625
4
def uniquePaths(m,n): # use dynamic programming and answer is at arr[m][n] # let's create and empty grid with 0's grid = [[0 for x in range(m)] for y in range(n)] print(grid) # then using the top down uproach we shall prefill all the # i,j i = 0 and j+1 # then i +1 ,j = 0 for i in r...
d692240c2fbea8c09d39fad50598d96ffd5af3a2
swj8905/Onlie_Live_0529
/03_곱셈 계산기.py
170
3.578125
4
num1 = int(input("첫번째 숫자 >> ")) # int() : 문자열 --> 정수형 num2 = int(input("두번째 숫자 >> ")) print(f"곱셈 결과는 {num1 * num2}입니다.")
bdaf8cdd71d6f31b1bb9f4ca00fd90bb997e410e
Maxwell-Hunt/NEAT
/Main.py
1,066
3.625
4
from Population import Population from Network import Network from math import floor ################################# class Player: def __init__(self,brain=None): self.brain = None if(brain == None): self.brain = Network(2,1) else: self.brain = brain ...
5e7d16c58fcf416397368706b7e9296831f5d0df
masset151/Grupo-5---Entorno-Servidor
/Sprint 2/Individual/Andres Masset/Practica_02.py
3,147
3.578125
4
import math # ========================================================== # Desarrollo Web - Entorno Servidor # Ciclo Superior Desarrollo Web # Curso 2020-21 # Segunda práctica # =========================================================== # APELLIDOS, NOMBRE: # DNI: # Práctica 2: Programación orientada a objetos #...
58523e7fa797343e7995a7d35ec1f2f85dc0245c
nullgad/learnPython
/working_scripts/quadraticEquation.py
1,155
4.28125
4
#How to find the root of a quadratic equation #the equation is (-b+sqrt((sqr(b)-4*a*c)))/2a and (-b-sqrt((sqr(b)-4*a*c)))/2a # import math print("\n\n\nSimple Calculatr to find the Root of a Quadatic Eqution!..\n\n\n") print("The Quadratic equation is (ax^2)+bx+c where a not= 0\n\n\n") a=int(input("Enter the value of...
c34f427615f0189fc9251ab686510c5b687f24ce
loqum/Curso-Python
/Tema13_Ejercicio1.py
1,014
3.890625
4
import sqlite3 NAME_TABLE = "Coches" def get_connection(name_db): return sqlite3.connect(name_db) def create_table(cursor, name_table): cursor.execute(name_table) def insert_table(db_connection, cursor, name_table, item): cursor.execute("INSERT INTO " + name_table + " VALUES (" + item + ")") db_c...
231ce3073491d5f42fc20753bb916a1827963829
AhmedRaafat14/CodeForces-Div.2A
/118A - StringTask.py
1,743
3.59375
4
""" Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: 1. deletes all the vowels, 2. inserts a character "." before each consonant ...
ce9a0aaccc2591e315565500719b295eeefef2ef
EinarPall/skoli
/assignment 5/ass5.py
1,094
4.03125
4
# Assignment 5 # dæmi 1 # Algorithm that finds the maximum positive interger input by user. # The user repeatedly inputs numbers until a negative value is entered. # num_int = int(input("Input a number: ")) # Do not change this line # # Fill in the missing code # max_int = 0 # while num_int >= 0: # if num_int...
163003d9beff3d1eadb5a7c7cc2e819323373563
ITAM-Coding-Rush/Coding-Rush-19
/semana1/CR19-El-numero-perfecto/solutions/90.py
274
3.59375
4
n = int(input()) if n == 0: print("No es perfecto") else: if n < 0: n = - n sumadiv = 0 for i in range(1, n): if n % i == 0: sumadiv += i if n == sumadiv: print("Es perfecto") else: print("No es perfecto")
53180a05ec22042a9a4cf965b154107e90015936
Android-Ale/PracticePython
/mundo3/Teste.py
1,484
4.15625
4
print("PADARIA ELIZA MARTINEZ") print("Digite 'A' para refrigerante") print("Digite 'B' para salgados") b = input('O que você deseja ?') if b == 'A' or b == 'a': print('Refrigerantes:') print('Guarana Antartica [1]') print('Coca Cola [2]') print('Fanta [3]') print('Dole Guarana [4]') print('Peps...
37979080cc5065fb552bee1e10cecd027191ab47
lm-t/cs9h
/unit_converter.py
2,058
4.25
4
'Project 2a: Unit Converter' print '''\n\t\tUnit Converter by Luis Torres You can convert Distances , Weights , and Volumes to one another, but only within units of the same category, which are shown below.''' print "Input your measurements to convert in the following format '1 ft in m'." print '''\n Distances: ft cm ...
d10d37582ad0ec2b2c7b28e5e95f6af80d266344
gitMan2019/Python-Java-work
/randomness_perpetua.py
6,143
3.84375
4
# Randomness Perpetua """ Pygame base template for opening a window Sample Python/Pygame Programs Simpson College Computer Science http://programarcadegames.com/ http://simpson.edu/computer-science/ Explanation video: http://youtu.be/vRB_983kUMc """ import pygame PI = 3.14159 # Define some co...
4bc69bebf504e10b27a568bed254db2896212f4f
Chantlog/Python-Projects
/guess.py
396
4.09375
4
import random number = random.randrange(0,100) guessedCorrectly = False while guessedCorrectly == False: guessed = int(input("Guess the number between 1-100: ")) if(number < guessed): print("\n Number is lower, try again") elif(number > guessed): print("\n Number is higher, try again!") ...
2dcfc8ecf8614461b800adc3650aaab0b451f4df
rsacpp/misc
/qsort.py
1,658
3.515625
4
import random def swap(arr, indexA, indexB): if indexA == indexB: return if arr[indexA] == arr[indexB]: return arr[indexA], arr[indexB] = arr[indexB], arr[indexA] def sort(arr, fromIndex, toIndex): if fromIndex >= toIndex: return if fromIndex + 1 == toIndex: if arr[...
868851d699cb9b593142970c0a465c39526967dd
shubhamsahu02/cspp1-assignments
/M5/p3/square_root_bisection.py
493
4
4
# Write a python program to find the square root of the given number # using approximation method # testcase 1 # input: 25 # output: 4.999999999999998 """Square root bisection""" # testcase 2 # input: 49 # output: 6.999999999999991 INPUT_STRING = int(input()) EPSI_LON = 0.01 LOW = 0 HIGH = INPUT_STRING GUESS = (LOW+HI...
ffd0be2fd32b1a1d6f85f29328de95758752ec40
DamoM73/work-projects
/progress_report.py
1,496
3.625
4
import csv class Student: def __init__(self, given_name, family_name, email): self.given_name = given_name self.family_name = family_name self.email = email self.activities = [] def print_student(self): print(self.given_name, self.family_name, self.email, end=" ") ...
a1542ee2517d421da24428a2860b162a17ca4be1
berdoezt/Python-Challenge
/solution/15.py
169
3.5625
4
#!/usr/bin/python import calendar for i in range(1000, 2000): if calendar.isleap(i): c = calendar.monthcalendar(i, 1) if c[0][3] == 1 and i % 10 == 6: print i
ef0b6f85a08479e5ac92c5f6083343309e176868
MaKToff/SPbSU_Homeworks
/Semester 5/Formal languages/tester.py
2,246
3.671875
4
""" Tester for grammar. Authors: Mikhail Kita, Sharganov Artem """ import sys # Reads grammar rules from specified file. def load_grammar(filename): grammar = [] with open(filename, 'r') as f: text = f.readlines() for line in text: left, right = line.split(" -> ") r...
6a2e2187371783d05ebb7da65ebc70bc9a701c8b
Byliguel/python1-exo7
/code/chaines/chaines_code_2_2.py
565
3.59375
4
def transforme_en_latin_cochon(mot): """ Transforme un mot en latin-cochon Entrée : un mot (une chaîne de caractères) Sortie : le mot transformé en latin cochon s'il commence par une consonne. """ premiere_lettre = mot[0] reste_mot = mot[1:len(mot)] if premiere_lettre not in ["A", "E", "I", "...
9cd01f030efd169e4e0eb5c5ca5398aa2ad603c7
addyp1911/Python-week-1-2-3
/python/Algorithms/VendingMachine/VendingMachineBL.py
663
4
4
# ----------------------------------vendingmachine prg----------------------------------------------- # VendingMachine.py # date : 26/08/2019 # method to calculate the minimum number of Notes as well as the Notes to be returned by the Vending Machine as change def calculateChange(bill): notes=[1000,500,100,50,20...
b80f95f63b86c7553be512216c44ec5cd5ba5d66
luisnarvaez19/Proyectos_Python
/edu/cursoLN/funciones/1- args_por_default.py
192
3.515625
4
''' Created on Agosto 18, 2019 modified on April 16, 2020 Funciones y argumentos por defecto @author: luis. ''' i = 5 def f(arg=i): print(arg) i = 6 f() # +58414-2840599 Pydroid 3
61c854db7b0a9f7be7a8186215faddf5ff40a83a
bblinder/home-brews
/threader_app.py
1,817
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Turns a twitter thread URL into a thethreaderapp.com URL for easier reading""" import argparse import sys import requests parser = argparse.ArgumentParser(description="Get the thread ID from a twitter URL") parser.add_argument("url", help="the URL of the thread") ar...
5f9d45a2fad20d9eb2bf9fcf13eb57fe52ecb0a8
wanghan79/2020_Python
/2018012956韩旭作业/结课作业.py
2,105
3.5
4
# -*- coding: utf-8 -*- import random import string import pymongo def gen_random(dtype, num, datatange=(10, 1000), str_num=8): """ 随机数生成 :return: """ try: start, end = datatange if dtype is int: return [random.choice(range(start, end + 1)) for _ in rang...
d79ec35400af3d79f22d65d1e51e9793c5912c02
MonikaSophin/python_base
/2.1 number.py
1,882
3.546875
4
import math; import random; """ 2.1 基本数据类型 -- Number(数字) """ ## 赋值与删除 a = 1 print(a) del a ## 数字类型转换 a = 1.0 print(a) a = int(a) print(a) a = float(a) print(a) a = complex(a) print(a) ## 数字运算 a, b = 3 , 2 print(a + b) print(a - b) print(a * b) print(a / b) print(a // b) #取整余 print(a ** b) #幂乘 ## 数字常量 print("pi =", ...
f931efaaf6ee632d5adc6f331b7ed7239d8e4681
DarkEnergySurvey/despyServiceAccess
/bin/serviceAccess
2,090
3.8125
4
#!/usr/bin/env python3 """ serviceAccess -- print information from a service access file syntax: serviceAccess [-l] [-f file] [-s section | -t tag] format Format is a string format string drawing items from a python dictionary. Python dictionary formats are of the form %(key-i-ndictionary)s . ...
56462a189bd159affccf95bc8555fa7f5deaed3d
aneeshkher/HackerRank
/Mathematics/Strange-Grid/solution.py
265
3.65625
4
# Enter your code here. Read input from STDIN. Print output to STDOUT import math line = raw_input("") r, c = map(int, line.split()) if r % 2 == 0: answer = (int(r/2) - 1)*10 + 1 + (c - 1)*2 else: answer = int(math.floor(r/2))*10 + (c - 1)*2 print answer
84570868fea7b46d7d3a77cb88107e958dc44db5
Huanyu-Liu/pythonLearningScript
/bagels.py
1,890
3.953125
4
import random def getSecretNum(numOfDigit): numberList = list(range(10)) random.shuffle(numberList) secretNum = "" for i in range(numOfDigit): secretNum += str(numberList[i]) return secretNum def getClues(guess, secretNum): clue = [] for i in range(len(guess)): ...
8b0acfd9c3070da288ce4ea548901eec93f15400
Xlszyp/hello
/标准库/双端队列_collections模块/collections方法集合.py
639
3.578125
4
#!/usr/bin/python3 #-*-coding:UTF-8-*- from collections import deque q=deque(range(5)) print('双端队列:',q) #在结尾添加元素 q.append(5) print('添加5到结尾',q) #在开头添加元素 q.appendleft(6) print('添加6到开头',q) #提取出结尾的元素 print('提取末尾元素:',q.pop()) print('末尾元素被提取后的队列:',q) #提取开头的元素 print('提取左边元素:',q.popleft()) print('左边...
831f1154f288b8f78c4c5e759e5b34f97844f144
charleskausihanuni/B2-Group-Project
/Dropdown with Search.py
2,159
3.546875
4
from Tkinter import * import sqlite3 as sql master = Tk() col = StringVar(master) col.set("Colour") option = OptionMenu(master, col,"Any","", "Black", "Blue", "Green", "Red", "Silver", "White") option.pack() loc = StringVar(master) loc.set("Location") option = OptionMenu(master, loc,"Any","", "Birmingham", "Cardi...
14a8d4817ae960425d17a6741b82ceb32ab42c0f
alfir-v10/IntroToCryptography
/stream_cipher/open_file.py
874
3.515625
4
import numpy as np def open_f(file_name): file = open(file_name,'r') f = file.read() s = f.split(',') s = s[:-1] print('Вы выбрали последовательность сгенерированная по методу М-последовательностей. Данный файл содержит последовательность длиной ' + str(len(s))) interval_in_posled = input...
913cb8fae1cdcf4acd63547367304f76c50fa746
ellinx/LC-python
/TheSkylineProblem.py
3,558
3.953125
4
""" A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Now suppose you are given the locations and height of all the buildings as shown on a cityscape photo (Figure A), write a program to output the skyline formed by these buildings collectively...
abb49fdc704f5ceb13af212255c11f6d6bd5ac2d
AFigaro/Power-indices
/utils/preprocessing.py
2,181
3.78125
4
# The functions to preprocess the excel file to dict format import sys sys.path.append(r'C:\\Python files\\Power indices\\indices') sys.path.append(r'C:\\Python files\\Power indices\\utils') from collections import OrderedDict def dict_construct_over_data(data): '''Create a dictionary from excel file. The exce...