blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
48326564ae35b86f2b150ac2fe6d4e89f5cedc6d
matijapretnar/uvod-v-programiranje
/odlozisce/datoteke-s-predavanj/08-razredi/kwargs.py
394
3.53125
4
def f(x, y, *args, a=10, b=20, **kwargs): return (x, y, args, a, b, kwargs) def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b class IteratorFibonaccijevih: def __init__(self): self.a, self.b = 0, 1 def __next__(self): self.a, self.b = self.b, self.a...
ccb76eb886793f93f7043bc54356b82771f65b0d
matijapretnar/uvod-v-programiranje
/04-zanke/zanke_v_pythonu.py
683
3.75
4
import math def gcd(m, n): while n: m, n = n, m % n return m def gcd(m, n): while n != 0: m, n = n, m % n return m def gcd(m, n): while n != 0: o = m % n m = n n = o return m gcd(42, 15) # m n o # 42 15 ? # 12 # 15 # 12 # ...
e19b3221a6eaa14ca85ca8c1d1d7ac176b97aa44
shadycannon/adventofcode2016
/9.py
1,815
3.625
4
#!/usr/bin/python f = open('9_input', 'r') input_str = f.read().replace('\n','') def decode_chunk(chunk): length = int(chunk[1:-1].split('x')[0]) mult = int(chunk[1:-1].split('x')[1]) return (length,mult) #given a string starting with '(' this returns a chunk if it exists def get_chunk(input_string): chunk =...
7e0d4bab6c794044117701693d078647f92e062d
chicocheco/codewars_exercises
/duplicate_encode.py
725
4.09375
4
"""The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate. NO...
95596215ef57cb7fa798d7fa57ae552ebb61471a
neelbshah/projecta
/myexp21.py
184
3.515625
4
s1="HELLO WORLD" s2="THIS IS PYTHON PROGRAMMING" print s1 print s2 print s1.title() print s1.isdigit() print s1.islower() print max(s2) print min(s1) print s2.split() print s2.split(" ",2)
4b5274de9583ae552b16cab33ef513774b51ac7a
Nunomatos7/leci_2ano
/LFA/Projeto/geometrics-lfa-07-master/pygame/Ponto.py
1,220
4.375
4
import math class Ponto: def __init__(self, x, y): self.x = x self.y = y #setter method to change the value of the x coordinate def set_x(self,x): self.x = x #setter method to change the value of the y coordinate def set_y(self,y): self.y = y #getter ...
52f53d069b997d1d722d1111813c940d9dfa72ad
gokuldaz/rsa
/encrypt.py
1,491
3.875
4
#expects encryption key and filename import sys from decimal import Decimal import os.path e = int(sys.argv[1]) n = int(sys.argv[2]) word_list = sys.argv[3:] #print(word_list) #fetching each character and storing in a list char_list = [] for w in word_list: for i in range(len(w)): char_list.append(w[i])...
d314e04a6b1ed2636e8bc73f67af718a5026612f
ArjunAssi/MerkleHash
/Merkle_Hash_Util.py
2,690
3.515625
4
# ------------------------------------------------------------ # AUTHOR : LEONIDAS # DATE : 25th APRIL 2016 # DESCRIPTION : CLASS TO PROVIDE HASHING UTILS #------------------------------------------------------------ import hashlib import os #------------------------------------------------------------ # Function to g...
ad728ccd8a3d0bb843a6788f3b5bb88a4b4e76bd
SandieKateFentonBG/Brain
/Brain - Copie.py
2,379
3.609375
4
from math import exp def sigmoid(z): return 1 / (1 + exp(-z)) class Brain: def __init__(self, theta=None, layers_size=None, x=None, y=None): if theta: self.layers = len(theta) + 1 self.layers_size = [len(theta[0][0]) - 1] + [len(theta_l) for theta_l in theta] elif lay...
c09365382c5424f0c9626eaf6c8b89284eec493a
AmyOrz/FullStack
/python/script/Fn2.py
312
3.796875
4
#*args 可变参数,接受一个tuple# #**kw 关键字参数,接受一个dict(map)# def calc(*num): sum = 0 for n in num: sum = sum +n return sum arr = [1,2,45,67,89] print calc(*arr) def person(name,age,**kw): print name,age,"other:",kw fck = {"gf":"hehe","city":"yunnan"} person("yh",23,**fck)
3c3fdf3892ca95964db92487345834fd788fbae9
AmyOrz/FullStack
/python/script/sort.py
169
3.703125
4
arr = [1,4,7,8,3232,31,4,23123,3] print sorted(arr) def reversed_cmp(x,y): if x>y: return -1 elif x<y: return 1 else: return 0 print sorted(arr,reversed_cmp)
900de72bc952f47d9911c7602aa2b2b8cec779f0
optionalg/programming-introduction
/Aula 08/aula08-lab-08.py
504
4.0625
4
""" Aula 8 Exercício de Laboratório 8 Maior e menor números Autor: Lucien Constantino """ count = 0 num = 1 biggest_number = 0 smallest_number = 0 while True: num = int(input("Digite um número: ")) if num < 0: break if num > biggest_number: biggest_number = num if count == 0: smallest...
abdf7c2da004306fba141e6364f8c5fda1f80c46
optionalg/programming-introduction
/Aula 11/ex_2.py
636
3.640625
4
""" Exercício 2 Autor: Lucien Constantino """ def get_number(): n = int(input("Digite um número ")) if n < 0: print("Número deve ser positivo") else: return n def divisors_of_number(number): divisors = [] for i in range(1, number): if number % i == 0: divisors....
e7f0dce7f0d4324909f42b4fb8899de6f83763b8
optionalg/programming-introduction
/Aula 11/ex_5.py
2,632
3.90625
4
""" Exercício 5 Autor: Lucien Constantino """ class City(): def __int__(self, code, passenger_cars, traffic_accidents_with_victim): self.code = code self.passenger_cars = passenger_cars self.traffic_accidents_with_victim = traffic_accidents_with_victim def __eq__(self, other): ...
06daf093e025cb63b0d4e9aa72b1a7cfbc3a110e
optionalg/programming-introduction
/Aula 10/Aula10-Lab-07.py
380
4.03125
4
def get_number(): n = int(input("Digite um número: ")) if n < 0: print("Número deve ser positivo") else: return n def factorial(number): multiplier = 1 for i in range(1, number + 1): multiplier *= i return multiplier for n in range(get_number()): term = get_numbe...
c1ce570ae64a98ab9aa59fb2553c55028146d915
optionalg/programming-introduction
/Aula 09/Aula9_Tut-1.py
325
3.828125
4
""" Aula 9 Exercícios Tutoriados 1 Lê e valida nota Autor: Lucien Constantino """ def get_nota(): while True: nota = float(input("Digite a nota: ")) if nota < 0 or nota > 10: print("Nota inválida") else: return nota nota = get_nota() print("Nota do aluno: {0:.1f}"....
0d90bebc632014bb7527e236e50a63ffaae4d715
optionalg/programming-introduction
/Aula 07/aula7-LAB-05.py
414
3.59375
4
kwHourPrice = float(input("Preço do KW/hora: ")) kwHourConsumption = float(input("KW/hora consumidos no mês: ")) consumerType = input("Tipo de consumidor (I = Industrial, C = Comercial, R = Residencial): ") bonus = 0 if consumerType == "I": bonus = 1.15 elif consumerType == "C": bonus = 1.05 cost = (kwHourConsumpti...
f2258625a9045bb2c2e7435948002403124d11e7
optionalg/programming-introduction
/Aula 10/Aula10-Extras-04.py
613
4.09375
4
def read_number(): while True: number = int(input("Digite um número: ")) if number <= 0: print("Número deve ser maior que 0.") else: return number def fibonacci_series(n): seed_f1 = 1 seed_f2 = 1 series = [seed_f1] if n == 1: return series ...
5881282cabc0368ebea635492b3c7f36c7bd8816
optionalg/programming-introduction
/Aula 10/Aula10-Duplas-02.py
304
4.3125
4
def is_even(number): return number % 2 == 0 max_number = int(input("Digite um número: ")) number_of_even_numbers = 0 for i in range(0, max_number): if is_even(i): print(i) number_of_even_numbers += 1 print("Quantidade de números pares: {0}".format(number_of_even_numbers))
74f7d462280ca3e012599db532336d97d8e971c4
optionalg/programming-introduction
/Aula 07/aula7-LAB-06.py
753
3.8125
4
""" Aula 7 Laboratório Exercício 6 Banco Imobiliário Autor: Lucien Constantino """ # Banco Imobiliário spot = input("Digite o nome da casa: ").upper() if spot == "IMPOSTO": print("Se cair nesta casa o jogador deve pagar 10% de seus honorários") elif spot == "TERRENO OU EMPRESA SEM DONO": print("Se cair num terreno ...
6e8ff9e32bd9c965156fd01303b35c905fbf4c38
optionalg/programming-introduction
/Aula 08/aula08-lab-05.py
279
3.984375
4
""" Aula 8 Exercício de Laboratório 5 Multiplicação sem * Autor: Lucien Constantino """ n1 = int((input("Digite um número: "))) n2 = int((input("Digite outro número: "))) sum = 0 count = 0 while count < n2: sum += n1 count += 1 print("{0} * {1} = {2}".format(n1, n2, sum))
08e82561db95c998b689c4541230456be945ee65
optionalg/programming-introduction
/Aula 06/aula6-LAB-3.py
1,546
3.71875
4
# 👊🖐️✌ import random from enum import Enum class Hand(Enum): Rock = 1 Paper = 2 Scissors = 3 class Winner(Enum): Draw = 0 P1 = 1 P2 = 2 print("Pedra = 👊\nPapel = ✋️\nTesoura = ✌️") def bet(player): betString = input("Aposta do jogador {0}: ".format(player)) if betString == "Pedra": return Hand.Rock ...
a78039e152255fe9935ca6e4abdfd54b8d5ab176
optionalg/programming-introduction
/Aula 04/aula4-lab2.py
329
3.90625
4
import math # Aula 4 # Exercício Laboratório 2 x = float(input("Type x: ")) y = float(input("Type y: ")) z = float(input("Type z: ")) result = math.pow(x, 2) + math.pow(y, 2) + math.pow(z, 2) print("x^2 + y^2 + z^2 = {0:.2f}".format(result)) result = math.pow((x + y + z), 2) print("(x + y + z)^2 = {0:.2f}".format(re...
09752c908d2dbcded8981783f1df664cea9d5cc1
optionalg/programming-introduction
/Aula 11/ex_4.py
3,170
3.875
4
""" Exercício 4 Autor: Lucien Constantino """ def get_weight(): while True: weight = float(input("Digite o peso: ")) if weight < 0: print("Peso inválido.") else: return weight def get_height(): while True: height = float(input("Digite a altura: ")) ...
d90c3694c124824e563fff7137bf818d2c49239e
abdulnsheikh/Projects-in-Python
/Automation/Multiclipboard/Multiclipboard.py
874
3.53125
4
# Abdulnaser Sheikh # https://www.linkedin.com/in/abdulnasersheikh/ # Multiclipboard #Usage is in the form of commmand line argument #file name save <keyword> - saves clipboard to keyword #file name <keyword> - loads keyword content to clipboard #file name list - copies list of all keywords to clipboar...
e4d63019b6f373ddbaccddb45c8fb1004bd61783
Dharani379/BEST-ENLIST-Internship
/day25.py
622
3.84375
4
#1q import datetime def convert(date_time): format = '%b %d %Y %I:%M%p' # The format datetime_str = datetime.datetime.strptime(date_time, format) return datetime_str date_time = 'Mar 24 2021 03:24AM' #2q from datetime import date, timedelta delta = date.today() - timedelta(5) print('Current Date...
780f71afea0e691740211a14a2b427391a8d01c8
Dharani379/BEST-ENLIST-Internship
/lambda funcs.py
1,292
3.953125
4
>>> #create lambda fun that multiplies argx with arg y >>> l=lambda x,y:x*y >>> print(l(93,7)) 651 >>> #creating a fibonacci series to n using lambda >>> from functools import reduce >>> fib=lambda n :reduce(lambda number :number*n,nums) >>> fib=lambda n :reduce(lambda x,_:x+[x[-1]+x[-2]],range (n-2),[0,1]) >>>...
19d67827358c0f3770ff5f269a53aff0febc938e
Lunarstaff/Python3ObjectOriented
/Book_chapters/Chapter_2/testcode/MyFirstClass_v1.4.py
1,355
4.125
4
# MyFirstClass_v1.3.py import math # 定义Point类 class Point: ''' Point类 ''' # 增加初始化函数 def __init__(self, x=0, y=0): ''' 初始化方法: 初始化一个新的Point类型对象的位置,如果没有给初始值,新的点类型对象默认位置为(0, 0) :param x: :param y: ''' self.move(x, y) # 增加一个新的方法move,允许我们...
08e65a8fa3826754d34d1e40073cfb9790cd1c86
Lunarstaff/Python3ObjectOriented
/Book_chapters/Chapter_2/testcode/MyFirstClass.py
325
3.703125
4
# MyFirstClass.py # 定义一个什么都不做的类Point class Point: pass # 实例化两个对象 p1 = Point() p2 = Point() # 通过点记法给一个实例化的对象赋予任意属性 p1.x = 5 p1.y = 4 p2.x = 3 p2.y = 6 # 检查对象的属性 print(p1.x, p1.y) print(p2.x, p2.y) # 输出为: # 5 4 # 3 6
cd94caaf3d0e01ab6d672b63dfd8cf897b60d4f2
Beebkips/UWTCodingDojo
/Advanced - Python/Lesson 2 - My First Game/myGame.py
4,152
3.5625
4
''' Gliding movement of ball object ''' import pygame, random pygame.init() run = True # background screen = pygame.display.set_mode((400,600)) screenrect = screen.get_rect() background = pygame.Surface(screen.get_size()) background.fill((255,255,255)) background = background.convert() # ball ballsurface = pygame....
6f3cf649c2d05bb2cebf64decb57aecf9a7912db
namnd15197/Python_OverView
/Data_Wrangling/Data_Wrangling.py
9,187
3.71875
4
#3.0 Introduction # Load library import pandas as pd # Create URL url = 'https://raw.githubusercontent.com/chrisalbon/simulated_datasets/master/titanic.csv' # Load data as a dataframe #dataframe = pd.read_csv(url) #print(dataframe.shape) # Show first 5 rows #print(dataframe.head(5)) #3.1 Creating a Data Frame # Loa...
ad4084f67b5d907d4ec79b8d44fea4e5534c2164
namnd15197/Python_OverView
/Handling_Numerical_Data/Handling_Numerical_Data.py
7,382
3.546875
4
#4.1 Rescaling a Feature # Load libraries import numpy as np from sklearn import preprocessing # Create feature feature = np.array([[-500.5], [-100.1], [0], [100.1], [900.9]]) # Create scaler minmax_scale = preprocessing.MinMaxScaler...
b03cc9b17382d9c6f8057aca0a1580e4de3bed24
namnd15197/Python_OverView
/Chapter16_Logistic_Regression/Chapter16_Logistic_Regression.py
818
3.796875
4
#16.1 Training a binary Classifier #load libraries from sklearn.linear_model import LogisticRegression from sklearn import datasets from sklearn.preprocessing import StandardScaler #load data with only two classes iris = datasets.load_iris() features = iris.data[:100,:] target = iris.target[:100] #standardize featu...
eb4e3ed229421a8b360787f7053fdf77acc90899
namnd15197/Python_OverView
/Handling_Categorical_Data/Handling_Categorical_Data.py
5,986
3.875
4
#5.1 Encoding Nominal Categorical Features # Import libraries import numpy as np from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer # Create feature feature = np.array([["Texas"], ["California"], ["Texas"], ["Delaware"], ["Texas"]]) # Create one-hot encoder one_hot = LabelBinarizer() # One-hot e...
76fabca03208e568a4ea11fc48d28ec0a4a686d1
lewisdarkone/pythonPracticas
/diccionario.py
791
3.734375
4
persona1 = {'id':1,"Nombre":"Pablo","Apellido":"Mendez","Edad":40,"Profesión":"Pintor","Vivo":False} persona2 = {'id':2,"Nombre":"Juan","Apellido":"Diez","Edad":50,"Profesión":"mecanico","Vivo":True} persona3 = {'id':3,"Nombre":"Mario","Apellido":"Montero","Edad":60,"Profesión":"albagnir","Vivo":True} persona4= {'id':4...
983cf82dd61ab7fb13286df0eec2fc760f1a6954
lewisdarkone/pythonPracticas
/list.py
373
3.515625
4
productList = ['carne','arroz','habichuela','maiz','pan','queso','jamon'] vegetales = ['silantro','brocoli','ajo'] frutas = ['guineo maduro','mango','zapote','fresas'] frutas.pop() print(frutas) verdes = vegetales+frutas print(verdes) print(vegetales) productList.append('Sopita') print("brocoli" in vegetales) produc...
85c2d3c2bea860f8fa4164575eef75a7e92206f0
lucasmvnascimento/trybe-exercises
/exercises/Computer_Science/aprendendo-python/exercicio6.py
320
3.9375
4
def tipo_triangulo(l1, l2, l3) : isTriangle = (l1 + l2 > l3) and (l1 + l3 > l2) and (l2 + l3 > l1) if not isTriangle : print('Nao eh Triangulo') elif l1 == l2 == l3 : print('Triangulo Equilatero') elif l1 == l2 or l2 == l3 or l1 == l3 : print('Triangulo Isosceles') else : print('Triangulo Escaleno')
df1f43b0c13c45bf5e294f2a86e095238215abfa
lucasmvnascimento/trybe-exercises
/exercises/Computer_Science/json-csv-entrada-e-saida-de-dados/exercicio3.py
537
3.859375
4
import random with open('game_words.txt', mode='r') as game_words_file: words_list = game_words_file.read().split() random_word = random.choice(words_list).upper() scrambled_word = "".join(random.sample(random_word, len(random_word))) attempts = 0 while attempts < 3 : print(f"{attempts + 1} TENTATIVA") ...
bb66dc6c8fca6bf8c5a775b48307a3a1b7ebec36
2580ayush2580/AI
/Part 1 - Artificial Neural Networks/ann.py
3,875
3.5
4
# -*- coding: utf-8 -*- # Artificial Neural Network # Importing the libraries import numpy as np import pandas as pd import tensorflow as tf tf.__version__ # Part 1 - Data Preprocessing # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].valu...
9011c19a3b5be1c7fb176d52fecefa19efc01084
lcbc-epfl/data_management
/script/create_metadata.py
8,268
3.53125
4
#!/usr/bin/env python3 """Generate a README file for metadata based on some input information.""" import os import datetime # ADD POSSIBLE README FILE TYPES HERE allowed_types = ['main', 'calculation'] # ADD POSSIBLE SUBJECTS HERE allowed_subjects = ['perovskites', 'biochemistry', 'photochemistry', 'methods'] class...
dfdd6b66836e740ea41ee0e944cdfb076be49694
dongyj1/projects-in-EC602
/w1b_factdiff.py
834
4.09375
4
# white a python program that : # reads two integers X and Y using input() # calculates Z = X! - Y! from math import factorial X = int(input("Please input integer X:")) while(X<0): X = int(input("X should be non-negative integer, please input again:")) Y = int(input("Please input integer Y:")) while(Y<0)...
eae668cd8a0ce92e2d60b7c13fc88b46b6dbdc45
raghureddyram/pyp-w1-gw-extensible-calculator
/calculator/operations.py
889
3.796875
4
def add(*args): if len(args) is 1: return args[0] else: return sum(args) def subtract(*args): first_num = args[0] if len(args) is 1: return first_num else: subtraction_list = list(args[1::]) return first_num - sum(subtraction_list) def multiply(*arg...
d8493cd438c8dc88158331c58d0711be20960e8f
rohansjoshi/Algorithms
/QuickSelect.py
2,390
3.953125
4
# Use the QuickSelect Algorithm to find the k-th largest element of an array import random def swap(arr, i, j): arr[i], arr[j] = arr[j], arr[i] def kthlargest(arr, k): n = len(arr) def partition(start, end, ind): """ Rearranges arr[start:end] so that everything to the left of arr[pivot] is...
1bcc302b888757db7abbad85bb12cfcb0cb4e59c
zbigniewzolnierowicz/school-notes
/Klasa 4/informatyka/20200310/quicksort.py
602
4.15625
4
def quickSort(numbers): if len(numbers) == 0: return [] elif len(numbers) == 1: return numbers else: pivot = numbers[len(numbers) - 1] left = [] right = [] for number in numbers: if number < pivot: left.append(number) el...
4ed6621c96c4759fd20bc7ead3673ef566afd21b
zbigniewzolnierowicz/school-notes
/Klasa 4/informatyka/20191022/main.py
150
3.515625
4
def squareRoot(a, exactness = 0): p = a while(abs(a-(p/a)) > exactness): a = (a + (p/a))/2 return a print(squareRoot(125, 0.001))
adacd6d03fbd4efeafc06d8789d79126d45965a0
zbigniewzolnierowicz/school-notes
/Klasa 4/informatyka/20191022/calki.py
401
3.59375
4
def function(x): return x**2 - x - 3 sumOfFields = 0 i = 1 p = int(input('Początek funkcji: ')) q = int(input('Koniec funkcji: ')) n = 0 temp = input('Dokładność funkcji: ') if temp == '': n = 1 else: n = int(temp) dl = (q - p) / n while (i < n): sumOfFields += abs(function(p+i*dl)) i += 1 totalFie...
5c2cd0a7c7242280fa00da5f645049e391a92c67
thegeniesghost/Python-scripts
/printapp.py
267
3.75
4
from sys import exit import random a = input("How many?\n> ") s = input("Enter range start: ") e = input("Enter range end: ") def printer(s, e): print random.choice(range(s, e)) def printerx(a): for i in range(a): printer(s, e) printerx(a)
ace0c6154839a52aceee1e9c959cf2f3ab1f94b4
thecskc/PythonTut
/tuts/regularexpressions.py
597
4.0625
4
# regular expressions are for matching patterns in text # they are also called regexes. import re def main(): fh = open("raven.txt"); for line in fh: if re.search('(Len|Neverm)ore',line): print(line); print("Now Replacing"); print(re.sub('(Len|Neverm)ore','###',line)) print("After Replacement") fh.s...
ea8d6b597a7142605855b32c62b1b3ede1ab25a6
thecskc/PythonTut
/tuts/typeandidentity.py
655
3.734375
4
# everything in Python is an object # including ints and floats # 42 for example has its own id within python # x = 42 will make x hold the same id as 42 #id(x) -> will provide x's id and type(x) -> will provide the class of x # equality -> x==y # to check if two things are the same (same id's that is) you do "x is y" ...
4e5a3bc2d2e3dd5a50bd3afa697499c2f1db1f90
alemanyr/assignment3
/ziptonamefile.py
244
3.640625
4
import zipfile def zipToNameFile(zip): with zipfile.ZipFile(zip, "r") as zipped: with open("output/output_filenames.txt", "w", encoding='utf-8') as NameFile: for fileName in zipped.namelist(): NameFile.write("{}\n".format(fileName))
932b3552495d511a3f8e6e99fe7f2e583a51c4fe
FDWraith/adventOfCode
/2018/day13/sol1.py
7,750
3.578125
4
class TileEntity(object): def __init__(self, X, Y): self.X = X self.Y = Y self.l = EmptyTile(X, Y) self.r = EmptyTile(X, Y) self.d = EmptyTile(X, Y) self.u = EmptyTile(X, Y) def __str__(self): return str((self.X, self.Y)) def left(self): ret...
c12367f8528594106deba70b66d21bf009694b93
MariaMedvede/coursera
/week 1/clock2.py
861
3.984375
4
# Электронные часы показывают время в формате h:mm:ss, то есть сначала записывается количество часов (число от 0 до 23), # потом обязательно двузначное количество минут, затем обязательно двузначное количество секунд. # Количество минут и секунд при необходимости дополняются до двузначного числа нулями. # # С начала су...
051b9711719d48ca2e3382321b2e7c18cab4e952
MariaMedvede/coursera
/week 2/caws.py
157
3.625
4
n = int(input()) if 11 < n < 14 or n % 10 in (0, 5, 6, 7, 8, 9): print(n, "korov") elif n % 10 == 1: print(n, "korova") else: print(n, "korovy")
18f434e8623339cb42aa18b68146f066db2354c7
MariaMedvede/coursera
/week5/Stairs.py
83
3.71875
4
N = int(input()) B = "" for i in range(1, N + 1, 1): B += str(i) print(B)
05ea169f9a59ae7f09244d88eece63356ab0abc9
MariaMedvede/coursera
/week 1/sum3.py
204
3.609375
4
#Дано трехзначное число. Найдите сумму его цифр. N = int(input()) first = N % 10 tens = N // 10 % 10 hundreds = N // 100 summ = first + tens + hundreds print(summ)
3fbf00d43f85df3cd40b4d7e5460b2c454b24734
MariaMedvede/coursera
/week 1/next.py
725
4.34375
4
# Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере # (важно в точности соблюдать вывод программы: обратите внимание на пробелы и на точки). # Нельзя пользоваться конкатенацией строк, используйте print с несколькими параметрами. A = int(input()) prev = A - 1 nexty = ...
0890f8115facad0690bb7489e5b3bddc117c4da7
MariaMedvede/coursera
/week4/FastExponentiation.py
258
4
4
def power(a, n): if a == 0: return 0 elif n == 0: return 1 elif n % 2 == 0: return power(a, n/2) ** 2 else: return a * power(a, n-1) a1 = float(input()) n1 = int(input()) print(power(a1, n1))
19db038d6e96f1d3617e1f8a3b16b6c268489e26
MariaMedvede/coursera
/week3/TheSystemOfLinearEquations-1.py
242
3.5625
4
a = float(input()) b = float(input()) c = float(input()) d = float(input()) e = float(input()) f = float(input()) delta = a * d - b * c delta1 = e * d - f * b delta2 = a * f - c * e print(float(delta1/delta), float(delta2/delta))
c88b2c0f4104aaab29ba66aac26fdbdf2d77e9ae
sulaxd/python_tutorial
/_answer/104.py
191
4.125
4
import math PI = math.pi radius = eval(input("Enter radius = ")) print("Radius = %.2f" % radius) print("Perimeter = %.2f" % (2*radius*PI)) print("Area = %.2f" % (pow(radius,2)*PI))
7a683c51181673a8fec7233aad8b5f544724f0cd
sulaxd/python_tutorial
/_answer/604_new.py
258
3.734375
4
print("Enter 10 integers:") tmp = {} for i in range(10): num = input() if(num in tmp): tmp[num]+=1 else: tmp[num]=1 mode = max(tmp, key=tmp.get) print("Mode of the set: ", mode) print("Number of occurrence: ", tmp[mode])
7bc75f1e6b841c5a1cfe851f0c0f9ab32b315c26
mowoka/small_project_python
/password_generator.py
312
3.640625
4
import random, string password_lenght = int(input("How long would does your password to be ?? ")) password_caracthers = string.ascii_letters + string.digits + string.punctuation password = [] for x in range(password_lenght): password.append(random.choice(password_caracthers)) print(''.join(password))
730f0629e1d8e25b92cecb988fc6a87a1ded8595
xscorp/urlencoder
/urlencoder.py
3,124
4.09375
4
#!/usr/bin/env python3 import argparse import codecs #result_url is a global variable for storing the url string after encoding/decoding result_url = "" #description of the tool encoder_description = "A tool for converting string into Hex URL format and vice versa" #code for parsing command line arguments parser = ...
03852842cb4ab3d970d5dc4266db3ec415ad31c8
yeos60490/algorithm
/leetcode/medium/add_two_numbers.py
841
3.78125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: #print(l1) sum_value = l1.val + l2.val carry = int(sum_val...
609aeca41a3d21e4e334a50d7f7dfd5281e325c4
yeos60490/algorithm
/programmers/프린터.py
974
3.5
4
from collections import OrderedDict def solution(priorities, location): answer = 0 queue = OrderedDict(zip(range(len(priorities)), priorities)) ##location : priorities while queue: i, pri = list(queue.items())[0] if pri >= max(queue.values()): queue.popitem(last=False)...
df467b926b59ab1e527a9df58cc50966fd6b1213
yeos60490/algorithm
/leetcode/medium/validate-binary-search-tree.py
638
3.890625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode, lessThan=float('inf'), greaterThan=float('-inf')) -> bool: if...
9c6190da78aa2c2f1a0014842e2aaa78390c8e0b
AnkittPareek/Turtle_Crossing
/car_manager.py
894
3.828125
4
from turtle import Turtle from random import * COLORS = ["red", "orange", "yellow", "green", "blue", "purple"] STARTING_MOVE_DISTANCE = 5 MOVE_INCREMENT = 10 Y_COR = [] for i in range(-230, 250, 40): Y_COR.append(i) print(Y_COR) class CarManager: def __init__(self): self.cars = [] self.speed ...
e3bb5770c19d64272a6764995214f70d92fce712
stashinskii/task-manager
/TMan/task_manager_library/controllers/task_controller.py
5,325
3.546875
4
""" This module represents controller of tasks which is managing actions of them and give full access to user and his CLI for adding, editing, deleting, sharing, viewing, etc. """ from task_manager_library.storage.task_storage import Storage from task_manager_library.models.task_model import Status, Priority, Tag from...
72eda47b76120428c5f9b781d9fa2894ffdfcb85
marcustut/UnlockProject
/Games/NumSequence/main.py
911
3.6875
4
import random class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' playerInput = input("Please enter 3 number: ") ans = [] for i in range(3): ans.append(str(ran...
d61d5f4fea5dad936266e365700326f2b8f3bb94
azmiu-bootcamp/third-seminar-Nihad1999
/Problem7.py
538
3.703125
4
import random n = int(input("Maksimal təxmin etmə şansını daxil edin:->")) number = random.randint(1, 99) s = n while n >= s > 0: texmin = int(input("Eded daxil edin")) s = s - 1 if texmin == number: print("Tebrikler dogru texmin elediniz") break elif texmin < number and s > 0 : ...
2ab2e851b1d18be5634647b449d80786f4e0f976
yl0115/python_study
/day06/01-魔法方法__str__.py
553
3.875
4
# coding=gbk # __str__:ʹprintӡʱ򣬻Զö__str__ class Person(object): def __init__(self, name, age): self.name = name self.age = age # ضϢ def __str__(self): # һַϢ return "ҽУ%s,䣺%d" % (self.name, self.age) # һ # initʹλòʽ # person = Person('', 14) # print(person.name, person.age)...
b1241c799fae942e29a1d241720528f58b7c4765
yl0115/python_study
/day7/09-StringIO.py
420
3.546875
4
# 把字符串写入内存 import io # StringIO的操作和文件写入和读取的操作很类是 str_io = io.StringIO() # 向内存写入字符串数据 str_io.write('hello') str_io.write('world') # # 获取数据 # content = str_io.getvalue() # print(content) # 另一种获取数据方法 # 设置文件指针的位置到文件开头 str_io.seek(0) result = str_io.read(2) # 读取指定长度 print(result)
7a38ce3c95ca5f073a0aedcc38df3bed6126240d
yl0115/python_study
/day7/11-序列化.py
771
3.671875
4
# 序列化:把内存中的数据保存到本地,可以做到持久化存储 import pickle # 比较通用,可以序列化任意对象类型 # 序列化 # my_list = [{"name": "张胜男", "age": 16}, {"name": "王鹏", "age": 19}] # file = open('my_list.serialize', 'wb') # pickle.dump(my_list, file) # file.close() # 反序列化 # file = open('my_list.serialize', 'rb') # result = pickle.load(file) # print(result) # f...
049d45edd355ea197f3d01bf7f0cda785ba8e99b
yl0115/python_study
/day4/01-列表推导式.py
865
4.21875
4
# 列表生成式(列表推导式):通俗理解使用for循环快速创建一个列表,最终要获取一个列表 my_list = [] for i in range(1, 6): print(i) my_list.append(i) print(my_list) m = [i for i in range(1,8)] print("你是一个打住", m) # 列表推导式,目的快读创建一个列表 # 列表推导式的语法格式 my_list1 = [value for value in range(1, 7)] my_list2 = [i for i in range(1, 9)] print(my_list2) print(my_list...
7c6dd22ffb5f623cbd7fff1b76548b99936f874d
yl0115/python_study
/day4/04-global的使用-扩展.py
656
4.1875
4
# 定义一个不可变全局变量 g_num = 10 print("函数外",g_num, id(g_num)) def modify(): # 声明要修改全局变量 global g_num g_num = 1 print("函数内", g_num) print("函数内", id(g_num)) modify() print(g_num) # 定义一个可变类型的全局变量 g_list = [2,5] print("函数外", id(g_list), type(g_list)) def modify1(): # 在原有的数据上添加一条数据 # 如果只是修改数据,那么这...
8eb2af76c79a98f6e339f6cbba06ccd115bce750
yl0115/python_study
/day03/07-函数的不定长参数.py
1,204
3.96875
4
# 函数的不定长参数:1、不定长位置参数2、不定长关键字参数 # 不定长参数:调用函数的时候不确定传入多少个参数,可能是0个或者多个 # 定义函数的时候:1、不定长位置参数2、不定长关键字参数 # -----------------------不定长位置参数----------------- # 定义一个不定长位置参数 def show(*args): pass def sum_num(*args): # 提示:args:会吧调用函数传入的位置参数封装到一个元祖里面,如果没有传入就是一个空元祖 print(args, type(args)) result = 0 for i in arg...
5eae8edb991bca37ff21232b8b738d5627fd536e
tatwik-sai/Path-Finder
/search.py
22,491
3.625
4
import math import operator import random import time from tree import Tree class Search: """ A Class with many Artificial Intelligence Search Methods(eg:- bfs, dfs, a*, heuristics e.t.c). """ def __init__(self, goal_test, next_states, state=None, heuristic=None): """ ...
9ca9fd5aa50937ac435194ebfa0a242035b5816f
NeverGiveUppp/Python
/Задание 6.4.py
3,604
3.78125
4
'''4. Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, name, is_police (булево). А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, повернула (куда). Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. ...
ad9c8ff91d68c1b3e986b4c799574d6824c2f461
NeverGiveUppp/Python
/Задание 5-3.py
1,084
3.890625
4
'''3. Создать текстовый файл (не программно), построчно записать фамилии сотрудниковr и величину их окладов. Определить, кто из сотрудников имеет оклад менее 20 тыс., вывести фамилии этих сотрудников. Выполнить подсчет средней величины дохода сотрудников.''' with open("text_3.txt", "r", encoding="utf-8") as my_fail: ...
e7a721132211ff4f2eb2ba36330bcfc6fa2eefba
NeverGiveUppp/Python
/Урок 1. Знакомство с Python/Задание 6 Результаты спортсмена.py
1,188
4.34375
4
# 6. Спортсмен занимается ежедневными пробежками. # В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который общий результат спортсмена составить не менее b километров. # Программа должна принимать знач...
e8d2f1d1e4705e96719be5ed4712ba3ea9095157
xozai/Assignment2
/nimm.py
717
4.1875
4
""" File: nimm.py ------------------------- Add your comments here. """ import random def main(): stones = 20 player = 1 while stones > 0: print("There are "+str(stones)+" stones left") turn = input("Player "+str(player)+" would you like to remove 1 or 2 stones? ") while (turn != '2...
e9aa1d3cca5bef6ae843b2dadcae1f8fa2969cd4
khanchi97/Smvdu-Algos
/Greedy-algos/huffmanCoding/huffmanCoding.py
2,909
3.78125
4
import random dic = {} class MinHeapNode: def setNode(self, left, right, freq, char): self.left = left self.right = right self.freq = freq self.char = char return self def huffmanCoding(arr, freq): heapArr = [] for i in range(len(arr)): heapArr.append(MinHea...
3ac265ca4e34007f7f5a2552202d75a56950cb71
khanchi97/Smvdu-Algos
/search-algos/binary_search/b_search.py
839
3.9375
4
#******************* Binary Search ******************************* def binary_search(l,beg,end,val): mid = int((beg + end)/2) if beg > end: return -1 if l[mid] == val: return mid elif l[mid] > val: return binary_search(l,be...
1730602b9fde65f1fbd46391101766373c86ec9c
Prabhanda-Akiri/Data-Structures-Implementation
/ordered-Dict-Bst.py
4,027
3.859375
4
class TreeNode: def __init__(self): self.parent=None self.left=None self.right=None self.value=0 self.s='a' class Node: def __init__(self): self.next=None class OrderedDict: def __init__(self): self.root=Node() def insert(self,x,s): ...
62a9730e07c7216a16f369a3011e8f0c4aab3b9f
Prabhanda-Akiri/Data-Structures-Implementation
/Avl-Tree-Time.py
8,450
3.625
4
import time class AvlNode: def __init__(self): self.parent=None self.left=None self.right=None self.s=0 self.value=0 self.height=0 class Node: def __init__(self): self.next=None class AvlTree: def __init__(self): self.root=None def insert(self,k,s): t=AvlNode() t.value=k t.s=s t.he...
b13d5a523f2615c588474535136f4cce1ce29118
bstekas/AdventOfCode
/2020/Day3.py
1,487
4
4
# https://adventofcode.com/2020/day/3 DAY = 3 x_test = ''' ..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.#'''.split('\n') x_test.remove('') y_test = 7 y_test2 = 336 def run_slope(r, d, slope): width = len(slope[0]) trees = ...
5cbb44de957999f3a96dbf4df3088deb6202065a
gabrieldrakar/organizacao_de_clientes
/organizador.py
1,166
3.6875
4
import os if os.path.isdir ('arquivos') == False: os.mkdir('arquivos') os.chdir('arquivos') cwd = os.getcwd() print (cwd) arquivo1 =input('nome do arquivo: ') +'.txt' if os.path.exists(arquivo1) == False: arquivo= open(arquivo1, 'w+') elif os.path.exists(arquivo1) == True: arquivo=open ( arquivo...
3c75027f1e60030e956b4bce3e990ba0d7e71072
rytwalker/sl-graphs
/projects/graph/src/graph.py
4,520
4
4
""" Simple graph implementation """ from collections import deque class Graph: """Represent a graph as a dictionary of vertices mapping labels to edges.""" def __init__(self): self.vertices = {} def add_vertex(self, vertex): if vertex not in self.vertices: self.vertices[verte...
a7d8a08dcf25186879a4bb045a3ede7ed0985fc5
Shane-Kao/leetcode
/Algorithms/5. Longest Palindromic Substring/solution.py
545
3.6875
4
# -*- coding: utf-8 -*- __author__ = 'Shane_Kao' class Solution: def longestPalindrome(self, s: str) -> str: N = len(s) g = (s[i: i + len_] for len_ in range(N, 0, -1) for i in range(N - len_ + 1)) while True: curr_ = next(g) if curr_ == curr_[::-1]: ...
b8d1823732d877e5d13ebbf5cab465cca7300645
bvhest/IoT-01_Playground
/esp32_wroom/randomLED/randomLed.py
817
3.5
4
from machine import Pin import time import random # (blue) LED on board: led = Pin(2, Pin.OUT) # Green LED 1 on GPIO16, pin 25. # Green LED 2 on GPIO17, pin 27. # Yellow LED 1 on GPIO18, pin 35. # Red LED 1 on GPIO19, pin 38. led1 = Pin(16, Pin.OUT) led2 = Pin(17, Pin.OUT) led3 = Pin(18, Pin.OUT) led4 = Pin(19, ...
8e05421c3535ab05098fd4dd8815971638d4d462
jmfcool/py
/sandbox/dictionaries.py
303
3.546875
4
array = { "item": "alpha", "id": 1234, "notes": None } print(array["id"]) # Print keys print(array.keys()) # Print values print(array.values()) # Change value of item array["item"] = "bravo" print(array.values()) # Delete item del array["item"] print(array.values())
ad121dad5e5fe4c6e1d530d3eddc596d43a88f97
konflic/sqlite_database
/1_insert_data.py
1,200
3.546875
4
import sqlite3 import datetime from create_database import example_db, simple_db """ Python -> SQLite ---------------- None -> NULL int -> INTEGER float -> REAL str -> TEXT bytes -> BLOB """ EXAMPLE = "example.db" SIMPLE = "simple.sqlite" example_con = example_db() simple_db() def insert_row(db, sql, para...
bd13fe090b796d2ffa6ef1947d5cafd538f14617
adrianna/DSandA
/PyLibrary/GraphAlgorithms/connecting_islands.py
5,717
4.5
4
#!/usr/bin/env python # coding: utf-8 # ### Problem Statements # # In an ocean, there are `n` islands some of which are connected via bridges. Travelling # over a bridge has some cost attaced with it. Find bridges in such a way that all # islands are connected with minimum cost of travelling. # # You can assume tha...
ca317e05c8c26196a7ae68de7d16c56bcf8b1c3a
adrianna/DSandA
/PyLibrary/Heaps/heapArray.py
24,365
4.09375
4
#!/usr/bin/env python class Heap: def __init__(self, initial_size=10): self.cbt = [None for _ in range(initial_size)] # initialize arrays self.next_index = 0 # denotes next index where new element should go def insert(self, data): # insert element at the next index self.cbt[s...
dca8a1f96ee8bedd5795fda13aac6bce83453c15
adrianna/DSandA
/Project/P2/search_rotated_array.py
2,741
3.734375
4
################################### ## search_rotated_array.py ## ################################### import pdb debug = 0 def rotated_array_search(input_list, number, start_index, end_index): start_index = 0 end_index = len(input_list) - 1 while start_index <= end_index: mid_index = (start...
2e7d3b535963ffdf114a92a8f26bba7176ba5675
adrianna/DSandA
/Practice/Detecting Loops.py
2,614
4.125
4
#!/usr/bin/env python # coding: utf-8 # # Detecting Loops in Linked Lists # # In this notebook, you'll implement a function that detects if a loop exists in a linked list. The way we'll do this is by having two pointers, called "runners", moving through the list at different rates. Typically we have a "slow" runner w...
ed286a1b8118aed93da325dbb7be4367c91dd247
StephennFernandes/Rest-API-
/create_tables.py
438
3.828125
4
import sqlite3 connection = sqlite3.connect('data.db') cursor = connection.cursor() create_table_query = "CREATE TABLE IF NOT EXISTS items (name text, price real)" create_table_query2 = "CREATE TABLE IF NOT EXISTS users (id INTEGER, username text, password text)" cursor.execute(create_table_query) cursor.execute(creat...
86cfa38299714d06cae62b8c4c807fe36a433c84
moonpunk1234/Day03
/find_your_animal.py
679
3.734375
4
x=("Animal shelter program \n ==========================") print(x.upper()) print(x.center(30)) animal =[] x= int(input('How many would you like to keep :\t')) print('\n') for i in range(x): y= input ("Please Enter your animal :") print('\n') animal.append(y) print("Total number of animals...
d28aacfd7d2f6f926578cdba9aa82610b35177a1
bluehat/beginner_tutorials
/rpg.py
6,077
4.6875
5
# code with a # in front of it is a comment. It is my way of writing to you. The computer will ignore it. # it is always important to put comments in your code so you can remember what you were doing when you come back several years later and need to fix something # it also makes you way easier to work with # this is ...
4d2d927647c88c1f4fedaa7710d251d7f5297930
jumaga/katas
/python/StringCalculator/stringcalculator.py
801
3.796875
4
import re class stringCalculator: default_delimiter_pattern = re.compile('\n|,') custom_delimiter = re.compile('\/\/.+\n') several_delimiters = re.compile('\/\/\[[^\[\]]\]+\n') def __init__(self,numbers): self.numbers = numbers def add(self): number_list = [] sum = 0 if self.numbers == None ...
acc31ac7d6eae04dcaed7e0f8c3f9f9b67f5740a
acheng1230/NBA_Player_Types
/lib/cluster.py
3,480
3.5
4
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn import cluster, metrics, datasets from sklearn.preprocessing import StandardScaler np.set_printoptions(precision=4) def kmeans(reduced_data...