blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
d9df4158b15accfba5c36e113f383140409ab02a
Lycurgus1/python
/More_exercises/More_Methods.py
2,013
4.21875
4
# From the Calculator file importing everything from Calculator import * # Inheriting the python calculator from the previous page class More_Methods(Python_Calculator): # As per first command self not needed def remainder_test(): # Input commands get the numbers to be used, and they are converted to ...
d445e006605290b0c4511c1272f6ff07ed306ca0
renatojobal/fp-utpl-18-evaluaciones
/eval-parcial-primer-bimestre/Ejercicio8.py
1,333
4.15625
4
''' Ejercicio 8.- Ingresar por teclado tres variables, dichas variables siempre tendrán como valores letras mayúsculas de abecedario. Sabiendo que por ejemplo la letra “E” es menor que la letra “P”; establezca una solución que permita determinar ¿Cuál de las tres letras ingresadas, aparece primero en el abecedario ? E...
e03113509c9c78385a00ba2253044ab698d974a6
xtiancc/Andalucia-Python
/listaintstr.py
561
4.15625
4
def mostrarNombres(nombres): print("\nListado:") for name in nombres: print(name) print("LISTA NUMEROS Y NOMBRES") print("-----------------------") numeros = [20, 14, 55, 99, 77] print(numeros[0]) numeros.sort() print("Los numeros ahora están ordenados") for num in numeros: print(num) nombres...
0e936ac3aad4c7147f61cccc3a28422378e02707
xtiancc/Andalucia-Python
/actividad11coche.py
1,229
4.09375
4
class Coche: marca = "" modelo = "" velocidad = 0 encendido = False def arrancar(self): if (self.velocidad == 0 and self.encendido == False): print("Ha arrancado el coche.") self.encendido = True else: print("El coche ya está arrancado.") def...
596c008de4505e2390016c02eb1157be77219b40
xtiancc/Andalucia-Python
/bucles.py
180
3.921875
4
print("EJEMPLO BUCLES") print("--------------") print("WHILE:") contador = 0 while (contador <= 5): print("Contador: " + str(contador)) contador += 1 print("FIN DEL PROGRAMA.")
d774c1f864cbd93683fd8ce59f56fbb687ebf10e
xtiancc/Andalucia-Python
/libreriamath.py
334
4.03125
4
from math import floor, ceil, trunc print("LIBRERÍA PYTHON") print("---------------") num1 = 20 num2 = 3 division = num1 / num2 print("La división es: " + str(division)) # Vamos a redondear al número inferior print("Floor: " + str(floor(division))) print("Ceil: " + str(ceil(division))) print("Trunc: " + str(trunc(...
ff7e25911df4182ab79ec832f384c565e9e41f49
ysze/python-refactorings
/week4/refactored.py
1,118
3.625
4
import random from datetime import datetime SUITS = ["d", "c", "h", "s"] RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank def value(self): if self.is_ace: return 11 ...
2fb440c166779042c7992f1e7ab044a17227e9a1
JulianRamm/LaboratoriosPC
/Laboratorio3.py
11,457
3.90625
4
## Punto 1 def multpl(arr): multp = 1; for i in range(len(arr)): multp *= arr[i] #Esta función multiplica todos los elementos de un arreglo return multpl def punto1(): arr = list(map(int, input("Ingrese los números separados por espacio").split(" "))) print(multpl(arr)) ## Punto 2 def fa...
fe0814129fdf524e9e1209436101aeacb98637a9
cocagolau/NEXT_13-00_Preschool
/day2/d2_base1.py
1,404
4
4
# randomize the number from random import randint com = [0,0,0,0] veri_sum = 0 # veriry the number while veri_sum == 0 : # veri = [0,0,0,0,0,0,0] veri_num = 0 i = 0 while i <= 2 : j = 3 while j > i : if com[i] == com[j] : # veri[veri_num] = 1 veri_num = veri_num + 1 j = j - 1 i = i + 1 # print ...
c344f12c996af9ca588dab90dc7ae1fdebf78ec4
cocagolau/NEXT_13-00_Preschool
/practice/130226/print.py
270
3.5625
4
principal = 1000 rate = 0.05 numyears = 5 year = 1 while year <= numyears: principal = principal * (1+rate) print ("%3d %0.2f" %(year, principal)) print format(year,"3d"), format(principal,"0.2f") print "{0:3d} {1:0.2f}".format(year,principal) print ("") year += 1
355b308b57a3abbade340a6b96a3c35f81f18382
cocagolau/NEXT_13-00_Preschool
/practice/130228/func.py
1,614
3.625
4
'''def foo(x, items=None): if items is None: items=[] items.append(x) return items print foo(3) print foo(1) print foo(2) # transfer or return parameter a = [1,2,3,4,5] b = [] def square(items): for i,x in enumerate(items): items[i] = x*x return items b = square(a) print a print b # ---- #2 def factor(a)...
700f7cf6df4e71882e8745f1e1f357d3c0f1352f
ToniMarinovic/Predavanje8
/Konverter.py
425
3.5625
4
#pretvaranje kilometara u milje #milja je 0.621371 kilometara milja = 0.621371 print "Bok" while True: km=int(input("Koliko kilometara: ")) print ("Ovo je " + str(km * milja) + " milja") jos= raw_input("Zelis jos? ") if jos != "da": break print ("Kraj") #pita korisnika zeli li jos #ako da...
96bd3ba07935156db5aec7236089eedde95828b2
jsatch/taller_introduccion_python
/codigo/s5/diccionarios.py
695
3.875
4
""" { 'pepito': { 'twitter': '@pepito', 'numero': '123432523' }, 'juanito': { 'twitter': '@juanito', 'numero': '2134324' }, } """ # [ [ "Pepito", "@pepito", "234234" ] , [ "Juanito", "@juanito", "2342342"] ] lista_amigos = {} continuar = True while continuar == Tr...
567ac98c7c6f81a1844f83737921470f60b55726
nandocoeg/pemrograman-python
/scripts/jawaban-kuis-soal3.py
396
3.5
4
#program soal 3 a = 0b10100 b = 0b01001 bitwise_and = a & b bitwise_or = a | b bitwise_xor = a ^ b print("Nilai dari operasi bitwise \"AND\" antara a:%d, b:%d -> (a and b) = %d "%(a,b, bitwise_and)) print("Nilai dari operasi bitwise \"OR\" antara a:%d, b:%d -> (a or b) = %d "%(a,b, bitwise_or)) print("Nilai dari opera...
aea7cb686aa85662fd93c34ce0b4d33c493c18ff
leandroaa7/OS
/Scheduling/project1/main.py
581
3.546875
4
import fifo import sjf import rr import prior myprocesses = [] def mensagem(): print(" ") print("Digite o processo ou 0 para executar") print(" ") def inputProcess(): mensagem() process = 1 while(process != 0): process=input("Processo: ") if(process == 0): return 0 ...
4a6a9033092ae714cdfc6359930c888283c5f23c
Python3pkg/PTVS
/Python/Tests/TestData/DebuggerProject/SteppingTestBug509.py
106
3.828125
4
def triangular_number(a): return a + triangular_number(a-1) if a > 0 else 0 print((triangular_number(3)))
1f2f112c4be5a594fc7ab0aa511088a5c2be357c
bharathkumarreddy19/basicpythonprograms
/quadratic_equation.py
468
3.96875
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 24 19:09:41 2020 @author: bhara_5sejtsc """ import cmath def quadratic_eq(a,b,c): d = (b**2) - (4*a*c) return d a = float(input("First coefficient: ")) b = float(input("Second coefficient: ")) c = float(input("Third coefficient: ")) d = (b**2) - (4*...
7e5e9434aa37eec69040d4ce1dcb20bd2b93507d
anirudh708/code
/Numbers.py
2,420
3.59375
4
from fractions import Fraction import itertools from math import factorial def P(event,space): return Fraction(len(event & space),len(space)) def cross(A, B): return {a+b for a in A for b in B} def combos(items, n): return {' '.join(combo) for combo in itertools.combinations(items,n)} def choose(n,c): ...
c93fa4b4296227d96b422e20da455e60e2ea8db9
ceantolentino06/PythonStack
/python/fundamentals/functions_interm2.py
1,611
3.90625
4
# 1. Update Values in Dictionaries and Lists x = [ [5,2,3], [10,8,9] ] students = [ {'first_name': 'Michael', 'last_name' : 'Jordan'}, {'first_name' : 'John', 'last_name' : 'Rosales'} ] sports_directory = { 'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'], 'soccer' : ['Messi', 'Ronaldo', 'Rooney'...
9c31a9ea00820538532a982702217d470b03bbfe
jlin22/code-watcher
/main.py
975
3.71875
4
from stopwatch import Stopwatch import sys if __name__ == '__main__': # create the stopwatch class to do the work sw = Stopwatch() # define the messages flags_message = '\n'.join(['Please enter a valid flag.', 'Here are a list of the valid flags:', ' -b Begin the stopwatch', ' -e End ...
9fccd51455ddd28fe80670531168317fd81ca877
lgh2/NYC_Python_Algorithms
/tree_search_solution.py
1,246
3.96875
4
class Node: """node objects that can represent a tree""" def __init__(self, name, children): self.name = name self.children = children def __str__(self): return self.name #instantiate graph nodes: h = Node("h", []) g = Node("g", [h]) d = Node("d", []) e = Node("e", []) f = Node("f",...
4647a2dee94584ff690df2b5e3ca0ca309ccbbb2
aoogo/data-science-from-scratch
/chapter-2.py
2,988
3.5
4
# _*_ coding: utf-8 _*_ import random # 2.2.3 生成器和迭代器 # 每个dict都有一个item()方法可以返回它的键值对列表 # 更常见的做法是使用iteritems()方法:当我们在列表上迭代的时候它延迟yield为每次一个键值对 data = {'tom': 90, 'James': 78, 'Aurora': 92} print data.items() # [('James', 78), ('Aurora', 92), ('tom', 90)] print data.iteritems() # <dictionary-itemiterator object at 0x0...
21d97a2dbed3f2cccc099aa5b24500de27913517
simonlindgren/btf
/mergedb.py
768
3.8125
4
import sqlite3 import os # Get connections to the databases db_a = sqlite3.connect('livetweets.db') db_b = sqlite3.connect('histtweets.db') # Get the contents of a table b_cursor = db_b.cursor() b_cursor.execute('SELECT * FROM tweets') output = b_cursor.fetchall() # Returns the results as a list. # Insert those co...
273e5eac8e0727161536b80629905211fa55b175
anandgaurav456/Online-Problem-Solution
/max_min.py
6,497
3.625
4
import numpy as np import random import pandas as pd import pulp import matplotlib.pyplot as plt import math def nCr(n,r): g = math.factorial return int(g(n)/g(r)/g(n-r)) print("Enter n(even):") # Taking Population Size num = int(input()) Rl = [] f = np.zeros((100,num)) for i in range(1,6): for j in range...
c01309448e62b93a882090ba46cfc860fe421a1e
computerscienceioe/Lesson-13
/Challenge 2.py
2,033
3.953125
4
# import matplotlib.pyplot as plt # plt.plot([1,3,4,2,1]) # plt.show() # import matplotlib.pyplot as plt # numSiblings = [1, 3, 4, 2, 1] # plt.plot(numSiblings) # plt.show() # import matplotlib.pyplot as plt # numSiblings = [1, 3, 4, 2, 1] # plt.plot(numSiblings,"yo") # plt.title("Siblings") # plt.xlabel("List...
5ec7134c60a21a3f50ec61dc6a1bdf7debf489b4
Dreegen/tensor
/dev.py
1,619
3.796875
4
# data preprocessing import pandas as pd # produces a prediction model in the form of an ensemble of weak prediction models, typically decision tree import xgboost as xgb # the outcome (dependent variable) has only a limited number of possible values. # Logistic Regression is used when response variable is categorical ...
9dd7427407426dc00ed48062a6e35a799a36e1a4
asylbek09/mycode
/shebang.py
148
3.953125
4
#!/usr/bin/env python3 name = input("Enter user's name: ") day = input("Enter day of the week: ") print("Hello " + name + "! Happy " + day + "!")
eeea3adc0b1d704f8de470bfcef1b1f684494287
asylbek09/mycode
/countries/guesscapital.py
1,546
4.03125
4
#!/usr/bin/env python3 import json import random import os def clearScreen(): os.system('cls' if os.name == 'nt' else 'clear') def getCapitals(): capitals_json = open ('capitals.json', "r") capitals_data = json.load(capitals_json) return capitals_data def prompt(): client_prompt = input("To pl...
4a7b9b5ff7cd0e824c866852b6f066413cf9ec6e
Gavr09/stepik_python_basics_and_applications
/src/1.6.py
1,499
3.734375
4
''' Sample Input: 4 A B : A C : A D : B C 4 A B B D C D D A Sample Output: Yes Yes Yes No parents_names_dict = {'A':[], 'B':['A'], 'C':['A'], 'D':['B', 'C']} ''' def add_one_class(parents_names_dict, class_name): parents_names_dict[class_name] =...
e845a4a20b9241f411ea3bf6c17b627826f7d02d
Gavr09/stepik_python_basics_and_applications
/src/3.1_1.py
636
3.578125
4
# s = 'abab' # a = 'ab' # b = 'ba' # операция: замена всех вхождений строки a в строку s на строку b # s: abab -> baba -> bbaa # после какого минимального количества операций в s не останется вхождений a # вывести число операций либо Impossible, если их больше 1000 s = input() a = input() b = input() num = 0 while T...
9e86e43abb55997733ac34293c23010e35fab36f
Gavr09/stepik_python_basics_and_applications
/src/2.2_1.py
251
3.78125
4
import datetime lst = input().split() year, month, day = (int)(lst[0]), (int)(lst[1]), (int)(lst[2]) days = (int)(input()) date1 = datetime.date(year, month, day) date2 = date1 + datetime.timedelta(days=days) print(date2.year, date2.month, date2.day)
29a427ac8c5a6299d90595bf2da2c00d5793e957
abeishenaliev7/geektech-month-2
/hw lesson 3.py
661
3.703125
4
import random wordlist = ['mercedes', 'toyota', 'honda', 'globus'] secret = random.choice(wordlist) guesses = 'eoaubm' turns = 5 while turns > 0: missed = 0 for letter in secret: if letter in guesses: print (letter, end=' ') else: print ('_', end=' ') ...
a960f21e2fe7276c250cd09d7807845e73bc8962
Microboiii/pycrobit
/pycrobit/utils.py
985
3.59375
4
import json from collections import namedtuple from typing import Dict class JSONStringCorruptError(Exception): pass def main(): pass def string_to_dict(string: str) -> Dict: try: return json.loads(string) except json.decoder.JSONDecodeError: raise JSONStringCorruptError(f"Cannot...
80a11ffa961d83208461d324062f37d9f7b1d830
yesusmigag/Python-Projects
/Functions/two_numberInput_store.py
444
4.46875
4
#This program multiplies two numbers and stores them into a variable named product. #Complete the missing code to display the expected output. # multiply two integers and display the result in a function def main(): val_1 = int(input('Enter an integer: ')) val_2 = int(input('Enter another integer: ')) mul...
a5643896a36f24aab394372e73d18e052deb624c
yesusmigag/Python-Projects
/List and Tuples/10 find_list_example.py
710
4.34375
4
"""This program aks the user to enter a grocery item and checks it against a grocery code list. Fill in the missing if statement to display the expected output. Expected Output Enter an item: ice cream The item ice cream was not found in the list.""" def main(): # Create a list of grocery items. grocery_list ...
8c4a55fa444dc233b0f11291147c224b0ed1bdb5
yesusmigag/Python-Projects
/List and Tuples/18 Min_and_Max_functions.py
500
4.40625
4
"""Python has two built-in functions named min and max that work with sequences. The min function accepts a sequence, such as a list, as an argument and returns the item that has the lowest value in the sequence.""" # MIN Item my_list = [5, 4, 3, 2, 50, 40, 30] print('The lowest value is', min(my_list)) #display Th...
dd45561d7cd82adbdf04407a589bf562bf593aa0
yesusmigag/Python-Projects
/Functions/math_functions.py
1,146
3.90625
4
'''Math Module Function Description acos(x) --------------- Returns the arc cosine of x, in radians. asin(x) --------------- Returns the arc sine of x, in radians. atan(x) --------------- Returns the arc tangent of x, in radians. ceil(x) --------------- Returns the smallest integer that is greater than or equal to x. ...
9f47556628fe391494d37b8ae1080212bef35c81
yesusmigag/Python-Projects
/File and Files/nameSearch.py
809
3.6875
4
def readBoysNameFile (filename): boysNameFile = open(filename,'r') boysNameList = [] boyName = boysNameFile.readline() while boyName != "": boyName= boyName.rstrip("\n") boysNameList.append(boyName) boyName = boysNameFile.readline() return boysNameFile def readGirlsNameFi...
73037324693d0170667f036a2e61fcd1e586895f
yesusmigag/Python-Projects
/File and Files/Chapter6_Project3.py
639
4.125
4
'''Write a program that reads the records from the golf.txt file written in the previous exercise and prints them in the following format: Name: Emily Score: 30 Name: Mike Score: 20 Name: Jonathan Score: 23''' #Solution 1 file = open("golf.txt", "r") name = True for line in file: if name: print("Nam...
d4766c0fa0f0fd70fa3768893ca43b015a69334a
MingZx8/MNIST
/MNIST.py
4,998
3.609375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: MingZ # @Date created: 05 April 2018 # @Date last modified: 24 May 2018 # Python Version: 3.6 # Description: Construct a classification model on the MNIST data set in the form of a deep neural network # Perform and compare two or more methods of hype...
e68b87c07f75f58cedafd3904bb45b07c419fa12
WisTiCeJEnT/intro-to-python
/day2/ptx.py
268
3.703125
4
def is_7_valid(x): return not (x%7==0 or '7' in str(x)) # ถ้ามี 7 หรือหาร 7 ลงตัว ตอบ False # ถ้าไม่ใช่ตอบ True n = int(input()) while(is_7_valid(n)): n = int(input()) print('You lose')
a17b37799fc18f43e77cff558e0442dcf2117735
WisTiCeJEnT/intro-to-python
/day1/pt6.py
360
3.890625
4
n = int(input()) if n < 0 or n > 100: print('Invalid score') else: if n >= 80: print('A') elif n >= 75: print('B+') elif n >= 70: print('B') elif n >= 65: print('C+') elif n >= 60: print('C') elif n >= 55: print('D+') elif n >= 50: ...
c3ee68016e9a3eb3abedaf6175eff4521e7b06e3
njharper26/filter_type_NH
/filter_type.py
1,071
3.6875
4
sI = 45 mI = 100 bI = 455 eI = 0 spI = -23 sS = "Rubber baby buggy bumpers" mS = "Experience is simply the name we give our mistakes" bS = "Tell me and I forget. Teach me and I remember. Involve me and I learn." eS = "" aL = [1,7,4,21] mL = [3,5,7,34,3,2,113,65,8,89] lL = [4,34,22,68,9,13,3,5,7,9,2,12,45,923] eL = [] s...
5a0e3bc605ea516ec5079711ca1675b0a7820eb0
techdragon/focus
/focus/environment/io.py
5,099
3.609375
4
""" This module provides the stream encapsulation class for the runtime environment. """ import os import errno class IOStream(object): """ Basic abstraction interface for IO streams. Example Usage:: >>> io = IOStream() >>> data = io.read() # read from input stream >>> io.w...
f735a64f0aa2132efd6a12b57cc812bc87a29444
JaimeFanjul/Algorithms-for-data-problems
/Sorting_Algorithms/ascii_encrypter.py
1,301
4.40625
4
# ASCII Text Encrypter. #-------- # Given a text with several words, encrypt the message in the following way: # The first letter of each word must be replaced by its ASCII code. # The second letter and the last letter of each word must be interchanged. #-------- # Author: Jaime Fanjul García # Date: 16/10/2020 ...
bc1531aa0683a6035b4770928f239f7a651414c2
harsh-98/bare-socket
/python/server.py
1,131
3.6875
4
# import the socket library import socket # A string predefined in the form of HTTP resopnse. (More on HTTP responses later) server_message = """\ HTTP/1.1 200 OK <HTML> <Head> <Title>Title: Bare Socket</Title> </Head> <Body> <center> <h1> Hello from server! </h1> </center> </Body> </HTML> """ # define a ...
ff9e0cf48a4f0fe9c2fd254e8ffd73d79c8dee73
shashank4902/assignment-12
/prgm1 ass12.py
176
3.921875
4
1#sum all the items in a dictionary def returnSum(mydict): sum=0 for i in mydict: sum=sum+mydict[i] return sum dict={'a':100,'b':200,'c':300} print("sum:",returnSum(dict))
3a99e95ef6347b626ec08347330ebb6388bceece
gamebars/Programming
/Practice/11/Python/11.py
280
3.890625
4
chsilo = int(input("Введите число возводимое в степень: ")) stepen = int(input("Введите степень данного числа: ")) i = 0 result = 1 while (i < stepen): result = result*chsilo i = i + 1 print("Результат: ",result)
0672f353d0761505f3968f8f52831e88784062b3
riley-csp-2019-20/final-exam-semester-1-skylar-85740
/2019fallfinalexamCSP.py
1,259
3.921875
4
#2019-20 Fall Computer Science Principles Final Exam #Ms. Haubold #Name #Skylar Strieper #Date #12/18/19 #### INSTRUCTIONS #### #Create an etch a sketch turtle game #The turtle should move with the arrow keys (up, down, left and right), and draw #Space should clear the screen #o and p should make the pen size bigg...
5eb4aae3cedf1e101de199cfa7d5590b32a303e0
luohenyueji/OpenCV-Practical-Exercise
/ITEM 1-9/ITEM9 centroid_blob/single_blob.py
717
3.515625
4
#coding=utf-8 import cv2 import numpy as np # read image through command line img = cv2.imread('./image/circle.png') # convert image to grayscale image gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert the grayscale image to binary image ret,thresh = cv2.threshold(gray_image,127,255,0) # calculate m...
0cadf36fe1ce77de51173ffb6b629af21e4240eb
hweeeeeei/pythonLearn
/1.语法&特性&函数/21-函数-lambda匿名函数.py
349
4.0625
4
# 当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。 L1 = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])) print('L1', L1) # 匿名函数lambda x: x * x实际上就是: def f(x): return x * x # 关键字lambda表示匿名函数,冒号前面的x表示函数参数。
75159eed891f7601fbbb6ffce52035f7f0ddfbbc
hweeeeeei/pythonLearn
/1.语法&特性&函数/8-函数.py
1,545
3.546875
4
# 文档 https://docs.python.org/zh-cn/3/library/functions.html#abs # 绝对值 print(abs(-20)) # 定义一个函数 def my_ads(x): # 验证参数类型 if not isinstance(x, int): raise TypeError(' x type error') if x >= 0: return x else: return -x print('my_ads(20)', my_ads(20)) print('my_ads(-30)', my_ad...
23110bd9dab1677217124ac09ebf7894b5c88749
hweeeeeei/pythonLearn
/7.常用第三方模块/图像处理Pillow/图像处理Pillow.py
667
3.6875
4
# 操作图像 from PIL import Image # 打开一个png图像文件,注意是当前路径: im = Image.open('test.png') # 获得图像尺寸: w, h = im.size print('Original image size: %sx%s' % (w, h)) # 缩放到50%: im.thumbnail((w // 2, h // 2)) print('Resize image to: %sx%s' % (w // 2, h // 2)) # 把缩放后的图像用png格式保存: im.save('thumbnail.png', 'png') # 其他功能如切片、旋转、滤镜、输出文字、...
8f893c5e788c02f117c11e8370473639af4ed16f
hweeeeeei/pythonLearn
/6.常用内建模块/集合collections.py
2,933
4.09375
4
# collections是Python内建的一个集合模块,提供了许多有用的集合类。 # namedtuple # 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: p = (1, 2) # 定义一个class又小题大做了,这时,namedtuple就派上了用场: from collections import namedtuple Point = namedtuple('Point', ['x', 'y']) p = Point(1, 2) print(p.x) print(p.y) # 坐标和半径表示一个圆,也可以用namedtuple定义: # namedtuple('名称', [属性...
0c919fea9f752231915f44bbc9f70e266e18c999
hweeeeeei/pythonLearn
/1.语法&特性&函数/22-函数-装饰器.py
1,185
3.953125
4
# 代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 # 定义能打印日志的decorator # 接受一个函数作为参数,并返回一个函数 def log(func): def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper # 观察上面的log,因为它是一个decorator,所以接受一个函数作为参数,并返回一个函数。我们要借助Python的@语法,把decorator置于函数的定义处: # 把@log放到n...
1e1f1712c71d36fa6f928fd4320fe1890530192f
tkinoti/python-basics-class
/excercise.py
1,534
3.984375
4
# yes = input("Type Yes :") # yes= yes.title() # # if yes == "Yes": # print(yes) # else: # print("No") #================================================== # a=int(input("value of a: ")) # b=int(input("value of b: ")) # c=int(input("value of c: ")) # # def compare(a,b,c): # if a>=b and a>=c: # return...
174b7ce69648d6e0d8201a823dd50694a43b8127
GruppoIcon/EsameIcon
/Esame Icon/src/knn.py
3,958
3.53125
4
from collections import Counter import matplotlib.pyplot as plt from classifier import Classifier import numpy as np from scipy.spatial import distance class KNN(Classifier): """Classificazione K-NN""" def __init__(self, k=1, dist_fn=distance.minkowski, p=2): self.k = k self.dist_fn = dist_fn...
8e5bd7c01408ee3cfe8e498fd8ba8a2cb2f68b69
AndreyLvovich/lesson1
/8.py
437
4
4
# Определить, является ли год, который ввел пользователь, високосным или не високосным. year = int(input('Введите год в формате yyyy: ')) if year % 4 != 0: print('Обычный') elif year % 100 == 0: if year % 400 == 0: print('Высокстный') else: print('Обычный') else: print('Обычный')
b10c16cec96b454a78b263cc577b327a38de7d4c
xtoolNH/data-normalizer
/normalizer.py
9,737
3.515625
4
import csv import datetime import threading import logging def set_flag(date_to_be_verified, start_date, end_date): """ set_flag() function to verify if a date is: 1. Equal to Recording Start Date 2. In between Recording Start Date and Recording End Date 3. Equal to End Date ""...
fdaf92daf50780e2532e1ef1463e2057b00949ce
Ersain/advanced-algorithms-course
/hw1/skylines.py
336
3.8125
4
def skylines(arr): arr.append(0) stack = [-1] res = 0 for i in range(len(arr)): while arr[i] < arr[stack[-1]]: height = arr[stack.pop()] width = i - stack[-1] - 1 res = max(res, height * width) stack.append(i) arr.pop() return res print(skyli...
830ce742c97ba708f13661a37ba989fce8afaf95
ftrijillo/PythonFiles
/Interview_Practice/fizzbuzz.py
264
3.75
4
numbers = [45,22,14,65,97,72] for item,num in enumerate(numbers): if num % 3 == 0 and num % 5 == 0: numbers[item] = 'fizzbuzz' elif num % 3 == 0: numbers[item] = 'fizz' elif num % 5 == 0: numbers[item] = 'buzz' print(numbers)
8101036620958f2a0d1207f68ce135a30315acb6
ftrijillo/PythonFiles
/gametasks.py
1,147
3.59375
4
#!/usr/bin/env python3 from os import remove, rename def printInstructions(instruction): print(instruction) def getUserScore(userName): content = [] users = "" try: users = open("userScores.txt", "r") except IOError: users = open("userScores.txt", "w") users.close() ...
8f0ae9aa9f81fa8ee166939e8eb78dcb3b4a290b
ftrijillo/PythonFiles
/Udemy/PrimeNumbers.py
368
4.09375
4
num = 100 def print_primes(): for i in range(1, num): for j in range(2, i): #This will not run when i is 1 or 2 because of the range command, so both #1 and 2 will be counted as prime numbers automatically. if (i % j) == 0: break else: ...
6bcafaddba2f0baaf7f55e966ee7e2d6d442ecb2
ftrijillo/PythonFiles
/week1/Odds.py
786
3.671875
4
from random import choice class Coin(object): def __init__(self): self.side = 'heads' def flip(self): possibilities = ['heads', 'tails'] self.side = choice(possibilities) def get_side(self): return self.side class Die(object): def __init__(self, max_side): se...
4eaaf83a389a8392f53bd3094dedf6cb45fadd72
aa2858/csc-648
/application/src/initializer/remove/table.py
623
3.671875
4
class DBTable(object): def __init__(self, name, column_creator, columns, entries): self._name = name self._column_creator = column_creator self._columns = columns self._entries = entries def get_entries(self): return self._entries def drop_table_string(self): ...
e4ff4a3537d833859d33e5aafcfe9e0a1237a773
MasterCourses/Image-Processing
/02.Histogram Equalization(HE)/HE_to_Gray.py
1,727
3.6875
4
# Implement Histogram Equalization program to gray image from PIL import Image import numpy as np import matplotlib.pyplot as plt # Input a grayscale image gray_img = Image.open('my_cat(low_contrast).png').convert("L") L = 256 # 8 bits grayscale # Define 8 bits grayscale value into an array gray_scale = gray_img.hi...
310b6e32ff4fe4f3571853b22805cec48946cc1b
dingqqq/LeetCode
/climbingStairs.py
383
3.625
4
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 if n == 2: return 2 resultDict = {1: 1, 2: 2} for i in range(3, n+1): result = resultDict[i - 1] + resultDict[i...
070a397eee09743f1e32ef34c3fc0cbf48a711e7
dingqqq/LeetCode
/invertBinaryTree.py
734
4
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def invertTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if roo...
27e8e509c20323fb76b067ebc67978101a702fc7
CoderVij/python
/BinarySearch.py
1,034
4
4
#Vijesh.V @FreakoutGames #Binary Serach def BinarySearch(elementToSearch, startIndex, endIndex): if endIndex >= startIndex: midIndex = int((startIndex + endIndex) / 2) midElement = elementsList[midIndex] if midElement == elementToSearch: return midIndex elif elementToSea...
9ee38d5d7d7341cf22b00b23b8defe1e15ac10ea
gitsana/Python_Tutorial
/M4-Objects/M4-Objects_Notes.py
3,420
4.0625
4
- Not variables but "named references to objects" in Python - even adding two numbers (like x = 5, then x += 2) is assigning pointer to new total and garbage collecting 5 and 2, and x points to 7 - everything is immutable >> x = 10 >> y = x this means both are pointing to "10" can do >> id(x) or >> id(y) and they ...
bc0c2d7871b4263c62e43cd04d7370fc4657468e
gitsana/Python_Tutorial
/M5-Collections/words.py
1,607
4.5
4
#!/usr/bin/env python3 #shebang # indent with 4 spaces # save with UTF-8 encoding """ Retrieve and print words from a URL. Usage: python3 words.py <URL> """ from urllib.request import urlopen def fetch_words(): """Fetch a list of words from a URL. Args: url: The URL of a UTF-8 text document Returns: A list o...
6ae6369d3fa48125e9f801423625dd2e8d7d6d66
achalparikh/python-projects-
/flower.py
541
4.03125
4
import turtle window = turtle.Screen() window.bgcolor("black") circle = turtle.Turtle() circle.shape("arrow") circle.color("pink") circle.speed(100) def flower1(): counter = 0 while (counter < 36): circle.circle(20) circle.right(10) counter = counter + 1 def fl...
694a082b5a007e239306039cc5be570802924b0d
chlolgr/Swarming-Behavior-Genetic-Algorithm
/Grid.py
4,272
4
4
import matplotlib.pyplot as plt import numpy as np from Prey import Prey """ The Grid class is the easiest to get. It contains all animal on the grid and has the function to do visualizations. That's pretty much it. The show() function isn't animated. Why is it there, you ask? I don't know anymore. Could be useful, ...
a90012c851cad115f6f75549b331cfa959de532b
JasleenUT/Python
/ShapeAndReshape.py
587
4.28125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 3 22:47:26 2019 @author: jasleenarora """ #You are given a space separated list of nine integers. #Your task is to convert this list into a 3X3 NumPy array. #Input Format #A single line of input containing space separated integers. #Output For...
47bc810d11c4fda590dd8872b9cab366558c06bc
lostarray/ProjectEuler
/21.py
956
3.609375
4
# Amicable numbers # Problem 21 # Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). # If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. # For example, the proper divisors of 220 are 1, 2, 4, 5,...
30f89e9a8442219d03d85774bb2b1f2895a5d4a4
lostarray/ProjectEuler
/17.py
1,865
3.859375
4
# Number letter counts # Problem 17 # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # NOTE: Do not count s...
b075e3e92afde6cad97f512cd2ec56cd06cb0f93
ChrisCooper/mostly-benevolent-infection
/tests/test_data_generation.py
4,116
3.734375
4
import unittest from math import sqrt import fun import graph_generation import models class TestClassroomGeneration(unittest.TestCase): """ These tests are rough and incomplete, since the spec is pretty flexible. Tests for the classrooms depend on randomness, so testing the distribution etc. is one ...
2a7e6887c86220bbc05fde257fde7264cbdfc154
ashish-bisht/ds_algo_handbook
/two_pointers/squaring_sorted_array.py
813
3.828125
4
# Algo ::: Sabse phele ek keft and ek right ppointer rakho, fir highest_square_index ko last index rakho , kyunki max wahi aaega, fir left right check karo and karte raho def make_squares(arr): squares = [0 for i in range(len(arr))] left = 0 right = len(arr)-1 highest_square_index = len(arr)-1 wh...
c4763d97b99c1061aa4e8eb68d7346dcb3ea05fc
ashish-bisht/ds_algo_handbook
/dp/un_bounded_knapsack/rod_cutting.py
670
3.59375
4
def rod_cutting(lengths, prices, n): row_length = len(lengths)+1 col_length = n+1 matrix = [[0 for _ in range(col_length)] for _ in range(row_length)] # Intialisation is not required as at 0 it will zero always... # logic for row in range(row_length): for col in range(col_length): ...
115096bc5934d3cf695d9a16149e84ef1df0a60f
ashish-bisht/ds_algo_handbook
/dp/fibonacci/stairaces_rec.py
276
3.640625
4
def count_ways(n): if n == 0: return 1 if n == 1: return 1 if n == 2: return 2 return count_ways(n-1)+count_ways(n-2)+count_ways(n-3) def main(): print(count_ways(3)) print(count_ways(4)) print(count_ways(5)) main()
5c8061c586c1ca3f86bb662601a812e3cf46fdec
ashish-bisht/ds_algo_handbook
/top_k_elements/frequency_sort.py
613
4.375
4
import collections import heapq def sort_character_by_frequency(str): str_dict = collections.Counter(str) heap = [] for key, val in str_dict.items(): heapq.heappush(heap, (-val, key)) final_string = '' while heap: val, char = heapq.heappop(heap) final_string = final_stri...
6890610afd1a5feb2593bb28270e87569c812029
ashish-bisht/ds_algo_handbook
/dp/lcs/min_del_dp.py
706
3.5
4
def min_del_ins(s1, s2): row_len = len(s1)+1 col_len = len(s2)+1 ans = 0 # create matrix.. matrix = [[0 for _ in range(col_len)] for _ in range(row_len)] # Already intialisesd to zero for row in range(row_len): for col in range(col_len): if s1[row-1] == s2[col-1]: ...
8b00382de062a6e1ba33e2b2966ac25517eb9655
ashish-bisht/ds_algo_handbook
/top_k_elements/kth_largest_number.py
426
4.0625
4
import heapq def find_k_largest_numbers(nums, k): result = [] heap = [] for num in nums: heapq.heappush(heap, -num) for _ in range(k): result.append(- heapq.heappop(heap)) return result print("Here are the top 3 numbers: " + str(find_k_largest_numbers([3, 1, 5, 12, 2, 11]...
79777526175029c85aa4d655f3503dadc7c9b7c9
Inzaniak/pybistuff
/Python pool/pypool.py
1,883
3.65625
4
import multiprocessing import time from string import punctuation text = "Hello World!, this is the text to be reduced. We need to split this text and then remove all the words shorter than 5 characters. " * 100 def clean_word(word): for c in word: if c in punctuation: word = word.replace(c,''...
76879ff431e419c0dcabdd9fd3aa8c10c685161a
Inzaniak/pybistuff
/NLTK Text Classification/main.py
1,746
3.546875
4
from nltk import NaiveBayesClassifier from nltk import classify import random ITA = open('data/italiano_utf.txt','r',encoding='utf-8').read().split('\n') ENG = open('data/english_utf.txt','r',encoding='utf-8').read().split('\n') def language_features(name): features = {} features["first_letter"] = name[0].low...
8d5312a4489988236f75acb7025db9c86dd4d58a
Krishesh/AngelAssignment
/q1.py
864
4.1875
4
class Person: firstlen = 0 middlelen = 0 lastlen = 0 def __init__(self, first_name, middle_name, last_name): self.first_name = first_name self.middle_name = middle_name self.last_name = last_name def first_name_length(self): for _ in self.first_name: Per...
91c9b7099c65c97b0a8f66a790a3d43d95572711
suryadevs/Data-Management-and-Visualization
/Week 4.py
5,706
3.921875
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import pandas as pd import numpy as np income_groups = ['high_income', 'upper_middle_income', 'lower_middle_income', 'low_income'] income_limits = [6000, 2200, 600] employrate_groups = ['75% - 100%', '50% - 75%', '25% - 50%', 'l...
3bf435e090879b6f92f502f033381b186424060a
devonjones/rando
/rando/meaning.py
2,344
3.65625
4
class Meaning(object): def __init__(self, usage, tags, meanings, sources): self.usage = usage self.tags = tags self.meanings = meanings self.sources = sources self.__set_location__() def __set_location__(self): if self.usage.startswith('-') and self.usage.endswith('-'): self.location = 'inner' elif...
5a43eac53818f66ef5dab94cec27377050af1b67
amit-d-bahir/MotionDetector
/video_recorder.py
1,199
3.65625
4
import cv2, time """ We create a VideoCapture object from a video file or we can also use our webcam 0 triggers our webcam for a file we need to provide it the path """ video = cv2.VideoCapture(0) no_of_frames = 0 while True: no_of_frames += 1 # the loop helps us to display a series of frames as captured by ...
698cb02b9a82ce23df9b39fdce843d7b2f83fe69
vodinhhung/Algorithm_practicing
/code_force/236A/a.py
193
3.71875
4
name = input() store = {} count = 0 for i in name: if i not in store: count += 1 store[i] = 1 if count % 2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
d212f8827f8b19fe3dd63c1f062ee7dfa7f017b7
tjasakpetric/FizzBuzz
/fizzbuzz.py
446
4.03125
4
#Naloga FizzBuzz print "*FizzBuzz game*" choice = raw_input("Enter a number between 1 and 100: ") try: for number in range(int(choice)+1): if number % 3 == 0 and number % 5 == 0: print "FizzBuzz!" elif number % 3 == 0: print "Fizz" elif number % 5 == 0: ...
5aca4f287ee186ff3d91caf30a957a83e46e2bd4
prabeshbk/pythonStart
/4pythonNumbers.py
306
3.90625
4
# int float complex a,b,c=1,3.0,1j # only j indicated complex number print(type(a),type(b),type(c)) # we change the data type a,b,c=complex(a),int(b),c print(type(a),type(b),type(c)) # random numbers # python doesnt have a random function but has built in random module used to make random numbers
7c8f282db9814f0124aadb93f5e6bc6f53db89d1
Dannypa/AutomatedTesting
/main.py
6,484
3.53125
4
import os from colorama import Fore import colors SEPARATOR = '-' * 30 def read_multiple_lines() -> str: """Reads multiple lines input, ignoring empty lines and spaces in the beginning and in the end of the lines""" res = "" current_line = input() while current_line != 'arr': current_line = c...
adb5fbb0aad35c8c88e2e4eea556f1177fe1afa5
desertzk/pythondemo
/lhy/pytorch_demo.py
2,100
3.6875
4
import torch import torch.nn as nn import torch.nn.functional as F from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np torch.manual_seed(446) np.random.seed(446) t = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7...
ee7c3b8e7a0a65291feed90d0d94adbfab99697a
desertzk/pythondemo
/numpy_learn.py
272
3.8125
4
import numpy as np X=np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]]) print(X[1:])#取第一行后面的所有 print(X[2:])#取第二行后面的所有 print(X[:1])#取第一行 print(X[:2])#取第二行前面的所有 print(X[1:2]) print(X[1,2])
e78192bf26c190dcbcd7e3dd55f625e18ddec024
AirmanKolberg/financeApp
/monthlyBills.py
1,159
3.671875
4
import pandas as pd from generalFunctions import verify_float, verify_yes_or_no, clear_screen def export_monthly_bills(bill_name_list, amount_list): framework = {'Bill Name': bill_name_list, 'Amount': amount_list, } df = pd.DataFrame(framework, columns=['Bill Name', 'Amount'...
8d21f4851640ceb7f240c7643344394d12e5cb90
renh/pyRaman
/porlarization/xyz2rtp.py
967
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- #============================================================================== # Module documentation """ FileName : xyz2rtp.py Purpose : convert cartesian coordinates to spherical Author : Hao Ren Version : 0.1 Date : , 2011 """ #=====================================...
527e078e88f77c92b9029b9267970d122451c481
sat-wik/Pattanaik_story
/amazing.py
518
4.0625
4
""" This program demonstrates IMPORT statements and LOOPS """ # import statements go FIRST! (Top of your code) import time #for variable name in range(start, stop, step) #OR #for variable name in range(stop): This will start at 0 and ste by 1 for Thoe in range(1, 11): print ("Hello " + str(Thoe)) #Count to 100 ...
6cfa11a58ffd90b886c4ab8783d2553432742023
codeaid-dev/Python_practice
/Practice_module/calc.py
177
3.71875
4
import ball r = int(input('半径 >>')) volume = ball.volume(r) area = ball.area(r) print(f'半径{r}cmの球の体積は{volume:.2f}立方cm、表面積は{area:.2f}平方cm')
6fee2a41f3d6c07d95f1b546fcede4b3b05b33c6
codeaid-dev/Python_practice
/Practice_object/destructor.py
357
3.671875
4
class Counter: count = 0 def __init__(self): print('in',end=' ') Counter.count += 1 def __del__(self): print('del',end=' ') Counter.count -= 1 @classmethod def how_many(cls): return cls.count a = Counter() b = Counter() Counter() #Counter() #a = None c = Coun...