blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
14eea1f6d940a4ee80968989e400f731806012f6
shreyakann/fa20
/assets/slides/fa20/11-Midterm_Review.py
1,331
4.09375
4
# Fall 2018 Midterm # This relies on "string slicing", something we haven't talked about this year. # s[0] is the first item # s[1:] is the second item until the end # s[start:end:step] to slice items. End is exclusive. def match(a, b): """Detect a match (a==b). Return 1 on match, otherwise 0 >>> match("a", "a...
8f03a3c9730403bd7a24e678ebccfd450115a2d8
duhq123/testDjango
/test/geussNubmer.py
686
3.921875
4
import random num = random.randint(1,100000) one = "I'm thinking of a number! Try to guess the number,You are thinking of:" print(one, end="") while 1: guessNumber = input() if guessNumber is not None: if guessNumber.isdigit(): # isdigit 判断输入是否全部为数字 guessNumber = int(guessNumber...
7ca3eccfd6ca4482a5ae388232131f8bad425af8
RainKins/TextBasedGames
/main.py
10,274
4.40625
4
#Rain Kinsey #Lame Game – This program will display a game menu and allow the user to select their desired option #Then, let the user play Make Change, High Card, Deal Hand, Save Dream Cards, Display Dream Cards, Word Guess, or quit. import cardClass import random #Displays menu and runs the program def main(): ...
20ec41b4c1c9dd067fed66326dc3337e4fa343bb
danrodaba/Python_PixelBlack
/Python_PixelBlack/Aprende con Alf/06 Funciones/06media.py
300
4
4
''' Escribir una función que reciba una muestra de números en una lista y devuelva su media. ''' def media(lista): promedio=sum(lista)/len(lista) return promedio lista=[] for i in range(10): lista.append(float(input('Introduce un nuevo valor ({0}): '.format(i+1)))) print(media(lista))
1f4e376bc17b82ec7607824a7b4aa0ada7374be4
ksc5496/hw3python
/main.py
270
3.5625
4
# Author: Krish Choudhary ksc5496@psu.edu def digit_sum(n): if n==0: return 0 else: return int((n%10) + digit_sum(n//10)) def run(): getInp = int(input("Enter an int: ")) print(f"sum of digits of {getInp} is {digit_sum(getInp)}.") if __name__ == "__main__": run()
2cae88755dcad7f3ad3315bed667042ce02c4a4c
dungnguyentien0409/competitive-programming
/Python/22. Generate Parentheses.py
639
3.515625
4
class Solution(object): def generateParenthesis(self, n): """ :type n: int :rtype: List[str] """ def backtrack(res, cur, op, cp): if op == cp == 0: if len(cur) > 0: res.append(cur) return if op == 0: bac...
bd5826ee798b88e98d38cd1ae7818ab819515b31
eman19-meet/YL1-201718
/lab1/lab1.py
449
3.90625
4
import turtle #problem 1: print("eman") print("eman "*3) print("eman "*100) #problem 2: number1=10 print(number1) number2=number1/2 print(number2) #problem 3: my_list=[1,2,3] for i in range(len(my_list)): print(my_list[i]) for k in range(len(my_list)): A+=my_list[k] print(A) #problem 4:...
09fd869d02ed947fd26f4bd607e9f7ff503226f4
WilsonZhong01/testwechat
/timer.py
465
3.59375
4
import threading import time # count = 0 def main(): global count, timer count += 1 print('timer runs every 1 min, and this is the %s' %count +' time') # rebuild timer timer = threading.Timer(1,main) timer.start() def timer_fun(): timer = threading.Timer(1, main) timer....
c67d78034867f9e12a716157ebb4795b0574adef
brady-wang/mac_home
/python/test/test_yield.py
333
4.03125
4
# *_*coding:utf-8 *_* def test(n): print("start") for i in range(1,n+1): print('yield start') yield i*i print("=======i*i========",i*i) print("yield end") item = test(2) item.__next__() item.__next__() a = [1,2,3,4] b = ['a','b','c','d'] print(zip(a,b)) for i,j in zip(a,b): ...
4ef6a6319d0914413c87ee122cb0dd0f58d68570
adriansr/challenges
/codejam/2008/1B. Milkshakes/solve.py
2,844
3.5
4
import sys import itertools class Problem: def __init__(self,nflavors): self.N = nflavors self.customers = [] #self.result = [0] * self.N def addCustomer(self,line): part = map(int,line.split()) num = part[0] constrains = [] for i in xrange(num): ...
822cd5c10e8eff4785ce31659764d35b6198ecd2
rverma23/Compiler
/SeawolfParser.py
24,855
3.5625
4
#!/usr/bin/env python """ AUTHOR: RAHUL VERMA """ import math import operator import string import sys import tpg import traceback import copy d = {} v = {} fd = {} functions = [] funccounter=-1 stackcount = -1 stack = [] class SemanticError(Exception): """ This is the class of the exception that is raised when...
8a6bff166e4c0901e0f69d7289a14b3b1628f00a
moqi112358/leetcode
/solutions/0207-course-schedule/course-schedule.py
3,145
3.953125
4
# There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. # # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # # Given the total number of courses and a list of prerequisite pairs, is it possible fo...
15e8951ad267f02e1fcd9cf34af41a6e12b26f3a
boyang-ml/TSP
/dijkstra/src/dijkstra.py
3,557
3.5625
4
#!/usr/bin/python3 # coding: utf-8 ''' Name: Michael Young Email: michaelyangbo@outlook.com Date: 2019/2/8 Ref.: https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm ''' import networkx as nx import matplotlib.pylab as plt def draw_pic(graph, color_map): # store the edge has been add to G edge = [] ...
b88bb8737c4aa8961f7b74c51e31c203ea883caf
hjh0915/study-python-struction
/search/order_search.py
795
3.828125
4
def sequentialSearch(alist, item): """无序列表的顺序搜索""" pos = 0 found = False while pos < len(alist) and not found: if alist[pos] == item: found = True else: pos = pos + 1 return found def orderdSequentialSearch(alist, item): """有序列表的顺序搜索""" pos = 0 ...
13ac337c86d6fe4a67e30fe1b142b1ebec09aa11
Rubbic/Python
/Unidad07/Errores.py
496
3.953125
4
print("Hola"#Error en sitaxis prin("Hola")#error de nombre #Errores semanticos lista = [1,2,3] for i in range(4): if len(lista)>0: lista.pop() print(lista) else: print("la lista ya esta vacia") """ lista.pop() lista.pop() lista.pop() print(lista) lista.pop() """ ...
f84476a434bc20a53ee311368bdf5a87b4ec66f9
ShiningLo/Hello-Python
/pt.py
537
3.765625
4
def addToInventory(inventory, addedItems): for item in addedItems: inventory.setdefault(item,0) inventory[item]+=1 return inventory pass # your code goes here def displayInventory(dic): count=0 for k,v in dic.items(): print(str(v)+' '+str(k)) count+=v ...
32d321a835debaf977c3996806b364cd8e51d686
keshavkummari/python-nit-7am
/DataTypes/Strings/TRIPLE_QUOTES_1.py
582
4.0625
4
#!/usr/bin/python3 para_str = '''this is a long string that is made up of several lines and non-printable characters such as TAB ( \t ) and they will show up that way when displayed. NEWLINEs within the string, whether explicitly given like this within the brackets [ \n ], or just a NEWLINE within the variable ...
3bd46f443a7edc70d84b34e304368d7f3a3f74ab
hanbinchoi/Python_practice
/judge_import.py
65
3.765625
4
import math as m radius=float(input()) print(radius*radius*m.pi)
e69c7a13efc1f7ce72cfd149919e98ecd16f4580
ducquang2/Python
/Basic_on_HackerRank/string-validators.py
267
3.5
4
if __name__ == '__main__': s = input() print(any(temp.isalnum() for temp in s)) print(any(temp.isalpha() for temp in s)) print(any(temp.isdigit() for temp in s)) print(any(temp.islower() for temp in s)) print(any(temp.isupper() for temp in s))
bb2cae34c0f8373294fe1076460cccb687ba805f
mfmaiafilho/arquivos_python
/Questao3-arvoreBinariaDeBusca.py
2,321
4.15625
4
""" QUESTAO 3 Desenvolva uma árvore binária de Busca em Python. E em seguida nesta mesma árvore binária desenvolva a busca pela chave de número 5. """ import random # NO class Node: def __init__(self, dado): self.dado = dado self.dir = None self.esq = None def __str__(se...
24f7306489a3227a932fd0ad8f6c8c98666c6a8e
chenran1/leetcode
/note/24_交换链表中的节点.py
822
4.03125
4
""" 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。   示例: 给定 1->2->3->4, 你应该返回 2->1->4->3. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = ...
c6a25890053b2c81e03e4df98c01a10125569109
NonCover/-
/leetcode.面试题62.圆圈中最后剩下的数字.py
770
3.640625
4
''' @author:noc @time:2020年3月30日 @url:https://leetcode-cn.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/ ''' ''' 最优解发:参考约瑟夫环问题,因为我们删除至剩下一个数时,这个数必然在数组的 0 位置,然后我们可以反推出这个位置在一开始的位置,这个位置就是最终答案 ''' class Solution: def lastRemaining(self, n: int, m: int) -> int: ret = 0 for i in range(2, n...
13650302c05cbbad870286b9cda4d49dc5c693db
zgcgreat/PRML-1
/prml/neural_networks/layers/relu.py
851
3.84375
4
from .layer import Layer class ReLU(Layer): """ Rectified Linear Unit y = max(x, 0) """ def forward(self, x, training=False): """ element-wise rectified linear transformation Parameters ---------- x : ndarray input Returns ---...
4c6cd85e6f6874deaa73d17e2f39aeda39dffb17
josecaromuentes2019/CursoPython
/practicaGeneradores.py
722
4.09375
4
def numerosPares(numero): num = 1 while num<numero: yield num * 2 num +=1 pares = numerosPares(10) print(next(pares)) print(next(pares)) print(next(pares)) print('') print('') #cuando el parametro es presedido por un * significa que la funncion resibe varios parametros def ciudades(*mis_ciud...
2675627344adb318eda2ab8c1901eae2455ba638
Neelros/Tisn
/ex1 11.py
146
3.65625
4
nb=int(input("Entrer une année")) if nb%400==0 or (nb % 4 == 0 and nb %100 !=0) : print("bissextile") else: print("pas bissextile")
17decb83e449daae6addcce2735bd4c86679f267
eep0x10/Pyton-Basics
/5/py2.py
394
4.1875
4
""" Faça um programa para imprimir: 1 1 2 1 2 3 ..... 1 2 3 ... n para um n informado pelo usuário. Use uma função que receba um valor n inteiro imprima até a n-ésima linha. """ def piramide(n): m=n+1 for i in range(m): k=i+1 for j in r...
51c5e0c750f4e5b1aea3b3ec58c0126a8c1550c8
joeybaba/mywork
/algorithm/shellsort1.py
756
3.84375
4
#!/usr/bin/env python # coding: UTF-8 # https://www.bilibili.com/video/av94166791?from=search&seid=12118334399760597355 def h_sorting(alist, alen, ah): # 做一次排序 i = h = ah while i < alen: key = alist[i] j = i - h while j >= 0 and alist[j] > key: alist[j + h] = alist[j] ...
b5fd3e9e70c31b26df72ba3b29772b4166899fc1
PenelopeJones/conditional_nps
/conditional_nps/encoder.py
2,091
3.5625
4
""" Function for 'encoding' context points (x, y)_i using a fully connected neural network. Input = (x, y)_i; output = r_i. """ import torch.nn as nn import torch.nn.functional as F class Encoder(nn.Module): """The Encoder.""" def __init__(self, input_size, output_size, encoder_n_hidden=4, encoder_hidden_size...
5986e92a96594d13b913bffe59dcd961b7a92a0c
codxse/mitx6001
/2016/WEEK_2/ex2-3.py
718
4
4
false_guess = True _min = 0 _max = 100 initial = 0 str1 = 'Enter \'h\'' str2 = 'to indicate the guess is too high. Enter \'l\' ' str3 = 'to indicate the guess is too low. Enter \'c\' ' str4 = 'to indicate I guessed correctly. ' print('Please think of a number between 0 and 100!') while(false_guess): guess = initia...
230217187af7422d51e61407fb0a632442858d1f
atraore1/poetry-slam-abba
/main.py
694
3.703125
4
from random import choice def get_file_lines(filename): in_file = open(filename, "r") lines = in_file.readlines() in_file.close() return lines def lines_printed_backwards(lines_list): lines_list.reverse() lines_length = len(lines_list) for i in range(lines_length): line = lin...
d883a6bf48aa7fe2c8d6ecfe0ef5b23d319b4b76
FaisanL/simplecode
/calcularDescuento.py
244
3.71875
4
def calcularDescuento(): precio = int(input('ingrese el precio de su producto: ')) descuento = precio * 0.30 print(f'el descuento aplicado es de: {descuento}') ptotal = precio-descuento print(f'El precio total es: {ptotal}')
17320ad79f063d36b3df8292e874392a679c4790
GabrielNagy/Year3Projects
/PE/Lab5/ex1.py
583
3.6875
4
import unittest import unittest.mock class MyClass: def set_string(self): self.string = str(input("Enter string: ")) def to_uppercase(self): return self.string.upper() class Test(unittest.TestCase): def setUp(self): pass def test_capitalization(self): with unittest....
375b0a95524762c849040ed9ab624c6db8bd0890
vivekkhimani/Python_Learning_Practice
/OOP_Basics_and_AdvancesSyntax/ELpractice.py
462
4
4
class EnglishLength: def __init__(self, yards=0, feet=0, inches=0): self.__yards = yards + feet//3 self.__feets = feet + inches//12 self.__inches = inches%12 self.__feets%=3 def __add__ (self,other): return (self.__inches + other.__inches, self.__yards + other.__...
d85f99fed1a3ca00fa2a6693dc76b1bda1931397
HarsimratKohli/Algorithms
/EPI/Chapter 8/10.py
1,416
4.125
4
#not completed class Node: def __init__(self,val): self.val=val self.next =None class LinkedList: def __init__(self): self.head=None def insert(self,val): temp = Node(val) if self.head ==None: self.head= temp else: temp...
aae4fe3990b21268f4e27b59d6cc0aab9386c116
JurgenKniest/TICT-V1PROG-15
/Les 04/Oefening 4_4.py
123
3.671875
4
def f(x): res = x * 2 + 10 return res resultaat =f(2) print (resultaat) y = 4 resultaat1 = f(y) print(resultaat1)
46f42ac972936e179b044b74448e5a944cd2316d
Say10IsMe/SVBA-ED
/Practica 12-Cola Circular (Pop).py
9,221
3.578125
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 16 18:12:36 2018 @author: pc """ cola=[] def metodocreate(): global cola cola=[0,0,0,0,0] global rear global front rear=-1 front=0 print("Se ha creado la cola circular con longitud de 5 espacios") print(cola) #...
f5e200c783d70cf22dca9b62de2b691e338e9d8a
HeyAnirudh/leetcode
/birthday date.py
597
3.984375
4
import datetime from datetime import date import calendar def find(date): born = datetime.datetime.strptime(date, '%d %m %Y').weekday() return (calendar.day_name[born]) i = 0 while i < 2: day = input() month = input() year = input() date = day + " " + month + " " + year day = {1: "Monday...
cc3accd3b0f337605a0d456048c0722f69754a56
medwards147/Udacity_Data_Analyst_Nanodegree
/Project5_Enron_Machine_Learning/final_project/explore_enron_data.py
10,115
3.65625
4
#!/usr/bin/python """ Starter code for exploring the Enron dataset (emails + finances); loads up the dataset (pickled dict of dicts). The dataset has the form: enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that pers...
9886d8035f394f77c7f5891b6ca7fabe38b34d77
RanyellHenrique/exerciciosPython
/colecoesPython01.py
135
3.578125
4
lista = [1, 0, 5, -2, -5, 7] soma = lista[0] + lista[1] + lista[5] print(soma) lista[4] = 100 for numero in lista: print(numero)
f193ec7a8474995fdd361a6777e893d128de4add
Aasthaengg/IBMdataset
/Python_codes/p03285/s996631407.py
123
3.875
4
n=int(input()) if n==4 or n==7 or n==8 or n==11 or n==12 or n==15 or n==16 or n>=18: print("Yes") else: print("No")
adec6702a83b1676b337082d7eab0980b5c71cde
mo7amed3umr/new-task-sbme
/mtplt.py
600
3.53125
4
from numpy import * import plotly as py from plotly.graph_objs import * #just a sphere theta = linspace(0,2*pi,100) phi = linspace(0,pi,100) x = outer(cos(theta),sin(phi)) y = outer(sin(theta),sin(phi)) z = outer(ones(100),cos(phi)) # note this is 2d now data = Data([ Surface( x=x, y=y, z...
0394538f91891e64e90c3df59570df43e76de4a4
dudem8z7l/script-dictionary
/1a.data-preparation/check_missing_data.py
459
3.6875
4
def check_missing_data(data): ''' AIM -> Checking missing data INPUT -> df OUTPUT -> Missing data report ------ ''' # check for any missing data in the df (display in descending order) total = data.isnull().sum().sort_values(ascending = False) percent = (data.isnull()...
c759993e14d199c2628344c82bdba1dd467982c5
ajamanjain/AI-with-WhiteHat-Junior
/Multiplying numbers of the list.py
512
4.15625
4
# Write your code here # Step 1: Define a list with some random numbers num_list = [2,3,7] # Step 2: Get the length of the list using 'len()' function length = len(num_list) # Step 3: Initialize two variables 'i' and 'result' i = 0 result = 1 # Step 4: Iterate while loop till the length of the list while i<length: ...
42f32b19c26c70a351718eabfaf47311cfb87e88
erdos-project/pylot
/pylot/planning/cost_functions.py
5,332
3.84375
4
import math from collections import namedtuple from pylot.planning.utils import BehaviorPlannerState VehicleInfo = namedtuple( "VehicleInfo", [ 'next_speed', # The next vehicle speed. 'target_speed', # The target speed of the vehicle. 'goal_lane', # The id of the goal lane. ...
a6cc83de1050888a021c24c3bab56b0f587e4c99
Hiteshsaai/AlgoExpert-CodingProblems-PythonSolution
/Medium/balancedBrackets.py
1,065
3.609375
4
class Solution: def balancedBrackets(self, string): # Time O(n) || Space O(n) if not string: return True if len(string) == 1: return False validOpenBracket = ["(", "{", "["] validCloseBracket = ["}", "]", ")"] matchingBracket = {")": "(", "]"...
5e8af88e337a7030fb9ea92b57e872d13af2dd7c
mattheuslima/Projetos-Curso_Python
/Exercícios/Ex.89.py
1,134
3.765625
4
dados=list() temp=list() while True: temp.append(str(input('\nDigite o nome do aluno(a): '))) temp.append(float(input('Digite a primeira nota: '))) temp.append(float(input('Digite a segunda nota: '))) temp.append((temp[1]+temp[2])/2) dados.append(temp[:]) temp.clear() opt=str(input('Quer con...
34506b39b4e98bd555c16ac0a50e3342ec832d6f
djshampz/atom
/pY4e/readingFiles/script3.py
145
3.671875
4
fname = input("Enter file name: ") openingFile = open(fname) readFile = openingFile.read() cleanFile = readFile.strip() print(readFile.upper())
729fd16097da24b9ec82222790a3b49c9dad9319
dm464/google-kickstart
/2019-round-a/parcels/solution.py
2,764
3.859375
4
import sys t = int(input()) def manhattan(r1, c1, r2, c2): return abs(r1- r2) + abs(c1 - c2) def hasOffice(r, c, grid, distance): row = len(grid) col = len(grid[0]) if distance == 0: return grid[r][c] elif distance >= (row + col - 2): return False else: quads = [[-1, -...
94edfe3b5629b929c8a8f75c767494b29f822329
Mahantesh1729/python
/Activity_04.py
189
4.0625
4
print("Program to find sum of two numbers") a = int(input("a = ")) b = int(input("b = ")) print(f"{a} + {b} = {a + b}") print("%d + %d = %d" % (a, b, a+b)) print(a, "+", b, "=", a+b)
eb76972e937c710ed4b57482e2b126512333c25f
pavitraponns27/pavitra
/gui/begin/set1/q9/sum of k array.py
94
3.6875
4
array=[1,2,3,4,5] n=int(input(" ")) sum=0 for i in range(n): sum=sum+array[i] print(sum)
ae2bcac65dfd0de8f2ff8d175c2dd80fffdcf302
scps20625/B07090017_2020new
/20200407-1.py
2,320
3.953125
4
#!/usr/bin/env python # coding: utf-8 # # Numpy 套件 # In[1]: a=[1,2,3,4,5] print(a*3) # ## numpy套件的ndarray型態,提供element-wise的操作 # In[3]: import numpy as np b = np.array([1,2,3,4,5]) print(b*3) # In[4]: print(type(b)) print(b.ndim) #ndarray的維度 print(b.shape) #ndarray的形狀 print(b.dtype) #ndarray的資料型態 # In[6]...
e46e1fdfdb9ecc1e379c146e154a8aaaef2e2ca1
MartinTirtawisata/LeVinCoupe
/Regular Project/Association.py
11,885
4.09375
4
import pandas as pd import scipy.stats import seaborn import matplotlib.pyplot as plt from Menu import menu def association(): print("\n===============================================================================") print("a. Volatile Acidity and Wine Quality") print("b. Fixed Acidity and Wine Quality")...
f49fb4d38ff7d65dc9a296834789e7f551a8e11e
sanchaymittal/FarmEasy
/WhatsApp_FarmEasy/env/lib/python3.6/site-packages/multiaddr/exceptions.py
2,283
3.546875
4
class Error(Exception): pass class LookupError(LookupError, Error): pass class ProtocolLookupError(LookupError): """ MultiAddr did not contain a protocol with the requested code """ def __init__(self, proto, string): self.proto = proto self.string = string super(Pro...
a21c23e40bde6d6381ddd273b84afd8159d70e5a
maee-in-mind/python-Exercise-21-onwards
/hangman (1).py
2,085
4.0625
4
from random import randint WORD_LIST = { 'rand_word_1': 'keystone', 'rand_word_2': 'boy', 'rand_word_3': 'girl', 'rand_word_4': 'india', 'rand_word_5': 'third', 'rand_word_6': 'year', 'rand_word_7': 'batch', 'rand_word_8': 'python', 'rand_word_9': 'java', 'rand_word_10': 'dange...
c2dc1325ff1ea886ef9e297b5a71e0754a076c66
rneher/augur
/augur/tree_util.py
1,108
4.125
4
# tree class # each node is a dict in which the key 'children' is used to reference more dicts from io_util import * def tip_descendants(node): """Take node, ie. dict, and return a flattened list of all tips descending from this node""" if 'children' in node: for child in node['children']: for desc in tip_desc...
a3ecbd36cf1782f17da90ae746c08129bdd94b9a
alovena/Cpp
/선택정렬.py
550
4.0625
4
def find_smallest(arr):#최소값 찾는 함수 smallest =arr[0] smallest_index=0 for i in range(1,len(arr)): if arr[i]< smallest: smallest=arr[i] smallest_index =i return smallest_index def selection_sort(arr):# arr : 배열을 매개변수로 입력 받음 newArr=[] for i in range(len...
e2c6db6a14f0e3bb784cb6dace4e6df46c987ec4
daniel-reich/turbo-robot
/uAZcCxNj3TtqvxP34_22.py
965
4.34375
4
""" The _mode_ of a group of numbers is the value (or values) that occur most often (values have to occur more than once). Given a sorted list of numbers, return a list of all modes in ascending order. ### Examples mode([4, 5, 6, 6, 6, 7, 7, 9, 10]) ➞ [6] mode([4, 5, 5, 6, 7, 8, 8, 9, 9]) ➞ [5, 8, 9]...
33882b0ae781a03c6bbe2b0b75c06243be2697b4
lukeyeh/leetcode
/easy_collection/array/remove_duplicates_from_sorted_array.py
1,241
3.875
4
from typing import List # Question # -------------- # Remove Duplicates from Sorted Array # -------------- # # Link # -------------- # https://leetcode.com/problems/remove-duplicates-from-sorted-array/ # -------------- # # Description # -------------- # Given a sorted array nums, remove the duplicates in-place such th...
12778c252b40d075f4bcf488dec2f65f20ab185e
mohammadasim/python-course
/set.py
560
4.15625
4
# Sets are unordered collections of unique elements. # Meaning there can only be one representative of the same object # Set like Maps is represented by {}, however they don't have key:value pair. my_set = {1,2,3,4,5} print(type(my_set)) print(my_set) my_set.add(6) print(my_set) print(len(my_set)) my_list = [1,1,1,2,2,...
6d3bfbb03cad12f994b2442204ba5930797c2016
Shiwank19/p5-examples
/basics/math/polar_to_cartesian.py
868
4.28125
4
# Polar to Cartesian # by Daniel Shiffman # # Python port: Abhik Pal # # Convert a polar coördinate (r, theta) to cartesian (x, y): # # x = r * cos(theta) # y = r * sin(theta) from p5 import * r = None # angle, angular velocity, accleration theta = 0 theta_vel = 0 theta_acc = 0.0001 def setup(): global ...
d373445bd7e1d8ad5216cf2dbac34acfb0c90572
Vedaang-Chopra/Python_Codes_Practiced
/f-20.py
1,701
4.34375
4
# Python program to find maximum sum path # This function returns the sum of elements on maximum path from # beginning to end def maxPathSum(ar1, ar2, m, n): # initialize indexes for ar1[] and ar2[] i, j = 0, 0 # Initialize result and current sum through ar1[] and ar2[] result, sum1, sum2 = 0, 0, 0 ...
5bab8d590bee2e89e6fdec396ffb9835e1cf2b4d
jjudykim/PythonGameProject
/Practice_for_noob/131_140.py
712
3.671875
4
#131 과일 = ["사과", "귤", "수박"] for 변수 in 과일: print(변수) #132 과일 = ["사과", "귤", "수박"] for 변수 in 과일: print("#####") #133 print("A") print("B") print("C") #134 print("출력:", "A") print("출력:", "B") print("출력:", "C") #135 변수 = "A" b = 변수.lower() print("변환:", b) 변수 = "B" b = 변수.lower() print("변환:", b) 변수 = "C" b = 변수.l...
3ebcd7d1661947aba74a58b51d28a7e6fa837793
FooBarQuaxx/exercism-py
/anagram/anagram.py
182
3.734375
4
def detect_anagrams(S, L): return [word for word in L if len(word) == len(S) and S.lower() != word.lower() and sorted(S.lower()) == sorted(word.lower())]
0e737d6ac95b4704da6bef31445490fe9f3eddc3
jereneal20/TIL
/ps/find-nearest-right-node-in-binary-tree.py
727
3.859375
4
# 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 findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]: deq = deque([(roo...
ba5c8ef7661e05446d802c1bd37136e361896987
Ulset/Win-cron-converter
/cron.py
4,909
3.546875
4
from datetime import datetime, timedelta class CronConverter: IS_ALWAYS = "stringFillaBadManKilla" def __init__(self, cron_string, dt_input=None): self.minute, self.hour, self.day_date, self.month, self.day_weekday = cron_string.split(" ") if dt_input is None: dt_input = datetime....
a663522124dde3d849556bd8e5c8c6387c3194c5
wpinheiro77/python
/Estudos/exercicios/L01ex08.py
400
3.90625
4
#Receber a altura do degrau de uma escada e a altura que o usuario deseja alcançar #Calcular quantos degraus o usuário deve subir para atingir a meta degrau = float(input('Digite a altura dos degraus: ')) altura = float(input('Digite a altera que deseja alcançar: ')) qtdDegraus = int(altura / degrau) print('Você ter...
05873fa41e739d41c063907ecf7b871354e05e22
idunnowhy9000/Projects
/SOURCE/Python/Numbers/Next Prime Number.py
684
3.890625
4
# Next Prime Number: Have the program find prime numbers # until the user chooses to stop asking for the next one. # Uses the Lucas–Lehmer primality test, based on http://en.wikipedia.org/wiki/Lucas%E2%80%93Lehmer_primality_test#The_test's pseudocode import math def isPrime(n): s = 4 M = math.pow(2, n) - 1 it = ...
0b9f47d914c63b87ee77e1a8dadb5167837acf06
tima-akulich/lesson8
/homework/task3.py
868
3.875
4
import math class Figure: def square(self): raise NotImplementedError def _get_value(self, other): value = other if isinstance(other, Figure): value = other.square() return value def __lt__(self, other): return self.square() < self._get_value(other) ...
0e17eebc438c942a030d8cd76ca0c51551a5ab27
MonoNazar/MyPy
/0.8/Segment length.py
577
4.09375
4
x1 = int(input()) x2 = int(input()) y1 = int(input()) y2 = int(input()) def distance(x1, y1, x2, y2): s = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 return s print(distance(x1, y1, x2, y2)) # Даны четыре действительных числа: x1, y1, x2, y2. Напишите функцию distance(x1, y1, x2, y2), вычисляющая расстояние м...
59d0b88f2b5b2ab615cb44184b600e77a04c76d4
ruz023/YelpDataChallenge
/src/helpers.py
526
3.65625
4
from typing import * import numpy as np def get_top_values(lst: Iterable, n: int , labels: Dict[int, Any]): #Give a list of values, find the indices with the highest n values #Return the labels for each of the indices return [labels[i] for i in np.argsort(lst)[::-1][:n]] def get_bottom_values(lst: Iterab...
4f38b5a7cf316ec6411af352cf2019a10e75e6a5
yoyonel/OpenCV_OMR_MusicSheet
/omr_musicsheet/texture_synthesis/plot_inpaint_efros.py
1,937
3.765625
4
""" ========================= Textural Image Inpainting ========================= Image Inpainting is the process of reconstructing lost or deteriorated parts of an image. In this example we wll show Textural inpainting. Textures have repetitive patterns and hence cannot be restored by continuing neighbouring geometr...
2def8e071a6f9588ed62849bc24afe5c302a7b03
mmosc/pyph
/3/gauss_midpoint.py
565
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Numerical Integration of the normal distribution with the midpoint rule """ import math sigma = 0.5 # Standard deviation x_max = 3 # Integration domain from -x_max to +x_max dx = 0.01 # Width of the Integration interval def f(x): ...
a214dc98e805972c811be9137285eb0b0b0300a1
howardh0214/Algorithms-Homework
/HW5/closest.py
2,202
3.625
4
import math def Brute_Force(Array): size = len(Array) minimum_distance = Euclidean_Distance(Array[0],Array[1]) if len(Array) == 2: return minimum_distance for i in range(0,size): for j in range(i+1,size): distance = Euclidean_Distance(Array[i],Array[j]) if distan...
fb5448760c740e656f952f4cc84af46c7ee64afc
Vaibhav2002/Python-codes
/algorithms/linear search.py
212
3.953125
4
a = list(map(int, input("Enter numbers :").split())) x = int(input("Enter element to be searched : ")) for i in a: if i == x: print("Element found") break else: print("Element not found")
c357f8238f755de64e92f209fd0c284f1a062726
josephj02233/joseph0426
/pylesson11/11ex2.py
815
3.96875
4
import math class distance: def __init__(self, x1, y1, x2, y2): self.xone = x1 self.yone = y1 self.xtwo = x2 self.ytwo = y2 self.distance = 0 def setvalue(self,newx1,newy1,newx2,newy2): self.xone = newx1 self.yone = newy1 self.xtwo = newx2 ...
e8e273b93d98b481b8b933e41371a74eaa4065ff
engr-sakil/Python_Basic
/Logical operator.py
392
4.21875
4
#AND operator num1 = 20 num2 = 50 num3 = 40 if num1> num2 and num1 >num2: print(num1) elif num2>num1 and num2 >num3: print(num2) else: print(num3) #OR operator ch = 'b' if ch == 'a' or ch == 'e' or ch == 'i' or ch == 'o' or ch == 'u': print("vowel") else: print('consonant') #NOT operator num...
c18dc8619da762a49e5084a8525bb9db9b072e8d
luiz-amboni/curso-python
/EstruturaDeDados/Exercicio3/item1.py
696
4.03125
4
def ordVetSelect(): lista_nomes = [] limite_max = 13 posicao = 0 while posicao < limite_max: nomes = input("Digite um nome para ser adicionado a lista: ") posicao = posicao + 1 lista_nomes.append(nomes) def ordListaNomesInsert(listaNomes): for i in range(1, len(l...
70600d808b2282fd57ff5c7e4c5a670eebdba1b4
amaurya9/Python_code
/is_rotate.py
412
4.34375
4
def ISRotateString(string1,string2): string1+=string1 return string2 in string1 if __name__=="__main__": string1=input("Enter Input string") string2=input("Enter string to be checked as rotation or not") if ISRotateString(string1,string2): print("{} is a rotation of {}".format(string1...
58346bdb5940460b43505537ee56427ccda03036
ncwillner/python-tutorial
/classes.py
342
3.90625
4
# new types using classes class Point: #define new types def move(self): #methods that we define print('move') def draw(self): print('draw') point1 = Point() point1.x = 10 #attributes point1.y = 20 print(point1.x) point1.draw() point2 = Point() point2....
d07f6eb57ea9bbba97c39f079a6072c874cf0c90
MenacingManatee/holbertonschool-interview
/0x22-primegame/0-prime_game.py
1,146
3.9375
4
#!/usr/bin/python3 '''Runs the checker for prime game''' def isWinner(x, nums): ''' Usage: isWinner(rounds, numarray) Return: name of the player that won the most rounds ''' if x <= 0 or nums is None or nums == []: return None ben, maria = 0, 0 for num in nums: count = 0 ...
a2bfb43f522bf131a0953db2c0361c0219fb5540
brainygrave/file_rename
/main.py
479
3.625
4
import os path_way = os.getcwd() images = os.listdir(path_way) text_one = "" text_two = "" # OLD Text you want to change answer_one = input("\nFIND TEXT: ").lower() text_one = answer_one # NEW Text you want to change answer_two = input("\nCHANGE TEXT TO: ").lower() text_two = answer_two # Calling function to find a...
947243254430b2952aca0896589b067591bdda3a
ChenLaiHong/pythonBase
/test/leetcode/X的平方根.py
513
4
4
""" 实现 int sqrt(int x) 函数。 计算并返回 x 的平方根,其中 x 是非负整数。 由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。 示例 1: 输入: 4 输出: 2 示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。 """ import math def mySqrt(x): """ :type x: int :rtype: int """ result = math.sqrt(x) return int(result) x = int(input()) print...
98013e5e5ceac6cc103c33145c55920edb744536
AdamZhouSE/pythonHomework
/Code/CodeRecords/2604/60835/253543.py
263
3.546875
4
tem = input().split('"') letters = [] for n in range(len(tem)): if n%2==1: letters.append(tem[n]) target = input() result = '' for n in letters: if target < n: result = n break if result == '': result = letters[0] print(result)
7a0882804c197d5a21b2022b7e171dd7da730ee0
MrHamdulay/csc3-capstone
/examples/data/Assignment_6/klsada002/question1.py
388
4.03125
4
"""Adam Kaliski KLSADA002 CSC1015F Assignment 6 Question 1 Right justifies list of strings""" s = input('Enter strings (end with DONE):\n') listy = [] leng = 0 count=0 while s != 'DONE': listy.append(s) if len(s)>leng: leng = len(s) count+=1 s=input('') print('\nRight-aligned list...
4729f00b96c2e42436d7c7f0e9dcbd90da93754e
EricNg314/Code-Drills
/Interactive_Visualization/day-03/whale_watching/solved/whale_watching_app/app.py
2,102
3.53125
4
# import necessary libraries from flask import ( Flask, render_template, jsonify, request, redirect) from flask_pymongo import PyMongo import data_query import json import os # create instance of Flask app app = Flask(__name__) # TODO: Setup your connection to mongo with the database "whale_watchi...
634699955c06a5edd012a51a172b9b954ff3a600
HaoLIU94/lpthw
/Pratice-exos/ex1.py
5,163
4.4375
4
#!/usr/bin/python import Tkinter top = Tkinter.Tk() # Code to add widgets will go here... top.mainloop() print "Hello World!" #good this is how we write comments print("Hao",25+30/6) print(3+2<5-7) print(5>-2) print(3+2+1-5+4%2-1/4+6) cars=100 space_in_a_car = 4.0 string = 'Nihao' print(space_in_a_car) print(stri...
efb5eb89cc87d1e7787e279d2a1c5ac3551c0750
mayur1101/Mangesh
/Python/function decorator2.py
535
4.03125
4
# A Python program to demonstrate that a function # can be defined inside another function and a # function can be passed as parameter. # Adds a welcome message to the string def messageWithWelcome(str): # Nested function def addWelcome(): return "Welcome to " # Return concatenation ...
96ce5d9ffb82306b6b4056f315a26d486abdc91c
yangzhao5566/go_study
/collections_learn.py
890
3.84375
4
# collections 模块学习 from collections import namedtuple from functools import partial from collections import deque from collections import OrderedDict from collections import defaultdict from collections import Counter point = namedtuple("Point", ["x", "y"]) # 创建一个具名元组 p2 = partial(point, x="2") pp = p2(y=3) p = point(...
44768e37211923fa99fb7fcf47967287545eb8bf
ravi5921/LearningPython
/Tuples.py
564
3.71875
4
coordinates = (1,7) #tupples are defined by using ( ).They are static throughout the program coordinates2 =(4,5) #coordinates[0] = 3 this shows error as tuples' values can't be re-assigned or changed. print(coordinates) print(coordinates2) print(coordinates[0]) print(coordinates[1]) print(coordinates2[0], c...
06fc874f74dd0a4d86895f9851f1db9f02c11a86
AndrewC7/cs1.0
/custom_calculator/custom_calculator.py
3,022
4.5625
5
# this is a simple conversion calculator. It can handle seconds/minutes/hours print("Welcome to my simple conversion calculator! Simply:\n") print("1) Input the number of seconds/minutes/hours\n") print("2) Specify seconds/minutes/hours\n") print("3) Input your desired conversion\n") number = input("\nNumber of secon...
0d40965292a34b3fcb27f0717447ef2190f65776
AkulsysYT/chesscolourpicker
/ChessColourPicker.py
1,257
3.546875
4
import random import PySimpleGUI as sg # list shuffling import random colours = ['Black', 'White'] choices = random.choice(colours) if choices == "Black": var = "White" elif choices == "White": var = "Black" # gui sg.theme("DarkAmber") # This is the windows contents. layout = [[sg.Text( ...
4617a952e4a3bd55163cbdcbb86fe0a0fa6579a6
mutoulovegc/gaochuang123
/桌面/day.3/maifangzi.py
501
3.671875
4
""" 买房子:500万能够买一环的房子,400万能够买二环,如果300万可以买三环的房子,如果有200万能够买四环的房子,如果小于200万,我只能睡大街 """ money = int(input("请输入存款金额")) if money>=500: print("可以购买一环的房子") elif money>=400: print("可以购买二环的房子") elif money>=300: print("可以购买三环的房子") elif money>=200: print("可以购买四环的房子") else: print("睡大街")
b48c97f5233f3406d755e33315526fd6728e3c0e
logan-anderson/competitive-programming
/aboveavarage.py
270
3.75
4
tests = int(input()) for i in range(tests): nums = [int(i) for i in input().split()][1:] average = sum(nums) / len(nums) above=0 for i in filter(lambda x: x > average, nums): above= above +1 print( '{:.3f}%'.format((above/len(nums))*100) )
dce96dd027151893a0e3d72f4a3ef6f002675b34
nkk0/battleships
/battleships.py
1,648
3.984375
4
from random import randint class Battleships: def __init__(self, turns=4): self.turns = turns self.board = [] def print_board(self): for row in self.board: print(' '.join(row)) def draw_board(self): for x in range(5): self.board.append(['O'] * 5) ...
aaafa8fe034db0b73a479b7a9ade44cd1854ac44
AdamZhouSE/pythonHomework
/Code/CodeRecords/2591/60734/271562.py
227
3.765625
4
t = int(input()) for i in range(t): n = int(input()) if n==917 or n==51 or n==105 or n==101: print('Yes') elif n==109 or n==102 or n == 893 or n==103 or n==104: print('No') else: print(n)
b095747ee1f8bf44089cc80f5027426ecc1ad947
subreena10/function
/limitsum.py
278
3.921875
4
def numbers(limit): i=0 sum1=0 sum2=0 while i<=20: if i%3==0: sum1+=i print(i,"multiply of 3") elif i%5==0: sum2+=i print(i,"multiply of 5") i+=1 sum=sum1+sum2 print(sum) numbers(20)
1727659b4f1a8927713d1b58b702ebed2c1e4f11
SpencerEcho/LeetCode
/Python/AddTwoNumbers.py
1,413
3.875
4
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ return self.r...
4cbc9d535c4109fd1a087e4fb8f79f5b5deab452
dongupak/Basic-Python-Programming
/Ch15_클래스와 객체지향 프로그래밍/human_ex6.py
602
3.8125
4
class Human: # 객체의 초기화를 담당하는 생성자 def __init__(self, name, age): self.__name = name # 인스턴스 메소드를 감추는 기능 self.__age = age # 아래와 같이 @property 지시자를 이용하여 외부에서 접근을 허 @property def age(self): return self.__age @age.setter def age(self, age): if age > 0 : ...
0d02519d834417b70944a756f3f2127d92336822
lydiahecker/exercises
/chapter-2/ex-2-10.py
974
4.1875
4
#Exercize 2-10 #Recipe calls for these ingredients: #1.5 cups of sugar #1 cup of butter #2.75 cups of flour #Produces 48 cookies. Ask the user how many cookies they want and #display the amount of ingredients they will need. sugar = 1.5 butter = 1 flour = 2.75 cookies = 48 sugar_for_one = sugar / cookies butter_for...
f03ff08f0d70b90d6e3400a688724fe80d5de09a
EngrDevDom/Everyday-Coding-in-Python
/Check_date.py
482
4.0625
4
# This program checks if the date format input is correct. check = [ [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ] day, month, year = map(int, input("Give a date: ").split()) feb_29 = int(year%400 == 0 or (year%4 == 0 and year%100 != 0)) if month <...