blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
57149de8bb6284a6b422590e18cb5dc04fe61233
PipsVazquez/PythonExamplebyExampel
/e019.py
456
4.28125
4
#Ask the user to enter 1, 2 or 3. If they enter a 1, display #the message “Thank you”, if they enter a 2, display #“Well done”, if they enter a 3, display “Correct”. If #they enter anything else, display “Error message”. print('Enter one of this numbers 1, 2 or 3') number = int(input()) if number == 1: print('Tha...
7b83fdf52acb2b63728bd2cb1700f20452e04998
PipsVazquez/PythonExamplebyExampel
/e033.py
509
4.125
4
print('''Welcome to this exercise. Enter 2 numbers and I will show you how many times the second divides the first number and which number is the remind. Let's do this! ''') print('Please enter de first number') first_number = int(input()) print('Please enter the second number') second_number = int(i...
f6228a700bc96322433d6c7e10942deb619b557e
PipsVazquez/PythonExamplebyExampel
/e022.py
253
4.40625
4
#Ask the user to enter their first name and surname in lower #case. Change the case to title case and join them together. #Display the finished result. print('Enter your name and surname in lower case:') name = input() name = name.title() print(name)
4ee36b0760515aca8b4b6790fb9bb0fa78dd0039
PipsVazquez/PythonExamplebyExampel
/e023.py
533
4.3125
4
#Ask the user to type in the first #line of a nursery rhyme and #display the length of the string. #Ask for a starting number and an #ending number and then display #just that section of the text #(remember Python starts #counting from 0 and not 1). print('Enter a nursery rhyme:') nursery_rhyme = input() lenght_nurse...
5f035fae7ee2348bb7710dc80a47ffb8d9b41081
PipsVazquez/PythonExamplebyExampel
/e036.py
198
4.0625
4
print('I will show you the magic. Please enter your name!') name = input() print('Please enter the times you want to see repeated') times = int(input()) for repeat in range(times): print(name)
a8169631189bf3f1480256f94a7231da33f7d591
PipsVazquez/PythonExamplebyExampel
/e024.py
166
4.4375
4
#Ask the user to type in any word and display it in #upper case. print('Enter any word you want!:') any_word = input() any_word = any_word.upper() print(any_word)
9597343db04e33acee1d8cf475ee668ada9f5d9f
PipsVazquez/PythonExamplebyExampel
/e021.py
335
4.34375
4
#Ask the user to enter their first name and then ask them to #enter their surname. Join them together with a space between #and display the name and the length of whole name. print('Enter your name') name = input() print('Now enter your surname') surname = input() total_name = name + ' ' + surname print(f'All name ...
d1e754ba9a7267cc0b40ff8712b3a4700eb3ecf8
PipsVazquez/PythonExamplebyExampel
/e044.py
364
4
4
print('You going to have a party!') print('Please enter a number below 10') number_menu = int(input()) if number_menu <= 10: for counter in range(number_menu): print('Please enter the guess names') guess_names = input() print(f'{guess_names} has been invited') else: print('Too many pe...
4c5dedc17ba34f70afdc2103614d6d0e7a96ad87
PoBidauGustang/EPAM-HW
/homework1/task3.py
239
3.890625
4
from typing import Tuple def find_maximum_and_minimum(file_name: str) -> Tuple[int, int]: values = [] with open(file_name) as fi: for line in fi: values.append(int(line)) return (min(values), max(values))
d54c765d2df0fd31772dab6cb676dfeb80af15c2
rehbarkhan/project-Euler
/Problem_6/Solution_6.py
813
3.796875
4
''' The sum of the squares of the first ten natural numbers is, 12+22+...+102=385 The square of the sum of the first ten natural numbers is, (1+2+...+10)2=552=3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025−385=2640. Find the difference betw...
ef1ccf2debad2dd99d88de3fb90b0ffa87be2a3d
waqarkaleemkhan/SCC_POS
/categories.py
1,891
3.71875
4
from tkinter import * import psycopg2 from tkinter import messagebox DB_NAME = "SCC_POS" DB_HOST = "localhost" DB_PORT = "5432" DB_USER = "postgres" DB_PASS = "root" conn = psycopg2.connect(database=DB_NAME,user=DB_USER,host=DB_HOST,port=DB_PORT,password=DB_PASS) print('database connected') my_cursor=conn.cursor...
eeeb686ad3239fbd2d899e9b968b8724c7c5b5ee
Yasthir01/Invent-Your-Own-Computer-Games-With-Python---TextBook
/Invent Your Own Games - Book/guess.py
668
4.09375
4
#This is a guess the number game. import random guesses_taken = 0 print('Hello! What is your name?') my_name = input() number = random.randint(1, 20) print(f'Well, {my_name}... I am thinking of a number between 1 and 20.') for guesses_taken in range(6): print('Take a guess') guess = int(input()) if guess < numb...
0639271e96bff1bed0bdc7e6ce5b10de502b5194
water66/-
/notepad.py
7,145
3.59375
4
# -*- coding: utf-8 -*- # @Time : 2019/5/1 # @Author : water66 # @Site : # @File : notepad.py # @Version : 1.0 # @Python Version : 3.6 # @Software: PyCharm from tkinter import * from tkinter.filedialog import * from tkinter.messagebox import * from tkinter import scrolledtext import os filename='' def au...
fd5908bfeae29fc0c416aca4170ec3108deeefef
harry-wright/skytale
/01_caeserCipher.py
2,004
4.5625
5
# Specifically import the 'argv' function from the 'sys' module. # This function opens the script with an argument we define. # In this case it is 'usermode' we will define. # The first value of 'script' can be ignored, but must always be added. # To use 'argv' add the arguments within the terminal. from sys import a...
63c0fd653011642785d5890bcace0fad739538f2
390892467/pystudy
/timeit.py
343
3.765625
4
#测试time.sleep(5)执行的时间,装饰器 import time def timeit(fn): def wrap(*args,**kwargs): start = time.time() ret = fn(*args,**kwargs) print(time.time() - start) # return ret return wrap ''' def sleep(x): time.sleep(x) timeit(sleep)(3) ''' @timeit def sleep(x): time.sleep(x) sleep(5)...
0b6ddf6b38dfe4603f1210ff1d04353a34e0021d
Sahha2001000/3LabForParadigmsProgramming
/imperative style/IPZR18K__Vasyliev__Lab3__3.py
436
4.46875
4
print("This program help revers array which you inputted") sizeArr=int(input("Enter size array: ")) arr = [] for i in range(0,sizeArr): num = int(input(f"\nenter your num for element under the index {i}: ")) arr.append(num) print(f"Your array: {arr}") arrRevers=[] sizeArrRev = -(len(arr))-1 for i in range(-1,...
c3c06d93744e3895e345935f20cba12acb6a15c7
MelloWill36/Python_Para_Analise_Dados
/scikit_learn.py
2,611
3.609375
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LogisticRegression from sklearn.linear_model import LinearRegression """## Classificação""" # Coleta de Dados df = pd.read_csv('https://pycourse.s3.amazonaws.com/tempe...
b8d7cf7c5d0d3255e3a19b5101b176f16371851c
Maximuf/2017project
/recursion.py
645
3.734375
4
def replicate_recur(a, b): if not isinstance(a, int): raise ValueError if(b==[]): raise ValueError if a <= 0: return [] res = replicate_recur(a -1, b) res.append(b) return res def replicate_iter(a, b): if not isinstance(a, int): raise ValueError if(b==[])...
3c2a1f49980064a3eb7d734205fc5542315b644d
jacky881011/12-Hours-Python-Class
/#55 Dictionary comprehension.py
1,534
3.96875
4
#55 Dictionary comprehension # Dictionary comprehension = create dicitonaries using an expression # can replace for loops and certain lamda funciton # dictionary = {key : expression for ( key , value ) in iterable} # dictionary = {key : ...
5457837e21e447ca0c1626a31795a582a74eb740
jacky881011/12-Hours-Python-Class
/#28 Write a File.py
713
3.625
4
text1 = "\n(Append) Have a nice day! See ya" text2 = "Hello Bro!\nWelcome to Python Class\nAmazing for 12 Hours!\n" with open('C:\\Users\\jacky hsu\\Desktop\\Read_text.txt','w') as file1: # Rewrite the text in the text file (覆寫 會遮蓋先前的資料) file1.write(text2) with open('C:\\Users\\jacky hsu\\Desktop\\Read_text...
fcb60dc79dfe69fe25185739789ec37b9b37b1f9
jacky881011/12-Hours-Python-Class
/#59 Thread.py
1,356
3.953125
4
# thread = a flow of execution. Like a seperate order of instructions. # However each thread takes a turn running to achieve concurrency # GIL = (global interpreter lock), # allows only one thread to hold the control or the Python interpreter at any one time # cpu bound = program/task sp...
31bfdd4411a38e738c04aa021145c0753b5a55fa
jacky881011/12-Hours-Python-Class
/#29 Copy a file.py
584
3.765625
4
# copyfile() = copies contents of a file # copy() = copyfile() +permission mode + destination can be a directory # copy2() = copy() + copies metadata (file's creation and modificaiton times) import shutil import os #shutil.copyfile('#29Testfile.txt','copy.txt') #src,dst (source , destination) # copy ...
ce38b37407d9e3f10d31e250d46f7e0a63fb135b
jacky881011/12-Hours-Python-Class
/#24 Random.py
664
4
4
import random import time #1 roll = random.randint(1,6) # random number of integer (first,end) roll2 = random.random() # random number conclude float and integer print(roll) print(roll2) for i in range(10): ra = random.randint(0,10) print(ra) time.sleep(0.8) #2 game = ['r...
83843a0f0eb5a4662eda5b956a27034491783b8a
jacky881011/12-Hours-Python-Class
/#54 List comprehension.py
882
4.1875
4
# list comprehension = a way to create a new list with less syntax # can mimic certain lambda functions, easier to read # list = [ expression for item in iterable] # list = [ expression for item in iterable if conditional] # list = [ ex...
0a417b152d8ac77143023267e49a969593904b03
jacky881011/12-Hours-Python-Class
/#43 Abstract classes/Main.py
1,451
4.53125
5
# Prevents a user from creating an object of the class # + compels a user to override abstract methods in a child class # abstract class = a class which contains one or more abstrawct methods # astract method = a method that has a declaration but does not have an implementation. #-------------------------------not ...
825600e9cdc6ea00f4548c125afc62ee774fd7f9
LakshmiManohar/MiniProjects_Python
/App.py
151
3.5
4
class sqr(object): def square1(self): x1 = input() x2 = input() return x1,x2 j = sqr() t1,t2 = j.square1() print(t1,t2)
0e07a77b609d557cd4b1da3a46d706e88d910df7
Bounci/pythonLearning
/Sort/merge_sort_iteration.py
1,987
4.375
4
# -*- coding: utf-8 -*- # author:57213 # time:2021/10/23 # description:(2路)归并排序 ②迭代式 def merge(lists, left, mid, right): """ 实现将两个有序子表合并为一个有序子表。 :param lists: 待排序列表 :param left: 子列表1索引起始 :param mid: 子列表索引分界 :param right: 子列表2索引结尾 :return: 经过一次归并后的列表 """ temp = [] # 临时列表 i = l...
ce394f9d84db6b1a9a585cc48089f091467f100c
CeciliaCodes/badJokeBot
/run.py
823
3.8125
4
import time print('Hi, friend! What is your name?') userName = input() time.sleep(1) print('Oh, ' + str(userName) + ', huh? I like the sound of that. Do you want to hear a joke? Y/N?') answer = input() time.sleep(1) if answer == 'y': print('What do you call a can opener that doesn\'t work? A can\'t opener! Haha!')...
21f3c4671901ddd239b98315f610713767f96ab0
elizavetagordeyeva/myhomeworks
/HW7_var7_Gordeyeva.py
759
3.75
4
unwords = [] def f(): words = [] with open('test.txt', 'r', encoding="UTF-8") as f: text = f.read() words = text.split() return words def words(): amount = 0 words = f() for i in range(len(words)): if words[i].startswith('un') : unwords.append(word...
9da8f634e7d77e4ee16856387052247187037e60
bug-dva/Insight_Donation_Analytics
/src/donation-analytics.py
3,327
3.578125
4
import sys import pandas as pd import numpy as np import math #read input file as a pandas datafram and rename columns #column 10 is zipcode, need to convert to str raw_data = pd.read_csv(sys.argv[1], sep="|", header=None, dtype={10:str}) raw_data.rename(columns={0:'CMTE_ID'}, inplace=True) raw_data.rename(columns={7:...
aef6c52ff77a12596ec0a15af060a4fce61b94d9
CainVelasquez/expsin
/old_python/Interpolation.py
3,097
3.78125
4
class Polynomial(object): """ Polynomial defined by c[i] x^i + ... """ def __init__(self, coeff): self.coeff = coeff def __str__(self): string = 'y(x) = ' for i in range(len(self.coeff) - 1, 0, -1): string += '({:.2e})'.format(self.coeff[i]) + '*x^%i + ' % i ...
da2ea9584948112ff137197bd7c8843c244d4a6a
JoseMacevo/First_Python_Course
/Pruebas.py
1,022
3.984375
4
#def sum(*args): #value=0 #for n in args: #value +=n #return value # print(sum(5,5,4,7,2,4,6)) # a="Jose" # b="Acevo" # x="%s %s" % (a,b) # print(x) # .Format # Nombre=input("Introduce tu nombre: \n") # Edad=int(input("Introduce tu edad: \n")) # Nombre_mascota=input("Introduce el nombre de tú ma...
e6f4ca267d0e20e90cbf06bb4d1235cf811755c3
JoseMacevo/First_Python_Course
/Trabajo_Bucles/Bucle_While.py
1,395
4.25
4
# Bucles indeterminados (While). # Se ejecutan un número indeterminado de veces. # No se sabe a priori,cuántas veces se va a ejecutar el código de su interior. # Se ejecutarán el número de veces que sean necesarias durante la ejecución del programa. # Sintaxis. # contador=0 # while contador<10: # print("Ho...
657ba264d9d736ea529745a3e41a1c235ad69aed
JoseMacevo/First_Python_Course
/Archivos_Externos/Primeros_pasos.py
1,498
3.84375
4
from io import open modo = input("Introduzca el modo de apertura, (W) para modo escritura, (R) para modo lectura o (A) para modo adicción: ") Modo = modo.lower() if Modo == "w": archivo_externo = open("Primerarchivo.txt", "w") texto_1 = input("Introduzca el texto a guardar, por favor: ") archivo_e...
5f49c71167cfe113cae5c45ac83ecafb8a9e1514
trevorhauter/Pong
/main.py
4,804
4.09375
4
import turtle, functools, time, random #sets the score for both players at 0 score = [0, 0] def createPaddle(pos): # creates the left paddle paddle = turtle.Turtle() #sets the speed to the fastest paddle.speed(0) paddle.shape("square") paddle.color("black") paddle.shapesize(stretch_wid=5, ...
539a40195d5d5637eb6c1c38eaee138353a8f5e1
alamyrjunior/pythonExercises
/ex043.py
444
3.765625
4
print('App: Saiba seu IMC') peso = float(input('Digite seu peso: ')) altura = float(input('Digite sua altura em metros: ')) imc = peso/(altura*altura) r ="" if imc < 18.5: r = 'abaixo do peso' elif imc <=25: r = 'com o peso ideal' elif imc <= 30: r = 'com sobrepeso' elif imc <= 40: r = 'com ...
9505f183460bf7bd0de2e646803058e415c6072c
alamyrjunior/pythonExercises
/ex053.py
285
3.859375
4
print('Será que sua frase é um palindromo?') a = str(input('Digite sua frase: ')) b = str(a.replace(' ', '')) r = "" for c in range(len(b),0,-1): r += b[c-1] if r == b: print('Sua frase é um palíndromo!') else: print('Sua frase não é um palindromo...')
a82b0106a60de7d1b11679eef21dd49aa21b9364
alamyrjunior/pythonExercises
/ex012.py
114
3.5
4
preco = int(input('Digite o preço do produto: ')) print('O preço com 5% de desconto é', preco*0.95,'reais.')
3fd5e09fb521469a3fe8138681267ea9c416ffd0
alamyrjunior/pythonExercises
/ex009.py
468
4.125
4
num = int(input('Digite um número: ')) print('Sua tabuada é: ') print('1 x {} = {}'.format(num,num*1)) print('2 x {} = {}'.format(num,num*2)) print('3 x {} = {}'.format(num,num*3)) print('4 x {} = {}'.format(num,num*4)) print('5 x {} = {}'.format(num,num*5)) print('6 x {} = {}'.format(num,num*6)) print('7 x {} ...
c70b561909333e664f12bc318ce6a0f0d3bc2d59
alamyrjunior/pythonExercises
/ex034.py
215
3.765625
4
sal = float(input('Escreva o sálario de um funcionário: ')) aumento = "" if sal < 1250.00: aumento = sal*0.15 else: aumento = sal*0.10 print('O novo salário é de {} reais.'.format(sal + aumento))
0c0d95078a25bffb60ce54183cb4e80dac540cfe
alifbhadrika/shortest-path-a-star
/src/main.py
1,283
3.78125
4
''' Tugas Kecil 3 IF2211 Strategi Algoritma : Shortest Path with A* Algorithm Cr : Mohammad Sheva Almeyda Sofjan (13519018/K01) | Alif Bhadrika Parikesit (13519186/K04) ''' import graph import math import sys def start(): print("#### A* Shortest Path Finder ####") filename = input("ENTER MAP NAME (map.txt): "...
f576a9cb51048cdd0fd8898c3fdf7e87e8668ce1
Jongminfire/Baekjoon
/Python/1780 (종이의 개수, 분할정복).py
512
3.515625
4
n = int(input()) board = [list(map(int,input().split())) for _ in range(n)] mo = 0 z = 0 o = 0 def divide (x,y,size): global mo,z,o color = board[x][y] for i in range(x,x+size): for j in range(y,y+size): if color != board[i][j]: for nx in [x,x+size//3,x+size//3*2]: for ny in [y,y+siz...
9c79d7c61c16213945dfabaf24a8d874c6d87a3d
Jongminfire/Baekjoon
/Python/16938 (행성연결, 최소 스패닝 트리).py
789
3.609375
4
n = int(input()) edges = [] board = [[]] parent = [i for i in range(n+1)] result = 0 for i in range(n): temp = list(map(int, input().split())) board.append(temp) # 양뱡향이므로 반쪽만 추가 for i in range(1, n+1): for j in range(i+1, n+1): edges.append((board[i][j-1], i, j)) def findParent(v): if parent...
54e2ced7036737280928426e2b5c98455a646e07
Jongminfire/Baekjoon
/Python/1991 (트리 순회, 구현).py
652
3.703125
4
tree = {} for _ in range(int(input())): root, left, right = map(str, input().split()) tree[root] = [left, right] # 전위 순회 def preorder(node): if node == '.': return print(node, end='') preorder(tree[node][0]) preorder(tree[node][1]) # 중위 순회 def inorder(node): if node == '.': ...
3091df5212d93046e88da6f01fd76ab65bb6cbf3
Jongminfire/Baekjoon
/Python/5585 (거스름돈, 그리디).py
128
3.5625
4
money = 1000-int(input()) count = 0 coin = [500,100,50,10,5,1] for c in coin: count += money // c money %= c print(count)
3e2b7f2d3c3c849044be62a28d155a53ee3d5b6e
SUTDNLP/ZPar
/scripts/ccg/msupereval.py
1,203
3.546875
4
import sys if __name__ == "__main__": file = open(sys.argv[1]) # output file_r = open(sys.argv[2]) # reference total = 0 correct = 0 count = 0 error = 0 list = [] sentence_index=1 missing = [] for line in file: line = line.strip() if not line: line_r = file_r.readlin...
d8ba0d72a7c336aa11cd48dba63009d158f784eb
SUTDNLP/ZPar
/scripts/var/reorder/translate.py
908
3.609375
4
#encoding=utf8 import sys d = {'(' : '(', ')' : ')', ':' : ':', ';' : ';', '"' : '“', ',' : ',', '.' : '。'} def mapping(word, d): return d.get(word, word) def unmapping(d): u = {} for key in d: u[d[key]] = key return u def translate(sent): sent = sent.split() r = [] for word in sent: ...
aacd79469b7df9c2db8ecbd9ad2e1bc84af53713
SUTDNLP/ZPar
/scripts/pos/pos2raw.py
780
3.515625
4
# # Remove tag from corpus. # The word format word_tag. # Yue Zhang # import sys, os file=open(sys.argv[1]) output=open(sys.argv[2], "w") sep='/' if len(sys.argv) > 3: sep=sys.argv[3] n=0 count = 0 line=file.readline().strip() while line: n += 1 output_line = [] wordls = line.split(" ") for word in w...
b228e93884612b1d9799fa90acf8366f4c853d18
SUTDNLP/ZPar
/scripts/ccg/updatepos.py
575
3.53125
4
import sys if __name__ == "__main__": file = open(sys.argv[1]) postaged_file = open(sys.argv[2]) for line in file: posline = postaged_file.readline() line = line.strip() posline = posline.strip() items = line.split() positems = posline.split(); out = [] for index in range(l...
ba15c8f72f522dd13ede9ef531cb7436afa283b8
bharathb04/Hello-World
/Prog1.py
421
3.875
4
# Hello World program in Python #!/usr/bin/python import sys ##print "Counted", len(data), "lines." #learning python print "Hello, Python!" name = sys.stdin.readline() num1 = int(sys.stdin.readline()) num2 = int(sys.stdin.readline()) num3 = int(sys.stdin.readline()) num4 = int(sys.stdin.readline()) print "Your name i...
a8807e2194b32df3299df9ecc5adeb36caa0117b
suflorcita/peuler
/p03.py
579
3.640625
4
#The prime factors of 13195 are 5, 7, 13 and 29. #What is the largest prime factor of the number 600851475143 ? import math def largest_prime(n): '''Retorna el primo más grande que es factor de un numero n''' while n >= 2: if n % 2 == 0: max = 2 n = n / 2 else: ...
18e62a9c6df5efe24f2e33ebc2ac8e347a54565c
suflorcita/peuler
/p08.py
859
3.90625
4
#The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. #Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. #What is the value of this product? def product(number): '''Calcula el producto de los n digitos dado un string que...
a37937e21c2a7d732a2e61df389e06da7620b659
BitorqubitT/ADT
/Stack/ADTStack.py
747
3.5
4
from ADTStackNode import ADTStackNode class ADTStack: def __init__(self): self._top = None def isEmpty(self): return self._top is None def push(self, value): newItem = ADTStackNode(value, None, self._top) if not self.isEmpty(): self._top.previous = newItem ...
6f9518289794665d36d4934815916919513d0e71
dagleaves/Miscellaneous
/AdventOfCode2020/Day 3/p1_sol.py
388
3.78125
4
trees = 0 with open('input.txt', 'r') as file: lines = file.readlines() col = 0 for line in lines: line = line.rstrip() # Return character threw off lines if line[col] == '#': trees += 1 col += 3 # Repeat pattern to the right if col >= (len(line) - 1):...
f8ace194fe1d0bc32f6bd45242ff8b34795f06b7
dagleaves/Miscellaneous
/TFDatabase/dataframe_controller.py
269
3.515625
4
import pandas as pd try: database = pd.read_csv('database.csv') except FileNotFoundError: response = input('File not found! Download database? (y/n)') if response == '' or response.lower() == 'y': pass # Download database def search(toy):
c8afc73a1eddeb6a2afa10acdc0acc8101e98cd1
aayush7484/industryoriented
/exp2a.py
159
3.765625
4
import math as mt def area(radius): return mt.pi *(radius ** 2) def area(length, breadth): return length * breadth print(area(5)) print(area(5,6))
2575b84f030d753d2725fe49df0320c196f22871
KOUSHIKRAJ1/code-29122020-KOUSHIKAKKINAPALLI
/tests.py
1,191
3.609375
4
import unittest #i am using unittest module which has built in testing framework which consists of set of rules to be followed while building test cases and #test runner for running test cases automatically #i have taken three json files present in json folder for testing import BMI_Calculator #design test class wh...
5667fd9e2797d275155c1fcf7241a50c05f9cb10
mofei952/cookbook
/c07_functions/p01_functions_that_accept_any_number_arguments.py
1,387
3.75
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2019/8/26 21:04 # @File : p01_functions_that_accept_any_number_arguments.py # @Software: PyCharm """可接受任意数量参数的函数""" import html # 让一个函数接受任意数量的位置参数,可以使用*参数 def avg(first, *rest): return (first + sum(rest)) / (1 + len(rest)) print...
211ed691e189cf25f810442dcc4f1ef0e403bfdb
mofei952/cookbook
/c12_concurrency/p04_locking_critical_sections/01_lock.py
850
4
4
from threading import Thread, Lock, current_thread import time # 要在多线程程序中安全使用可变对象,你需要使用 threading 库中的 Lock 对象, # 就像下边这个例子这样: class SharedCounter: def __init__(self, initial_value=0): self._value = initial_value self._value_lock = Lock() def incr(self, delta=1): with self._value_lock: ...
99c5dab3fba844cb557861805dab7098d1fb51d2
mofei952/cookbook
/c06_data_encoding_and_process/p02_read_write_json_data.py
3,028
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2020/3/9 19:44 # @File : p02_read_write_json_data.py # @Software: PyCharm """ 读写JSON数据 json模块提供了一种很简单的方式来编码和解码JSON数据,其中两个主要的函数是json.dump()和json.loads() """ import json from collections import OrderedDict from pprint import pprint # 将...
ca442705037a51383730dddc5810611ffe39368d
mofei952/cookbook
/c02_strings_and_text/p01_split_string_on_multiple_delimiters.py
1,293
3.6875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2018/11/12 21:29 # @File : p01_split_string_on_multiple_delimiters.py # @Software: PyCharm """使用多个界定符分割字符串""" import re # string 对象的 split() 方法只适应于非常简单的字符串分割情形, 它并不允许有多个分隔符或者是分隔符周围不确定的空格。 # 当需要更加灵活的切割字符串的时候,最好使用re.split() 方法 line = 'as...
24047a28ab92098c5f48ed8cea3f210b4f0ea5d3
mofei952/cookbook
/c08_classes_and_objects/p17_create_instance_without_invoking_init_method.py
1,537
3.703125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : mofei # @Time : 2019/9/21 16:50 # @File : p17_create_instance_without_invoking_init_method.py # @Software: PyCharm """创建不调用init方法的实例""" import json from time import localtime # 通过__new__方法创建一个未初始化的实例 class Date: def __init__(self, year, month, da...
54ea7a0107b65d3393b4c6c5ba599e2f3b09aa61
SiegmannGiS/master2
/test/summertime.py
486
3.984375
4
import sys import calendar from datetime import datetime def day(year): laststart_sunday = max(week[-1] for week in calendar.monthcalendar(year, 3)) lastend_sunday = max(week[-1] for week in calendar.monthcalendar(year, 10)) return datetime(year=year,month=3,day=laststart_sunday, hour=2),datetime(year=y...
3972f4c396016ef08dc46c54d7a03715c1e46ffa
JacobU/italian-training
/train.py
2,353
3.9375
4
import sys import random def train(diff="easy"): with open("words.txt", "r") as rf: if rf.mode == "r": print("Welcome to your training session. Your mode is: ", diff) print("To end your session, type: 'exit'") if diff == "easy": lives = 3 ...
c8792da8fc9ca80d2eb70764204ee0087635b60b
Ayush19-01/GCI-N-Power
/run.py
357
3.78125
4
#Made for the sole purpose of GCI 2019 print() while True: inp1=int(input("Enter the power from 0 to 1024 : ")) print() base=2 final=1 for i in range(0,inp1): final*=base print("2 to the power {} is : {}".format(inp1,final)) print() tmp=input("Do you want to continue[y/N]:") print() if tmp=="y": continue ...
f6b46bda59785c7324c6fd949dc33d6c37b04bcc
SudoBobo/data_structures
/min_heap.py
1,366
3.59375
4
class MinHeap: def __init__(self, arr, arr_size): self.arr_size = arr_size self.arr = arr self.swap_counter = 0 self.swap_log = [] for i in range(arr_size // 2, -1, -1): self.sift_down(i) def sift_down(self, i): # idx of minimum element between arr[...
1508486b8b2044f997ced5c58278dbdea2ec952c
SudoBobo/data_structures
/multi_thread.py
1,170
3.53125
4
from queue import PriorityQueue procN, taskN = map(int, input().split(' ')) tasks_times = [int(task_time) for task_time in input().split(' ')] # to store processing tasks in format [time_when_proccessing_ends, proc_idx] pq = PriorityQueue() # to store answer in format [proc_idx, time_when_proccessing_started] proc_l...
960e8c3cb8465f738865cbf177ea59560f24a570
barak21-meet/meetyl1
/lab_3_a.py
2,283
4.09375
4
class Animal(object): def __init__(self,sound,name,age,favorite_color): self.sound=sound self.name=name self.age=age self.favorite_color=favorite_color def eat(self,food): print("Yummy!! "+self.name+" is eating "+food) def description(self): print(self.name+" is "+self.age+" years old and loves the color...
6ce5286f1a56c96c36c60321cc2e7ace49ab0eb8
barak21-meet/meetyl1
/Project_Updated.py
10,744
3.703125
4
""" f=open("NewFile.txt","w+") f.write("Text") f.close() f=open("NewFile.txt","a+") f.write("\nNew Text") f.close() f=open("NewFile.txt","r") if f.mode=='r': contant=f.read() print(contant) fi=f.readlines() for i in fi: print(i) f.close() print("HI") class User: def __init__(self,name,email,password): self.n...
6f6c004ce1507470838e96d893d1e4563d9b127c
mdaffafikri/kodingan-python
/inheritance.py
568
3.65625
4
class Ortu(): def __init__(self,last_name,hair_color): self.last_name = last_name self.hair_color = hair_color def show(self): print(self.last_name + " hair color is " + self.hair_color) class Child(Ortu): def __init__(self, last_name, hair_color, badge): Ortu.__i...
0e7b0b679d0446e37c07f3dff4ee2910d4f7ea34
mdaffafikri/kodingan-python
/pyramid.py
454
3.96875
4
import math height = int(input('Type NUMBER of height : ')) # pyramid = ['*','*','*','*','*','*','*'] pyramid = [] for i in range(height): pyramid.append('·') median = math.ceil(len(pyramid)/2-1) print(median) for i in range(median+1): if i == 0: pyramid[median] = '*' pr...
a589d5aa1bd54dd8afb0a0f7eacbfec2278f24a8
mdaffafikri/kodingan-python
/ifelse.py
227
3.71875
4
a = 1 b = 2 def cetak(a, b): if a < b: print(str(a) + " is less than " + str(b)) elif a > b: print(str(b) + " is less than " + str(a)) else : print(" they're equal ") cetak(20,20)
0f1ed6244643fb49162fa3093de64f10edc8b190
Magdaapl/Tilda16
/Lab 3/BintreeFilen.py
1,606
3.828125
4
class Bintree(): def __init__(self): self.root = None def __str__(self): return "bintree Class" def put(self, newvalue): # som sorterar in newvalue i trädet self.root = putta(self.root, newvalue) def __contains__(self, value): # som kollar om value finns i träd...
06180a05129ae179773167b341b2bf36097fa25e
sandycamilo/SPD-2.3-Debugging-Techniques-Lab
/Refactoring-Other-Techniques/extract_class2.py
2,073
3.59375
4
# # by Kami Bigdely # # Extract class # class Email: # def __init__(self, first_name, last_name, birthdate, email): # self.first_name = first_name # self.last_name = last_name # self.birthdate = birthdate # self.email = email # def send_hiring_email(self): # print("emai...
60fa83f949eefebc794636d93c1ed09e38c8061e
echirchir/daily-coding-problem
/coding-problem-day-1/solution.py
946
4.09375
4
def main(values, key): """ step 1: loop through the list (outer loop) step 2: loop through the list again (inner loop) step 3: check if value in outer loop matches second value in inner loop (don't add number to itself) step 4: if values from different indices add to key, return True step ...
6c3ccd865c75244f4f4db1f2f7b3691009ee1194
put-tzok/canonical-sylnaw
/pseudoknot.py
11,609
3.765625
4
#! /usr/bin/python3 import glob import itertools import json import logging import os.path import unittest from dataclasses import dataclass from typing import List @dataclass class Strand: ''' A continuous fragment of RNA structure. When Strand object represents 5'-3' direction, then begin < end. Otherw...
273122c60ef88601a5c39be88c15331057b48d3d
sukaran/NLTKBook
/ch3_exercises.py
20,112
4.375
4
import nltk, re from urllib import request #1 Define a string s = 'colorless'. Write a Python statement that changes this to "colourless" using only the slice and concatenation operations. s ='colorless' print(s[0:4]+'u'+s[4:len(s)]) #2 We can use the slice notation to remove morphological endings on words. For examp...
5174c1946b29d71b42acd2b292571f6a63178631
camoca/M01-hardware
/M03/3-4-17/pedra_paper_tissores_II.py
1,722
3.53125
4
# coding: utf8 ######################### # ASIGNAMOS VARIABLES # ######################### num = 31 Salir = False ####################################################### # EMPEZAMOS EL BUCLE CON WHILE Y PONEMOS CONDICIONES # ####################################################### while (Salir == False): if ( ...
57497f9a885ad278e622b1f00a33675cc4b87233
camoca/M01-hardware
/M03/POKER/PI_PA_TI_LI_SP.py
827
3.8125
4
# coding:utf-8 from random import randint ############################## # DECIMOS QUE ELIJA OPCION # ############################## J1=raw_input ("Elije PI/PA/TI/LA/SP: ") aleatorio=randint(1,5) if (aleatorio==1): J2="PI" if (aleatorio==2): J2="PA" if (aleatorio==3): J2="TI" if (aleatorio==4): J2="LA...
328a5a5015dfceba09b44a06374d5bf8e37865b0
amorosogabriela/informatica-generale
/es.5-6 p.292.py
568
3.515625
4
#esercizio_5 = Elenca propietà e metodi della classe Prodotto. #esercizio_6 = Definisci il metodo assegna_prezzo della classe Prodotto. class Prodotto: def __init__(self, nome, numero, provenienza, prezzo): self.nome = nome self.numero = numero self.prezzo = prezzo def assegn...
9fb6760bb609fbf6f6429171d1be2e1ed245347d
amorosogabriela/informatica-generale
/concorso pubblico.py
432
3.96875
4
print ("concorso pubblico") l = input("qual è il nome del primo candidato?") r = input("quel è il nome del secondo candidato?") x = int(input("punteggio del primo candidato:")) y = int(input("punteggio del secondo candidato:")) if x > y : print("ordine decrescente del punteggio:", x, y) if x < y : print...
075eb61aa0a2b80bf8e7f6859b0db7b07d8de54d
benataranburu/bs4-scraping
/html/main.py
439
3.515625
4
from bs4 import BeautifulSoup from urllib.request import urlopen from urllib.error import HTTPError, URLError #load soup try: src = urlopen('https://bbc.co.uk/news').read() except HTTPError as e: print(e) except URLError: print("Server down or incorrect domain") else: #parse content = BeautifulSoup...
a02dce92a8a948a530e98cda3db1ed92544a3fd6
SCollinA/python107-dictionary-exercises
/word_histogram_tally.py
1,456
4.0625
4
# Write a word_histogram program that asks the user for a # sentence as its input, and prints a dictionary containing the # tally of how many times each word in the alphabet was used in # the text. user_string = input("Please enter a sentence: ") # iterate over user_string, adding chars to temp_string until # spac...
1b1b7dadc28ab330e0beecef56a883f61cd2e86f
kepha-okari/password-locker
/run.py
10,493
4.1875
4
#!/usr/bin/env python3.6 ''' This is the file that runs the application(call the methods from credential and user classes) Import User Class from User Module and Credential Class from Credential Module ''' import random from user import User from credential import Credential def create_user(name, password): ''' ...
2859e96e94ecd587af4a1470ec8d5b7cdf352fef
aurelixv/ciphers
/analise_frequencia.py
1,081
3.84375
4
#!/usr/bin/env python3 import sys alfabeto = list(range(ord('A'), ord('Z'))) + list(range(ord('a'), ord('z'))) + list(range(ord('0'), ord('9'))) #abre o txt e retorna o seu conteudo, caso sucesso def abre_txt(arquivo): try: file = open(arquivo, 'r') mensagem = file.read() file.close() ...
618029874b4dbdcd64ae8930d15a088ed68efbd7
Mus1cBreaker/Hangman-Hyperskill
/Problems/Percentage/task.py
437
3.609375
4
def get_percentage(number, round_digits=0): for x in range(0, 2): number *= 10 x += 1 number = round(number, round_digits) if len(str(number).split(".")) > 1 and round_digits > len(str(number).split(".")[1]): round_digits = len(str(number).split(".")[1]) elif len(str(number).spli...
af5b0d920d4bdfe0ee6043dc6e5f82959a3b8049
MomenMushtaha/ECOR-1051
/lab4.py
1,357
4.28125
4
#Momin Mushtaha #101114546 from math import pi,sqrt,sin #ex1 def area_of_disk(radius): """ area_of_disk() takes the parameter as the radius of the circle, then it returns the disk area pi * radius^2 """ return pow(pi * radius,2) #ex2 def distance(x1,y1,x2,y2): ""...
4b8814220ef7d79fb08a0e46e210ea5e58985ce5
Derrior/tutorials
/python-tutorial/strings.py
312
4.15625
4
string = "abacaba" print(string.find('b'), "| first position of letter b") print(string.rfind('b'), "| last position of letter b") print(string[1:-1], "| substring") print(string * 2, "| double string") print(string.replace('b', 'd'), "| can replace anything in your string") print(string.replace('b', "dddd"))
5837d80299e86ec53631bd9bb03f1da7873d63f8
ArthurPatricio/NBA_BI_Project
/get_teams.py
1,864
3.625
4
# Import Libs import requests import pandas as pd def get_teams(): seasons =input('Enter the seasons you would like to get data from separated by space (ex:"2020-21 2019-20"): ') season_list = seasons.split() per_mode = 'PerGame' headers = { 'Connection': 'keep-alive', ...
b4938e77748104c981b656d1713102dfb6a7f19a
NightlySide/PyRogueLike
/core/items.py
741
3.71875
4
# -*- coding: utf-8 -*- class Chest: def __init__(self, y, x, size, items=[]): self.x = x self.y = y self.size = size self.items = items class Item: def __init__(self, name, itemType, desc=""): self.name = name self.type = itemType self.desc = desc ...
5bb4c6e916805142f51f7ed35163e3ba7a5bd432
webclinic017/ScalpingAlgoTrader
/utils.py
12,506
3.71875
4
import pandas as pd import csv from math import log, sqrt def create_set(input_file, output_file): """ Create a CSV file with the relevant data needed to predict the next-minute direction of stock prices. Inputs: input_file: A CSV file from the Wharton TAQ database containing the price, time, and...
58f33eba851006188bba21a86bbf119d84569a4e
parayc/FaceTrack_UE4
/pythonScripts/knn.py
608
3.578125
4
from sklearn.neighbors import KNeighborsClassifier import numpy as np import pandas as pd import csv as csv def buildKNN(file,PCA=False): df = pd.read_csv(file, header=0) # Store the id column before dropping it id_column =df["id"] # Drop it from th df = df.drop(["id"],axis=1) # Convert to usable format tra...
50a7ebc8b00dc92e020c4a96c1fccde9ce7ccd87
ryanlaycock/spelling_game
/game.py
1,608
3.96875
4
#freds main bit of the game(it is just the logic) import random import time import os from random import randint def jumble(word,jumble_): array = list(word) wordlen = len(word) counter = 0 while counter < jumble_: temp = [] lettre_sel = random.randint(0,wordlen-1) temp = array[lettre_sel] lett...
927cea52db2d7efefb856ef6a4c79657d43fdba6
Nanared1/Python-Codes
/Python programs/y2k.py
510
3.53125
4
## y2k CCC 1999 problem 2 import datetime from datetime import date no_line = int(input("# of lines: ")); words = []; for x in range(no_line): words.append(input()); date.today(); datetime.date(2012, 8, 12); date.today = '2012' ##Before 02/03/04, but not after December 19, 99, ##there was a rehash of the 5...
09d9c2b91f319ebdf9aa26a1b8f98663b746f868
Nanared1/Python-Codes
/Python programs/classes test1.py
1,357
4.03125
4
##Nana Abekah ##April 9th, 2018 ##Objects and Classes Test 1 ##ICS 4UO ##Mr. Veera class widget: ##Widget class to store information for different objects. def __init__(self, quantity): self.quantity = quantity; def show_stock(self): return(self.quantity); def remove_stock(self, amount): ...
d9d5ddb3abae722f66521c6ebd3ac9669c84c0c1
Nanared1/Python-Codes
/Python programs/Chapter 6/exercise 18.py
331
3.984375
4
original_sentence = input("Enter a sentence: "); remove_word = input("Enter a string: "); if remove_word in original_sentence: print(original_sentence[0:original_sentence.index(remove_word) - 1]+ original_sentence[(original_sentence.index(remove_word) + len(remove_word)):]); else: print("Can't remove...
7cbff4f3900e1d1fbcd061b6cb4e7f2854bedeaf
Nanared1/Python-Codes
/Python programs/fileIOex1.py
475
3.875
4
##Nana Abekah ##May 09 2018 words = ''; length = 0; sentence = ''; count = 0; with open('data.txt', 'r') as file: for line in file: words = line; words = list(words); for i in range(len(words)): if(not words[i].isalpha()): words[i] = ' '; else: count += len(words[i]); for i in range(...
78471f708c1c30626889a1263ac85c71a6cd4fba
jlmann-cp-1/guess-a-number
/guess_a_number_ai.py
1,804
4.03125
4
import random # config low = 1 high = 1000 # helper functions def show_start_screen(): print("*************************") print("* Guess a Number A.I! *") print("*************************") def show_credits(): pass def get_guess(current_low, current_high): """ Return...
40fc568bfd28cb23511fd6567a8da421623f44d8
s2ljeun/learnpython
/practice18.py
867
3.578125
4
# 8-2. 다양한 출력 포맷 # 공통: 총 10자리 공간을 확보 # 오른쪽 정렬하고, 빈칸을 공백으로 둠 print("{0: >10}".format(500)) # 양수일 때는 +로 표시, 음수일 때는 -로 표시 print("{0: >+10}".format(500)) print("{0: >+10}".format(-500)) # 왼쪽 정렬하고, 빈칸을 _로 채움 print("{0:_<+10}".format(500)) # 3자리마다 콤마를 찍어주기 print("{0:,}".format(100000000000)) print("{0:+,}".format(1000000...
27fd74bf1c7982bbcaf4e0ec36d57a8e1e16c0f0
ochinchina/my-tools
/json2text_log.py
3,746
3.828125
4
#!/usr/bin/env python import abc import argparse import json import sys """ convert log from json format to human readable text format the json log can be read from stdin or from a file The text log can be written to the file or stdout """ class JsonLogReader: @abc.abstractmethod def read_log(self): ...