blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
948352cc077b4401632492088c78006c093485a6
rutsky/python-course-2014
/03_unicode_io_exceptions/examples/exc_example.py
256
3.828125
4
while True: s = input("Please enter a number: ") try: x = int(s) break # остановить цикл except ValueError: print("Can't parse '{0}' as number.".format(s)) print("Try again") print("You entered:", x)
2a266e655c06df1afa55c6127eea48dccc7594c9
SaymonPhoenix/python
/if.py
209
4.0625
4
AGE = int(input ('How old are you? ')) # int, str, float if (AGE >= 21): print ('Vodka') elif (AGE >= 18) and (AGE < 21): # and, or, not print ('Beer') else: print ('Juice')
a501011f4baea1f742e61618c4bf28cc9c4706ea
adh2004/Python
/Lab05/Lab05P3.py
679
3.875
4
sentinel = 'y' uSentinel = sentinel.upper() flightCount = 0 lFlightMilage = [] def AddMilage(_list): milageTotal = 0 for x in _list: milageTotal += x print("Total milage so far: ", milageTotal) def PrintFlightMiles(_list): print("Milage of each flight you have taken:") for x in _list: ...
172c2088e902df0af316398f2febd267b641ad7a
hydrogen602/simpleServer
/staticPageServer/serverCode/fileLoader.py
1,908
3.5
4
errorMsg = '''<!DOCTYPE html> <html> <head> <title>Error</title> </head> <body> <h1>Server Error!</h1> <p>We apologize for the inconvenience</p> <p>{0}</p> </body> </html>''' '''Simple error message as html''' fileTypes = { ".html": "text/html", ".css": "text/cs...
981cf2f42ced40717d345da156977fb5fbcee2f3
KaterynaKandziuba/ITStep-hws
/HW_12/Kandziuba_hw12.py
651
4.125
4
#Task: #Написати функцію-декоратор, яка підносить до квадрату значення, # що повертає функція, до якої декоратор застосовується. def sqre(func): def wrapper(x): func(x) print("The square area is", x**2) return wrapper @sqre def foo(a: int): print(f'{a} is the square side lengt...
cba3ac0f81aea9847069560fcaa0d3f92140221f
spinon187/practice
/algoexpert/suffixtrie.py
655
3.875
4
class SuffixTrie: def __init__(self, string): self.root = {} self.endSymbol = "*" self.populateSuffixTrieFrom(string) def populateSuffixTrieFrom(self, string): for x in range(len(string)): self.insert(x, string) def insert(self, i, string): node = self.root for j in range(i, l...
a223e29552ac5faf262883a28e75a815ef85a5c0
CrisofilaxDives/Python-Practica
/practicaspropias1.7.py
3,539
4.09375
4
# Tipos de datos y condiconales # Strings string_1 = "Hola" string_2 = "Toma Agua" print(type(string_1)) ## upper() print(string_1.upper()) ## lower() print(string_2.lower()) ## swapcase() print(string_1.swapcase()) ## capitalize() print(string_2.capitalize()) ## replace() y multiples métodos print(stri...
18de63ab2cacc83f08ba9b8e7b06d574872d5cbb
Fel-o/stat-helpers
/analyze.py
1,474
3.625
4
import pandas as pd def col_missing_values(df, cutoff=None): """Find number of missing values in each column. cutoff (int): dont list indices if more missing values than cutoff -> np.nan else. """ missing_vals = pd.DataFrame(columns=["n_missing","indices"]) for col_name in df.columns: is_m...
6500e8c93421e46601cd4c88359da2914f6da0fb
General-Mudkip/Computer-Science-y10
/U7/U7 L2.2.py
4,151
4.125
4
import pprint def conditions(): num1 = float(input("Number 1: ")) num2 = float(input("Number 2: ")) if num1 == num2: print("They are equal") elif num1 > num2: print("Num 1 is bigger") elif num2 > num1: print("Num 2 is bigger") def musicChoice(): music = {"pop":"Ed Shee...
4a9cf3e8763c86f93619195a9209dbac8072357e
tig3r66/hacked-beta-encryptodoodles
/AES.py
6,504
3.640625
4
# AES def encrypt(message): key = input("Enter User Defined Password: ") cipher = [] length = len(message) remainder = length%16 num_of_blocks = int(((length-remainder)/16)+1) cipher.append(num_of_blocks) for blocks in range(num_of_blocks): message_block = get_message(message) message = list(message) del ...
937b69e57e2c6b066542ce1539be81fde35b4ca9
hanshnnn/FFC-coding-exercise
/Algorithms/Implement Quick Sort/solution.py
720
3.671875
4
def partition(array, start, end): if start == end: return -1 else: i = start - 1 pivot = array[end] for j in range(start, end): if array[j] <= pivot: i += 1 array[i], array[j] = array[j], array[i] array[i+1], array[end] = array[...
7f454ec8053fb0d3a5d1ca73df0045c98a7e5984
afahad0149/How-To-Think-Like-A-Computer-Scientist
/Chapter 11 (LISTS)/exercises/problem_11.py
678
4.1875
4
def swap(x, y): # Incorrect version print("before swap statement: x:", x, "y:", y) (x, y) = (y, x) print("after swap statement: x:", x, "y:", y) def correct_swap(x, y): # a workaround to solve the swap problem (x, y) = (y, x) return (x, y) a = ["This", "is", "fun"] b = [2,3,4] print("befor...
cdfd11dc8da894131509639328b92b31d833409b
eliasssantana/logicaProgramacao
/Exercício 3 - verificação de aprendizagem.py
1,557
4.15625
4
print("=-" * 30) e = 'Exercícios' print(e.center(50)) print("=-" * 30) # 03) ''' - Utilizando estruturas de repetição com teste lógico, faça um programa que peça uma senha para iniciar seu processamento. Não deixe o usuário continuar se a senha estiver incorreta, após entrar d-vindas a seuê as boas usuário e apresente...
7701f6c5c9aaa259f8e06586860f5c549dfbf1ac
khushboo011/python-programs
/array/swap_array.py
493
4.0625
4
# Write a program to swap `num` elements from the list from pos si, sj # eg: [1,2,3,4,5,6,7], si= 1, sj = 4, num = 2 # rs: [1,5,6,4,2,3,7] def swap_num_elements(arr, num, si, sj): if si >= sj or num == 0 or ((si + num) > sj): return arr if type(arr) != list or len(arr) == 0 or len(arr) < (sj + num): ...
84861e59a11716f9634fff845837270a3435f65b
fredy-glz/Ejercicios-de-Programacion-con-Python---Aprende-con-Alf
/02_Condicionales/09_CondicionalesPython.py
518
3.703125
4
# JOSE ALFREDO ROMERO GONZALEZ # 12/10/2020 edad = int(input("Ingrese su edad para entrar a la diversión!: \n")) if edad < 4: precio = 0.0 elif edad <= 18: precio = 5.0 else: precio = 10.0 print("El cliente debe pagar " + str(precio) + "$") # SOLUCION DE https://aprendeconalf.es/ edad = int(input("I...
96bf5cfe0bf7ec3deffbe96f29e2fb49eb9d431e
taliesinb/chartreuse
/utils.py
572
3.703125
4
def flatten(xs): f = [] for x in xs: if type(x) == list: f += flatten(x) else: f.append(x) return f def first(x, *y): return x def identity(*x): if len(x) == 1: return x[0] else: return x def stringify(arg): if type(arg) in [list, tuple]: return ''.join(map(stringi...
86c708d7d2b42a464495027b54e32f41addd96cb
mohamed17717/faculty-projects
/binarySearch.py
747
3.828125
4
def binary_search(lst, elm): ## must be sorted lst cus its depends on midian (basic statistics) lst.sort() while lst: ## to tell you howmany loops happened (not neccesary) print(lst) ## midian length = len(lst) midIndex = length // 2 mid = lst[midIndex] ## cretical points ...
9047a0ad6420031c615e8e3f7107367f6a6fb593
dayanepabla/curso_python
/level5/interromp.py
202
3.921875
4
#-*- encoding: utf-8 -*- soma = 0 print('Digite 0 para sair') while True: n = input('Digite o número que deseja somar: ') if (n == 0): break soma = soma + n print('Soma: %d' %soma)
e49e4b55220abe93d47ee1ca3bd4618908d2a5d9
zevgenia/Python_shultais
/Practic/task_4/digit.py
526
3.875
4
import sys digit = int(sys.argv[1]) # десятичное число получено #digit2 = bin(digit).lstrip('-0b') # двоичное число, подавили первые символы признаки системы счисления #digit8 = oct(digit).lstrip('-0o') # восьмеричное число #digit16 = hex(digit).lstrip('-0x') # шестнадцатеричное число #print(digit == bin(digit)) prin...
abe3f3a1b42d83346badae1232d33897b3b5f166
MorgFost96/School-Projects
/PythonProgramming/Homework/Exam 2/exam2program2.py
1,820
3.96875
4
#Morgan Foster #1021803 #This program allows the user to input stock information until the user is #chooses to stop, then outputs calculations for the stocks that the user input. #Input name = "default" while( name != "Quit" ): name = input( "Stock Name (Type 'Quit' to Stop): " ) if( name != "Quit" ): ...
f924a96ef518567eadedc42c897c22f063896cb3
furkanoruc/furkanoruc.github.io
/Python Programming Practices - Daniel Lyang Book/ch4 copy/assignment_24_ch_4.py
618
4.09375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 29 05:04:33 2021 @author: furkanoruc """ #radius of earth import random import math #scissor (0), rock (1), paper (2) card = eval(input("Pick your card: ")) rank = ["Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King"] suit = ["Clubs",...
c542a59be4299bd6bd96c48bfe13ab3746a5bd45
dlucidone/PycharmProjects
/new/Bucky/ppt38-Unpacking_List_Tuples.py
249
3.703125
4
date, name, price = ['january 1,2016', 'Bread gloves', 8.61] print(date) print(name) print(price) def unpack_list(list_var): first, *middle, last = list_var avg = sum(middle)/len(middle) print(avg) unpack_list([56, 64, 98, 76, 88])
ab15b252f6336da6d211b9ba92093cdeb423a941
NikolasSchildberg/pygui
/calculator/calculator.py
1,450
3.515625
4
from tkinter import * root = Tk() butpad = 15 go = 'c ' e = Entry(root, borderwidth = 5) e.grid(row=0,column=0, columnspan=3) def myClick(): e.insert(-1,go) # texttoprint = "Hoy!" # Label(root,text=texttoprint).grid(row=0,column=0) #myButton = Button(root, text="click Here!", state=DISABLED) b1 = Button(ro...
732c1b0fb9a2fcdb96eabf08acae5a69340e9ad3
DarkAlexWang/leetcode
/ReferenceSolution/17.letter-combinations-of-a-phone-number.139917117.ac.py
1,463
3.890625
4
# # [17] Letter Combinations of a Phone Number # # https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/ # # algorithms # Medium (36.00%) # Total Accepted: 212.9K # Total Submissions: 591.2K # Testcase Example: '""' # # Given a digit string, return all possible letter combinations that th...
0812c0487b380d6d0209c7caa8b65093b0ea32cf
rahulpacharya/PythonLearn
/8.Exception Handling.py
2,246
4.40625
4
## Handling exceptions ###### ### using try..except ##################### # The code to be handled is written inside try clause # and the code to be executed when an exception occurs # is written inside except clause. try: a = pow(2, 4) print("Value of 'a' :", a) b = pow(2, 'hello') # results in excepti...
ce27e5a8e5a61e277a2bafa5a8cb07acf070928f
PatMatrick/KnaveUI
/maincode.py
5,502
3.59375
4
import math import random class Player: def __init__(self, name): self.name = name self.strength = int(0) self.strbonus = int(0) self.dex = int(0) self.dexbonus = int(0) self.con = int(0) self.conbonus = int(0) self.intel = int(0) ...
6f8ecf771d99ac1eec9c6525f6845b8d457e08c5
mahesstp/python
/Day3/collection/list.py
1,075
4.0625
4
#!/usr/bin/python import sys def main(): numbers = [ 10, 20, 60, 30, 10, 40, 50 ] print ("List elements are ...") for x in numbers: print ( x ) print ("Reversed list elements are ...") numbers.reverse() for x in numbers: print ( x ) #Slicing print ('Current list') ...
1b06d480b360d16404fbdf42cb5654623bf5124c
vanphuong12a2/tuenti_challenge5
/challenge3.py
1,322
3.65625
4
import sys def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in xrange(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)/(2*i)+1) return [2] + [i for i in xrange(3,n,2) if sieve[i]] def count_primes(num, primes_list): """ Count number of r...
61914562d2314e5299eec131700e5b0208f4ed37
advaitsp/PS-1-Summer-2020
/Numpy/Statistical Functions/average.py
502
4.1875
4
import numpy as np a = np.array([1,2,3,4]) print 'Our array is:' print a print '\n' print 'Applying average() function:' print np.average(a) print '\n' # this is same as mean when weight is not specified wts = np.array([4,3,2,1]) print 'Applying average() function again:' print np.average(a,weights = w...
38c3dcd36dc9829a0d12d7c7350b724a8c81f353
TysonReimer/itDAS
/umbms/loadsave/__init__.py
945
3.65625
4
""" Tyson Reimer University of Manitoba June 19th, 2019 """ import pickle ############################################################################### def load_pickle(path): """Loads a pickle file Parameters ---------- path : str The full path to the .pickle file that wi...
66e877c8e21d50bafd3f12d63a950590a6f18167
RavinderSinghPB/Data-Structure-And-Algorithm-Python
/list/006 stockBySell.py
646
3.65625
4
def maxProfit(price, start, end): if end <= start: return 0 profit = 0 for i in range(start, end): for j in range(i + 1, end + 1): if price[j] > price[i]: curr_profit = price[j] - price[i] + \ maxProfit(price, start, i - 1) +\ ...
770a42f436fc5dec384f353367d2d2d2208f9795
Kamran444/python.
/WEEK 3.2.py
1,154
4.21875
4
item_1 = int (input ('Enter price of first item: ')[:-1]) # item prices are whole numbers integers and item_2 = int (input ('Enter price of second item: ')[:-1]) #'[:-1]' removes the pence from the phrase item_3 = int (input ('Enter price of third item: ')[:-1]) item_4 = int (input ('Enter price of fourth i...
624ad33267ce9d85d2f3e6466b07a72980e4d01d
mecomontes/Python
/Vision Artificial/Emparejamiento.py
4,283
3.890625
4
""" Emparejamiento de plantillas Teoría El emparejamiento de plantillas (o template matching en inglés) es un método para buscar y encontrar la ubicación de una imagen de plantilla en una imagen más grande. OpenCV viene con la función cv2.matchTemplate() para este pr...
e31fff519980e3a84c38c8cb092ab05d9d23debf
pengyang97/PathPlanning-1
/Morse/ranger_sim/scripts/move_eyes.py
858
3.59375
4
from pymorse import Morse print("Use wasd to control the Ranger") with Morse() as simu: motion = simu.robot.motion pose = simu.robot.pose eyes = sium.robot.eyes v = 0.0 w = 0.0 left = 0.0 right = 0.0 while True: key = input("WASD?") if key.lower() == "w": v += 0.5 eli...
114ee1dd8de3e91b2aaef892f1729b0142bd8336
luhralive/python
/Liez-python-code/0002/0002.py
822
3.71875
4
# coding = utf-8 __author__= 'liez' import random import sqlite3 def make_number(num, length): str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' a = [] i = 0 while i < num: numstr = '' for j in range(length): numstr += random.choice(str) if nums...
a11e3e3d8a1a39a54a3390a034a1f68771cfaa05
dmaterialized/sql-tests
/script1.py
3,987
3.9375
4
# / database loader - creates an sqlite3 database. # \ # / version: 0.2 # \ date: 2017.05.07 # / initial: 2017.05.07 # \ TODO: # / - update, move, search functions # \ - make row return more visually appealing # / - visual browser # \ - add items by typing them in # / - bind gui buttons to item funcs # \ # / # this ve...
926c213dcc528aaadb34c5961ca73d0f70549de9
xiaohanchen/PythonPractise
/DuplicateLetter.py
751
3.953125
4
def findAllUnrepeatedLetters( word ): unrepeatedChar = set() for letter in word: if letter in unrepeatedChar: unrepeatedChar.remove(letter) else: unrepeatedChar.add(letter) print "all unrepeated letters: " print unrepeatedChar print def findFirstUnrepeatedL...
1ff840fef8bc267fcf37268800d9bd29dd86f521
Pasquale-Silv/Improving_Python
/Python Programming language/DataCampPractice/Python_Data_Science_Toolbox_Part2/Generators_and_GENfunc_yield/GEN2.py
462
4.34375
4
# [ LIST COMPREHENSION ] # ( GENERATOR ) # Recall that generator expressions basically have the same syntax as list comprehensions, # except that it uses parentheses () instead of brackets [] # Create generator object: result result = (num for num in range(31)) # Print the first 5 values print(next(result)) print(ne...
8d58e8c62c213af074d36c67a413cf4212f13eec
djdd01/CS50-2020
/pset6/credit/credit.py
2,221
3.984375
4
from sys import exit from cs50 import get_int # ok so first of all creating a long variable to get a card number as an input card = get_int("What is your credit card number? \n") temp = card # creating another variable temp to utilize instead of making changes in card alt = 0 # alternate digits adj = 0 # alt altern...
43b6c269463f34d4bcbe676db6bb06a5d986b32d
skang6283/algorithm_daily
/Algorithms/Dijkstra.py
1,074
4.0625
4
# Find shortest path from starting vertex to every other vertex in the graph # Time complexity # O(V + E log V) with min-priority queue from heapq import * import sys INF = sys.maxsize N= int(input()) def dijstra(start): dist = [INF] * (N+1) # list to store current distance from start to node h = [(0,sta...
b36e4be08b1f786a76f3fb565dc0c4e177afc472
frotaur/SmartFish
/game.py
2,311
3.640625
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 2 19:06:49 2018 @author: Vassilis """ import constants as c import pygame as pg import playFish import groupObjet import food import random as rand import aiFish class Game: def __init__(self): pg.init() self.display = pg.display.set_mode((c.WIDTH,c.HEIGHT)) se...
6e9ae5b6d535be9377c0ee06c7f32a8b236c0340
unmtransinfo/ProteinGraphML
/DataCompare/FindCorrelation.py
3,405
3.59375
4
import pandas as pd import argparse def read_python_file(pythonfile, mlimit): """ Fetch the data from the output file of Python. """ print("Sort the Python file in descending order by probability and select PID") df = pd.read_csv(pythonfile, sep='\t') df1 = df.sort_values(by='Predict...
ba42eed52727c3a4e27f0dab89bbc95fa4c1b652
hyo-eun-kim/algorithm-study
/ch17/hyoeun/ch17_1_hyoeun.py
1,497
3.765625
4
''' 58. 리스트 정렬 연결리스트를 O(NlogN)에 정렬하라. https://leetcode.com/problems/sort-list/ ''' # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: ...
9932abf8e96d1ff6e0eea5cf799bc5121d09ef1e
JarvisFei/leetcode
/剑指offer代码/算法和数据操作/面试题26:树的子结构.py
1,434
3.90625
4
class TreeNode(): def __init__(self, val): self.val = val self.left = None self.right = None def judgeTree(Tree1, Tree2): #假定空树是任意树的子树 if not Tree1 and not Tree2: return True if not Tree1 or not Tree2: return False if Tree1.val == Tree2.val: if jud...
dd9320a86296a1e6a0d5165678a4061a1e570462
rcchen/project-euler
/python/euler31.py
335
3.640625
4
coins = [200,100,50,20,10,5,2,1] count = 0 discovered = [] def combinations(coin,total,combo): global count if (total == 0): count = count + 1 print "foundone" return if (total < 0): return for another in coins: combinations(another,total-another) for coin in coins: combinations(coin,20-coin,combo) ...
09454b988243d39aa822d35112bb5e7ae360f5d5
edubs/lpthw
/ex16.py
1,092
4.34375
4
# ex16.py # reading and writing files from sys import argv script, filename = argv print(f"we're going to erase {filename}.") print("if you don't want that, hit CTRL-C (^C).") print("if you do want that, hit RETURN.") input("?") print("opening the file...") target = open(filename, 'w+') # 'w+' doesn...
7b3e9a29b00b996fbd1b45c75860447aae3fc370
aidynkyzy/akerke
/9task2.py
365
3.96875
4
A1=int(input()) B1=int(input()) C1=int(input()) A2=int(input()) B2=int(input()) C2=int(input()) if A1*B1*C1==A2*B2*C2: print("Boxes are equal") elif A1*B1*C1<A2*B2*C2: print("The first box is smaller than the second one") elif A1*B1*C1>A2*B2*C2: print("The first box is larger than the second one"...
74626ce6d67cc9309e1715c72ece2c7b679d80ac
GrnTeaLatte/AlienInvasion
/Chapter_6/favorite_numbers.py
793
3.703125
4
favorite_numbers = { 'kyle': '24', 'audrey': '4', 'nathan': '15', 'derek': '57', 'auggie': '6' } print("Kyle's favorite number is " + favorite_numbers['kyle'] + ".") print("\nAudrey's favorite number is " + favorite_numbers['audrey'] + ".") print("\nNathan's favorite number is " + favorite_numbers['nathan'] + "."...
8dc56aa55548dc8396efee8198999e9cb2be735f
Isaac-Gathere/basic-calculator-python
/calc2.py
3,321
3.65625
4
from tkinter import* def btnClick(numbers): global operator operator = operator + str(numbers) text_Input.set(operator) def ClrButton(): global operator operator ="" text_Input.set("") def equals(): global operator total = str(eval...
2b3f6b76fc611dce5703f4c0c10845957ef73bf3
jayantrane/Blockchain
/Assignment 1/assignment.py
4,057
3.6875
4
#!/usr/bin/python2.7 # -*- coding: latin-1 -*- import hashlib import argparse from datetime import datetime TARGET_DIFFICULTY = 6 # No of preceding zeros required # Define Values from arguments passed parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=""" ...
67ec0793c045cea20f85b6186ca699d79ffca1b7
clementeqp/Analisis_de_Datos_Python_2021
/part02-e14_vector_lengths/src/vector_lengths.py
355
3.734375
4
#!/usr/bin/env python3 import numpy as np #import scipy.linalg def vector_lengths(a): return np.sqrt(np.sum(np.square(a), axis=1)) """ return scipy.linalg.norm(a, 2, axis=1) return np.sqrt(np.sum(a**2, axis=1)) """ def main(): a = np.random.randint(0,10,(2,3)) print(vector_lengths(a)) if ...
27a1f6d08fdfa8b3e7380cd5150a7446c9df9fab
mtask/Random-Scripts
/python/geoping.py
5,606
3.5625
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Usage: Geoping is pinging tool that lets you ping hosts and draw map of pinged hosts. Hosts that were up are shown as green plots on map and hosts that were down as red plots. It uses os's ping command so depending on your system it may not need root access. External...
736fc3a8ab0f6327998293379b562134a64fd0f6
maheshde791/python_samples
/pythonsamples/class1.py
869
3.96875
4
#!/usr/bin/python class Employee(object): empCount = 0; def __init__(self,name,salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print("Total Employee %d",Employee.empCount) def displayEmployee(self): print("Name=",se...
d438ab73040b1de3fa018141a9d3e7b8a106e1bf
ManuelSerna/intro_algorithms
/sorting_algorithms/quicksort/src/quicksort.py
1,186
3.671875
4
#************************************************ ''' Quicksort Best-case time: Theta(n*lg n) Worst-case time: Theta(n^2) Note: verbose shortened to v ''' #************************************************ def partition(A, p, r, v): x = A[r] i = p - 1 if v: print('partitioning') ...
263fe7f3b56c51a8658553ab635937d0dffe7756
QWJ77/Python
/StudyPython/Python列表-额外操作.py
1,790
4.0625
4
#------------------------------ 判定-------------------------------- # 元素 in 列表 # 元素 not in 列表 # s="abc" # print("a" in s) # print("c" not in s) # # values=[1,2,3,4,5] # print(5 in values) # print(5 not in values) #------------------------------ 比较-------------------------------- # cmp()内建函数,可以直接写出来,Python3不支持,直接用>,<,== ...
75b4d244706e83fb546bd660c1c17f1ce679b01e
maayansharon10/intro_to_cs_python
/ex4/hangman.py
6,814
4
4
import hangman_helper as hm def is_user_input_valid(string): """ checks if the user input is only a ONE lower case letter.""" if len(string) != 1: return False elif string.islower(): return True else: return False def update_word_pattern(word, pattern, letter): ...
cfa93d577fa66497651f92eafb6e19d870516a3a
NikitaOchin/Methods-Optimization
/Методы делением отрезка.py
2,252
3.59375
4
def Extr_Dixot(f, a, b, eps, delta): """Дихотомический метод нахождения экстремума функции f - принимаемая функция a - начало отрезка b - конец отрезка eps - константа различимости delta - точность конечного результата """ k = 1 while True: c = (a+b)/2 if b...
d5c17c978c0af84d335165bdf927fd3311150b38
Jakub-Kaczmarczyk/prac_prog_03
/zad17.py
750
4.125
4
x=int(input("Enter first number: ")) y=int(input("Enter second number: ")) if x>0 and y>0: print(f"Point P({x},{y}) is in the first quadrant of the coordinate system") elif x>0 and y<0: print(f"Point P({x},{y}) is in the second quadrant of the coordinate system") elif x<0 and y<0: print(f"Point P({x},{y}) i...
2a9e12d221204cb05aedbe746426406e912dfab8
pangfeiyo/PythonLearn
/Python:从入门到实践/从入门到实践代码/第9章 类/9.5 PYthon标准库/动动手.py
2,591
3.984375
4
# 9-13 使用 OrderedDict : # 在练习 6-4 中,你使用了一个标准字典来表示词汇表。 # 请使用 OrderedDict 类来重写这个程序,并确认输出的顺序与你在字典中添加键— 值对的顺序一致。 from collections import OrderedDict glossary = OrderedDict() glossary['string'] = 'A series of characters.' glossary['comment'] = 'A note in a program that the Python interpreter ignores.' glossary['list'] = ...
01466c88adc688a98f63d9ca28a3ca9d82504384
programasemdor/curso-python
/Aulas/aula04.py
117
3.65625
4
#coding: utf-8 #Processamento i = 1 while i <= 10: print('Ricardo') i += 1 # i = i + 1 print('Terminou!')
40a36606a73be1413a7b1f3e7d614fa58ed01603
ScienceStacks/microbepy
/microbepy/common/combination_iterator.py
1,107
3.625
4
"""Iteratively supplies combinations with optional exclusions.""" from microbepy.common import constants as cn import itertools class CombinationIterator(object): def __init__(self, elements, max_size, excludes=None): """ :param list-object elements: Elements to construct combinations :param int max_...
f7ad296b67ff7d61a388782faad745b73634fff9
somecat1996/Homeworks_IS
/2017_11_22/test.py
459
3.578125
4
from Polynomial import * # for m in [7, 5, 2]: # a1 = Polynomial([1, 5, 4, 3, 0, 1, 3], m) # a2 = Polynomial([1, 3, 5, 6, 0, 2, 1], m) # print a1 + a2 # print a1 * a2 # print a1 * a1 # print # a1 = Polynomial([0], 2) # print a1 t1 = [1, 0, 0, 1, 1] a1 = Polynomial(t1, 2) t2 = [1, 0, 0, 0, 1, ...
287bcec75275075c85d24d09e277c082f471e759
UoA-eResearch/cer_mojo
/python/cluster_tools/cluster/util/stringutil.py
1,362
3.96875
4
import re def extract(string, sub1=None, sub2=None): ''' Extract and return the string between sub1 and sub2 from string If sub1 is None, everything from the start to sub2 is returned If sub2 is None, everything from sub1 to the end is returned If either sub1 or sub2 cannot be found, an empty strin...
37f5b64cbdf964120b469864809dbe81a2f7b28e
ahhamamoto/snake
/snake.py
3,428
3.65625
4
# Autor: Anderson Hiroshi Hamamoto # Snake # a implementar # (DONE) - conforme o jogador vai pegando mais speed, brota mais de uma comida por vez # ou spawnar comida de acordo com o tempo # * comida nascer dentro da cobra e dentro de outras comidas # (DONE) - nao deixa o jogador ir na direcao oposta #...
570f9374b26d9406afaf948b9168c2909ec3193d
amr-nsu/httpd
/lib/gps.py
518
3.65625
4
from math import sin, cos, pi class GPS: def __init__(self, x=0, y=0, q=0): self.x = x self.y = y self.q = q def move(self, v, w, dt): self.q = wrap_to_pi(self.q + w * dt) self.x = self.x + v * cos(self.q) * dt self.y = self.y + v * sin(self.q) * dt ret...
5bf6917aeb5a4039fd83690a2b9a383adc2225bf
DKU-STUDY/Algorithm
/programmers/난이도별/level03.단어_변환/sangmandu.py
1,404
3.5625
4
''' https://programmers.co.kr/learn/courses/30/lessons/43163 단어 변환 : 한글자만 변경하면 같아지는 글자를 찾아 이동하면서 원하는 단어를 구할 때의 이동횟수를 구하는 문제 1) 모든 단어는 50개 이하이므로 51개와 min 비교 가능 2) 선택된 단어는 words에 제거되며 words의 크기인 length로 이동횟수 파악 가능 이 때, words는 mutable 하므로 slicing한 words를 인자로 결정 3) 매번 len을 조사하는 시간을 조금이나마 줄이고자 lenWord와 lenWords 그리고 length 사...
e2d61a793c1c24fe39f89fd9c96dd458d371f533
felipeaq/solution_of_a_course
/matriz/soma.py
607
3.53125
4
def compara(minha_matriz,mat): return str(len(minha_matriz))+'X'+str(len((minha_matriz[0]))) ==str(len(mat))+'X'+str(len((mat[0]))) def soma_matrizes(m1, m2): m3=[] if (not compara(m1,m2)): return False for (i) in (range(len(m1))): linha=[] for j in range(len(m1[i])): ...
924f8f1e1a5d8ac1d1a98b63c1b6e186741b0a9c
Shockley123/--
/实用/电子邮件/电子邮件.py
1,083
3.625
4
#电子邮件 #使用utf-8 #coding:utf-8 #导入模块 import smtplib from email.mime.text import MIMEText from email.utils import formataddr #发邮件函数 def sent(): #我的邮箱 my_mail='sxxx20153405@163.com' my_password = 'BJTJBJDAZOSAJIFL' #对方邮箱 your_mail=input('收件人:') #主题 theme=input('主题:') #正文 print('正文:'...
ecd85bd03e5cfbd0c8e886ad6a7df0dffa80a485
naseeihity/leetcode-daily
/easy/136.single-number.py
1,433
3.734375
4
# day 1 # # @lc app=leetcode id=136 lang=python3 # # [136] Single Number # # https://leetcode.com/problems/single-number/description/ # # algorithms # Easy (62.19%) # Likes: 3133 # Dislikes: 123 # Total Accepted: 578K # Total Submissions: 929.5K # Testcase Example: '[2,2,1]' # # Given a non-empty array of integ...
6a664edc469105c9fcff2a54a14dbd75096a9efa
luisa-maria1111/FPRO_MIEIC
/easy_change.py
1,211
4.28125
4
""" Easy change You're helping a teller decide how to give change. Write a Python script that given the price of the sale and the amount received by user input, then prints a string indicating how many notes of each amount they have to give as change. Consider that the largest note available is the 50€ no...
0eac195d0d4fb36bae7fff187e01ad6b6448c2f4
lingshanng/my-python-programs
/Practicals DHS/Practical 2/q05_find_month_days.py
1,189
4.375
4
# Finding the number of days in a month try: month = int(input("Enter month: ")) year = int(input("Enter year: ")) if month == 1: print("January %s has 31 days" %(year)) elif month == 2: if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: print("February %s has 29 da...
799dba633cf7d2d81209dd2962dfc982f08048be
pranshu28/euler_project
/Composites with prime repunit property.py
676
3.515625
4
import timeit start = timeit.default_timer() def prime(n): for i in range(2,int(n/2)+1): if n%i==0: return False return True def r(k): s='' for i in range(k): s+=str(1) return int(s) def gcd5(a): if a%5!=0: return True return False def a(...
ae12b12938aad671b10f0c7174c2ed5189a26ac8
turnergarrow/ProjectEuler
/PE1.py
89
3.703125
4
tot = 0 for i in range(1000): if i%3 == 0 or i%5 == 0: tot += i print(tot)
45fa7959512e49627b60af50c81a0300ea3f354a
kristofclaes/vigenere
/tests/test_utils.py
866
3.734375
4
# -*- coding: utf-8 -*- from vigenere.utils import pair_up_characters def test_pair_up_with_text_and_key_of_same_length(): """Tests that the characters of a text and a key are paired up correctly when they are of the same length.""" pairs = pair_up_characters('ABC', 'DEF') assert pairs == [('A', 'D'), ('...
535243d109ab626785acb9efb535df44571a0fdc
InfoTech-Academy/Python_Week3
/onur/equal_reverse.py
557
4.09375
4
"""This program receives strings and return whether this strings are equal to their reversed order""" def ters(str_in): str_in=list(str_in) str1=[] lenght=len(str_in) i=0 while i <lenght : str1.append(str_in[(lenght-i)-1]) i+=1 if str1==str_in: return True else: ...
0eeefffacb2313470062e3cb70c9c1bc530a0cf5
joema-m/attack_on_Python
/algorithm/tree_raverse.py
3,125
3.890625
4
# 二叉树的4种遍历 # 递归与迭代 class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None node1 = TreeNode(1) node2 = TreeNode(2) node3 = TreeNode(3) node4 = TreeNode(4) node5 = TreeNode(5) node6 = TreeNode(6) node7 = TreeNode(7) node8 = TreeNode(8) node0 = TreeNode(0) no...
4d8a0a1f116e894cb079ad64a435724cb3493736
likelion-donghun/shinsegye
/bag_of_words.py
3,107
3.625
4
import pandas as pd import numpy as np df = pd.read_csv('./movie_data.csv', encoding = "ISO-8859-1") #http://stackoverflow.com/questions/18171739/unicodedecodeerror-when-reading-csv-file-in-pandas-with-python df.head(3) # convert words into vectors from sklearn.feature_extraction.text import CountVectorizer count = C...
20fd76217513002d71a443ee12e092a79c846f58
edubrugg/desafio-bridge
/backend/duodigito.py
715
3.78125
4
from timeit import default_timer as timer def duodigito(): num = int(input("Digite um numero maior que 100: ")) if num > 100: busca = True aux = 1 inicio = timer() while busca: conjunto = set() resposta = num * aux aux += 1 respos...
835281bbe6c5a001750ec7c08b7b354611e87b5d
silascaimi/api-steam
/ApiSteam.py
954
3.5
4
import requests import json # This is an API for Steam Spy. It accepts requests in GET string and returns data in JSON arrays. #http://steamspy.com/api.php def BuscaJogo(nome): req = requests.get('http://www.steamspy.com/api.php?request=all') dic = json.loads(req.text) results = [] for appid in dic: ...
ebc14b33f403ea5d7fc783b45c3e2ac4adfaecd9
XNCV/Basic-Python-programming-examples
/assignment_2/l2_ex3.py
191
3.953125
4
def right_triangle(a, b, c): if a**2 == (b**2 + c**2) or b**2 == (a**2 + c**2) or c**2 == (a**2 + b**2): return('True') else: return('False') print(right_triangle(17, 15, 8))
412f874d8e5187eaf3ad0a28cfb8f2a57e054dbf
weimingtom/ai20projects
/2018202151/src/scripts/np_plot_quadratic.py
239
3.796875
4
import numpy as np import matplotlib.pyplot as plt #see what happens with this set if values: x=np.linspace(-5,5,num=100)[:,None] y = -0.5 + 2.2*x +0.3*x**2 + 2*np.random.randn(100,1) #print("x:",x) plt.plot(x,y) plt.show()
c917e3396a090b7e37323844ff58aa34bbd72840
WoodsChoi/algorithm
/al/al-973.py
2,860
4
4
# 最接近原点的 K 个点 # medium ''' 我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。 (这里,平面上两点之间的距离是欧几里德距离。) 你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。   示例 1: 输入:points = [[1,3],[-2,2]], K = 1 输出:[[-2,2]] 解释: (1, 3) 和原点之间的距离为 sqrt(10), (-2, 2) 和原点之间的距离为 sqrt(8), 由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。 我们只需要距离原点最近的 K = 1 个点,所以答案就是...
af7d90274a3a87c0d24de25f896f634fbb3ac4b2
DilLip-Chowdary-Codes/100DaysOfCode
/Python/Loops/sum_of_nums_from_m_to_n.py
182
3.53125
4
#33 """ __author__ = DilLip_Chowdary ❤️ Rayapati """ m = int(input()) n = int(input()) sum_of_nums = 0 for num in range(m , n + 1): sum_of_nums += num print(sum_of_nums)
6bcbc32efae07a6625f653aee6a8765ec8771395
kainpets/Zelle-introduction-to-CS
/code/chapter07/c07ex12.py
897
4.1875
4
# c07ex12.py # Date validator from c07ex11 import isLeap DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def isValidDate(month, day, year): if 1 <= month <=12: # month OK, check day # determine last day of month if month == 2: if isLeap(year): ...
4384fbcb3b7e50b6cbabd1a521472e22f8c3667e
nkukadiya89/learn-python
/dictionaryComprehensions.py
147
3.96875
4
#Dictionary Comprehensions number = {} for i in range(5): number[i] = i*2 print(number) values = {x:x*2 for x in range(5)} print(values)
dda6da9cede0127079fe4e27a18969b106a1dc4c
OZ-T/leetcode
/5/keyboard_row.py
512
3.6875
4
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ first_row = set('qwertyuiop') second_row = set('asdfghjkl') third_row = set('zxcvbnm') res = [] for word in words: word_lo...
858b9d0d4dc8748689c81dac6d0b23bb22d0246f
VitaliiStorozh/Python_Core
/HW5/5.5.py
805
3.859375
4
p = int(input('Star of range: ')) h = int(input('End of range(Must be grater than Start): ')) while h < p: print('Input corect End of range') h = int(input('End of range(Must be grater than Start): ')) sumLesP = 0 multGrateH = 1 count = 0 j = int(input("Your number: ")) while j != p and j != h: if j < p...
2c7e8217a337e372f5d8518748dc67426102acb9
Shubh250695/Python-statement_and_function
/Q3.py
250
4.3125
4
# Reverse the list using for loop # num1 = [5, 15, 20, 25, 30] num1 = [5, 15, 20, 25, 30] num2 = [] for i in range(len(num1)-1, -1, -1): num2.append(num1[i]) print("Original array:",num1) print("Array in reverse order:",num2)
e4ae1d6cad9d6786710b92858bd00cd1d26328cc
SebastianAthul/pythonprog
/Works/present.py
138
3.71875
4
a="luminar" b=input("ENTER AN ELEMENT: ") for i in a: if b in a: print("Present") break else: print("not prresent")
1f57e12d71cd1640dee7377cb2bffc4d60614453
ateneva/python-oop-2020-06
/defining_classes/demo.py
200
3.734375
4
def print_text(text): print('*' * len(text)) print(text) print('*' * len(text)) print_text('Hello') for i in range(1, 10): print_text(f'This is {i}') print_text('End')
2caf0a0c3cd3ddfe37f64435532b60dde6041bf3
Liluan1/python_codes
/cookbook/remove_same_element.py
666
3.796875
4
# 这个方法仅仅在序列中元素为 hashable 的时候才管用。 # def dedupe(items): # seen = set() # for key in items: # if key not in seen: # yield key # seen.add(key) # a = [1, 2, 3, 4, 5, 23, 2, 32, 542, 5, 234, 23, 5] # print(list(dedupe(a))) def dedupe(items, key=None): seen = set() for item i...
c6652539d115c5cf6e5e890b031d511335c330a3
PacktPublishing/Modern-Python-Cookbook
/Chapter 11/ch11_r03.py
1,636
3.75
4
"""Python Cookbook Chapter 11, recipe 3. """ from math import sqrt, pi, exp, erf def phi(n): """ Computes the cumulative distribution function of the standard, normal distribution for values <= n. >>> round(phi(0), 3) 0.5 >>> round(phi(-1), 3) 0.159 >>> round(phi(+1), 3) 0.841 ...
c1834c160c08aca751b62b8bfecf0730fb2e608d
Wenqin-Du/Python-for-Everybody
/Course1_week4Code.py
762
3.921875
4
# simple print out ddd = 1 + 4 print(ddd) eee = 'hello ' + 'python' print(eee) type(ddd) type(eee) # comma in print!! is space! cool! print('hello', 'mos', 'Q') # simple calculation (different from Java!) print(int(99 / 100)) print(99 / 100) # use int() and float() to convert between strings and numbers # get a er...
cfe715326a88fad335f791a94a8d435f7db45875
khushi3030/Master-PyAlgo
/Algebra/Happy_Number.py
1,360
4.34375
4
''' Starting with any positive integer, replace the number with the sum of the squares of its digits. Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy number. ''' ''' Ha...
2b32536c18c7917db2c044510fd7b8ae69a47abb
GeertVanDeyk/SomePythonCode
/AutomateBoringStuff_TicTacToe.py
2,266
3.96875
4
# ############################################# # TIC-TAC-TOE game # ############################################# # Data structures # ############### # 1. the game board theBoard_dict = { 'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', ...
15e095f6cd923ba55aeae8fb434b66e1e83c08db
mallyagirish/myHackerRankSolutions
/30 Days of Code/Day 08 - Dictionaries and Maps/Solution.py
581
3.671875
4
""" @author: zepman85 """ # Enter your code here. Read input from STDIN. Print output to STDOUT if __name__ == '__main__': n = int(input()) phoneBook = {} for i in range(n): name,num = input().rstrip().split() phoneBook[name] = int(num) namesToLookup = [] while True: try: ...
299b34d9af73f39cc1da12f4cf862019d8a28f15
nikita-p/stepik_algorithms
/Second Part/1.2.1.py
2,234
3.734375
4
#Скобки в коде #Проверить, правильно ли расставлены скобки в данном коде class Node(): def __init__(self, value=None, next=None, index=None): self.value = value self.next = next self.index = index class Stack(): def __init__(self): self.first = Node() self.size = 0...
f69f8769954a19db65e6b039e0b8da16489e9bc1
rmamba/pyLucasLehmer
/MersennePrime/threadedmath.py
861
3.578125
4
import threading import math class mul(threading.Thread): def __init__(self, idx, n, m): threading.Thread.__init__(self) self.idx = idx self.n = n self.m = m self.r = None def run(self): r = self.n * self.m self.r = [] self.r.append(r % 256) ...
c28e986df883524d9fc8295d3a117fd141e6522b
Hemavarsheni/codekata
/begn10.py
78
3.53125
4
num=int(input("")) c=0 while(num!=0): num=num//10 c+=1 print(c)
a13eec45ed034dabaac23f4895523c377de7bb10
erdl/legacy-scrape-util
/src/acquire/parsers/survey_display.py
904
3.671875
4
#!/usr/bin/env python3 from src.core.data_utils import Row import csv REQUIRE = [] # primary entry point of this parser. def parse(project,config,state,filepath): rawdata = read_csv(filepath) rows = reformat_data(config,rawdata) return state,rows # reformat the data into `Row` objects. def reformat_dat...