blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
651416b2a4ea2345de5a02e3c2e5b31cfbf454ba
0xRamadan/IEEE-Rookies-30-Day-Program
/IEEE_Rookies_30_Days_program/IEEE_Rookies_task_06_part_02.py
552
4.25
4
# IEEE_Rookies_task_06_part_01 # name: Mahmoud_Ramadan # task: find a string def count_substring(string, sub_string): c = 0 str_len = len(string) sub_len = len(sub_string) for i in range(str_len - sub_len + 1): if (string[i:(i + len(sub_string))] == sub_string): c = c + 1 return...
d61e6c78e8457ff4fc6fb4bd5e78533f386f4a90
chosaihim/jungle_codingTest_study
/FEB/15th/예은_짝지어제거하기.py
398
3.6875
4
def solution(s): answer = 0 stack = [] for one in s: if len(stack) == 0: stack.append(one) elif stack[-1] == one: stack.pop() else: stack.append(one) answer = 1 if len(stack) == 0 else 0 return answer s = "baabaa" # s = "cdcd" # s = "aaaaa...
f69992682b0f93461b8f956fb43e61fec2321b4f
umunusb1/PythonMaterial
/python3/13_OOP/34_singleton_design_pattern.py
661
4
4
#!/usr/bin/python """ Purpose: To create a class with singleton design pattern It means, If an instance of that class is already created, Instead of creating new instance, make use of already created instance """ from pprint import pprint # Question: __new__ vs __init__ # baby born => __new__ # baby named =...
5697d14d00d23be9f1a649d62501d06af5613db1
Tifinity/LeetCodeOJ
/105.从前序与中序遍历序列构造二叉树.py
551
3.65625
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def buildTree(self, preorder, inorder): if not preorder: return None root = TreeNode(preorder[0]) #print(root.val) i = inorder...
d6c91d78b45e4bf40b25f94cf9dcbeca41238feb
viniciusjulianirossi/Python
/Comprehension e Funções Integradas/Any_and_all.py
1,117
4.15625
4
""" Any e All all() retorna True se todos os elementos do iteravel são verdadeiros ou ainda se o iteravel está vazio """ # Exemplo all() print(all([0,1,2,3,4,3])) # Todos os numeros são verdadeiro: False print(all([1,2,3,4,3])) # Todos os numeros são verdadeiro: True print(all([])) #Todos os numeros são verdadeiro: T...
22289714ea2fbe425879687cb94416a2cd1ce004
idealgupta/pythgon-practis
/ifelif3.py
477
3.84375
4
#discount bill_amount=int(input("enter the amount : ")) if bill_amount>=5000: bill_amount=bill_amount - 500 elif bill_amount>=4000 and bill_amount<=4999: bill_amount=bill_amount - 400 elif bill_amount>=3000 and bill_amount<=3999: bill_amount=bill_amount - 300 elif bill_amount>=2000 and bill_amount<...
e5498a3759f01f423d61279f1839106f15496a73
tylerbrowndev/aoc2020
/3.py
593
3.625
4
f = open("input/3.txt", "r") lines = f.readlines() forest = [] for line in lines: forest.append([c for c in line.strip()]) x_len = len(forest[0]) y_len = len(forest) # part 1 trees = 0 x = 0 y = 0 while y < y_len - 1: x = (x + 3) % x_len y += 1 if forest[y][x] == '#': trees += 1 print(trees) # part 2 ...
2ab55c24620fa4ed54555e827693530452ba9a1a
Day-bcc/estudos-python
/02-recursos_avancados/manipulando-arquivos/armazenameto-with.py
247
3.59375
4
#Armazenando dados de arquivos dentro de variáveis #readlines() -> armazena cada linha do arquivo em uma lista arquivo = 'numeros.txt' with open(arquivo) as numeros: linhas = numeros.readlines() for linha in linhas: print(linha.rstrip())
8c9a96fa6bb2b8826252ddbfb54db35472108a38
DimitarPetrov77/py-course
/conditional_statements/Greater number.py
191
4.125
4
num1 = int(input('Enter first number:')) num2 = int(input('Enter second number: ')) if num1 > num2: print('Greater number: ' + str(num1)) else: print('Greater number: ' + str(num2))
897514f549187bdb15cfe050ed60c70c30256c0c
Yuvv/LeetCode
/0501-0600/0535-encode-and-decode-tinyurl.py
839
3.703125
4
import binascii import hashlib class Codec: """ https://leetcode.com/problems/encode-and-decode-tinyurl/ 编码/解码 url """ def __init__(self): self.urls = {} self.salt = 'Ax97' def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str ...
68102f5a87ce1fb7256b8b8a45df5d1746ed3da8
Tiyasa41998/py_program
/list.py
157
4.1875
4
MyList=[1,2,3,4,2,5,3,7] print(MyList) NewList=[] for i in (MyList): if i not in NewList: NewList.append(i) print(NewList)
12e8f9bfb5aa3fc8e0bf6fd0a6cb2537e20c60f6
Bwade95/Enrollment-Problem
/person.py
817
4.03125
4
from address import Address class Person: def __init__(self, firstName, lastName, dob, phoneNum, address): self.first_name = firstName self.last_name = lastName self.date_of_birth = dob self.phoneNum = phoneNum self.addresses = [] if isinstance(address, Address): ...
f73be97bfeeed6f010d097d6c84b8524eda68914
AndrianDenys/Labs
/dz_1.py
3,770
3.953125
4
#1 class Classroom(Object): def __init__(self, number, capacity, equipment): self.number = number self.capacity = capacity self.equipment = equipment def is_larger(self, classroom): if self.capacity is > classroom.capacity: return True else: ...
fc86ae90a3d59d060755fb1e307be7e754c7f681
kathedore/request_sender
/DBconnection.py
1,626
3.65625
4
import psycopg2 from psycopg2 import pool query = "INSERT INTO main_table (request, response, request_type) VALUES(%s,%s,%s)" def database(record_to_insert): try: postgreSQL_pool = psycopg2.pool.SimpleConnectionPool(1, 20, user="postgres", password="annawi...
59df48ba31c73faddca53658b2468f678718182a
hellion86/pythontutor-lessons
/1. Ввод и вывод данных/Следующее и предыдущее.py
411
4.21875
4
''' Условие Напишите программу, которая считывает целое число и выводит текст, аналогичный приведенному в примере (пробелы важны!). ''' num = int(input()) print('The next number for the number '+ str(num) + ' is '+ str(num +1)) print('The previous number for the number '+ str(num) + ' is '+ str(num -1))
417bb0e9983ba8a6a95ff4ff2f6212f3251ae508
kjovan27/RealLife_problem_OOP
/oop.py
1,554
3.96875
4
# -*- coding: utf-8 -*- """ Created on Tue Jul 4 13:27:57 2017 @author: Don Quan """ class Computer(object): #"""A real world problem modelled using OOP""" #initialising a class variable pcCount = 0 #initialization def __init__(self, RAM, processor_speed, hardDisk): self.R...
297cd71028f8f743121eb080c4b56e6591b03a83
Theoblanc/algorithm
/Sort/selectionsort.py
853
3.65625
4
# # 선택정렬 # 최소 값을 선택헤서 정렬 하는 방법 # # 시간복잡도 n^2 for 2번 list = [10, 5, 6, 8, 2, 1] # def sel_sort(a): # n = len(a) # for i in range(0, n - 1): # min_idx = i # for j in range(i+1, n): # if a[j] < a[min_idx]: # min_idx = j # temp = a[i] # a[i] = a[min_idx...
a6e8c6dac15297d5eb16ccbacba1b206147874c8
TM1066/-Arcane-Aristocracy-
/Spells.py
1,889
3.59375
4
#Internal Files from Utils import * from Characters import * #Class for the Spells in the game class Spell: def __init__(self,name,element,manacost,damage,level): self.name = name self.element = element self.manacost = manacost self.damage = damage #self.effect = effect - Doing this later, just g...
f84852e02446f49a260b6ce07033c309d16b9d9b
ivan-yosifov88/python_basics
/Exams -Training/01. Oscars ceremony.py
259
3.5
4
rent_of_hall = int(input()) statuettes_price = rent_of_hall * 0.7 catering_price = statuettes_price * 0.85 sound_system_price = catering_price / 2 total_money = rent_of_hall + statuettes_price + catering_price + sound_system_price print(f"{total_money:.2f}")
d1cdbf7e05123d70329bb087c9ebef2aa5106d9d
HunterLaugh/codewars_kata_python
/kata_8_Sum_The_Strings.py
764
3.875
4
''' 8 kyu Sum The Strings Create a function that takes 2 numbers in form of a string as an input, and outputs the sum (also as a string): sumStr("4", "5") // should output "9" sumStr("34", "5") // should output "39" If either input is an empty string, consider it as zero. If both inputs are empty, ou...
c1d856bb48373492a8492b281659550821f2f98b
KushalVenkatesh/pycard
/pycard/holder.py
648
3.890625
4
class Holder(object): """ A credit card holder. """ def __init__(self, first, last, street, post_code): """ Attaches holder data for later use. """ self.first = first self.last = last self.street = street self.post_code = post_code def __repr_...
30b823f9d4d6787160fe4222ae5a9be873dfd568
felipeonf/Exercises_Python
/curso_py/ex049.py
351
4.03125
4
valores = [] while True: valor = int(input('Digite um valor: ')) if valor in valores: print('Valor duplicado, não vou adicionar!') else: valores.append(valor) opcao = input('Deseja continuar(s/n) ?').strip().lower()[0] if opcao == 'n': break print(f'Você digitou os ...
62c4ff63236635d461215c116e30d5338ba3c1ec
bknie1/Code-Challenges
/Valid Parentheses/valid_parentheses.py
1,155
4.25
4
""" Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. """ def is_valid(test): """ :type s: str :rtype: bool Replaces all valid...
7fc998d47d86661f4ad46be64a51a6eb39460166
UCD-pbio-rclub/Pithon_Michelle.T
/pithon_06272018/pithon_0627_ex2.py
893
4.15625
4
### 2. Write a function which takes a sentence as input and returns the reverse order of the words. ie "these are words" --> "words are these". Bonus: Capitalize the the first letter of the first word and end the returned string with the same punctuation as the input string. ie "these are words!" --> "Words are these!"...
516993d36ac1faa0a2fc052c45f7202714437bed
KillaTomato1001/MySchoolPrograms
/odd and even.py
259
4.15625
4
n=int(input('upto which number')) ctr=1 sum_even=sum_odd=0 while ctr<=n: if ctr%2==0: sum_even+=ctr else: sum_odd+=ctr ctr+=1 print('the sum of even integers is',sum_even) print('the sum of odd integers is',sum_odd)
bde1f1ca8f898633414b876fec80f04360bde62c
quantrocket-llc/zipline
/zipline/data/_minute_bar_internal.pyi
2,822
3.875
4
def int_min(a, b): ... def minute_value(market_opens, pos, minutes_per_day): """ Finds the value of the minute represented by `pos` in the given array of market opens. Parameters ---------- market_opens: numpy array of ints Market opens, in minute epoc...
373cfbca5a305cc3316cc2707b9551bb1a47bbed
Aragnos/tf_test
/Code/FileConnector.py
1,976
3.625
4
"""Opens, closes and writes to file""" import PyToSh # todo test all def open_files(file_list, path, use): """ Open all files given in file list and returns the opened file handlers :param file_list: files, which should be opened, as list :param path: path to the file location, as string :param use: 'a' for appe...
400c84deeb15c3afe47c0dc80ac050cf5565e524
brentshierk/Web1.1-homework-1
/app.py
1,549
4.3125
4
# TODO: Follow the assignment instructions to complete the required routes! # (And make sure to delete this TODO message when you're done!) from flask import Flask app = Flask(__name__) @app.route('/') def homepage(): """Shows a greeting to the user.""" return 'Are you there, world? It\'s me, Ducky!' @app.r...
47faddadc44808940e4412c55f3de46785d24ea2
chowell2000/SQL
/study_2.py
1,208
3.5
4
import pandas as pd import sqlite3 DB_FILEPATH = 'Chinook_Sqlite.sqlite' connection = sqlite3.connect(DB_FILEPATH) connection.row_factory = sqlite3.Row cursor = connection.cursor() average_query = """ SELECT CustomerId, AVG(Total) as av FROM Invoice GROUP BY CustomerID LIMIT 5 """ result2 = cursor.execute(a...
298d3c43f043a7b7066ad03551ca21c1727fdd03
NivMeir/Niv-Meir-MySuperList-2021
/DataBase.py
12,768
3.5
4
import sqlite3 import emails_and_encryption passcheck = emails_and_encryption.Extras() class Users: """ create a users table in the data base """ def __init__(self, tablename="users", userid = "userid", email="email", password="password", username="username"): self.__tablename = tablename ...
b7723ece54f9263dd336911b03ca8688a61dbaa2
ReinisZonne/Pong
/main.py
4,563
3.609375
4
''' Pong game Date: 10.07.20 ''' import pygame pygame.font.init() from random import randrange class Paddle: def __init__(self, x, y, color): self.x = x self.y = y self.color = color self.width = 20 self.height = 70 self.speed = 5 self.sco...
1844d5e7558dfe8d0cbea59ccbd0eb75951c7591
zhangzhonghua1999/webapp
/hua/myproject/廖雪峰python/函数式编程/sorted函数.py
424
3.90625
4
print(sorted([-1,3,-4,5,-20,8])) print(sorted([-1,3,-4,5,-20,8],key=abs)) print(sorted(['bob','alice','Zoo'],key=str.lower)) print(sorted(['bob','alice','Zoo'],key=str.lower,reverse=True)) L=[('Bob',75),('Adam',92),('Bart',66),('Lisa',88)] #按名字排序 def by_name(t): return t[0] L2 = sorted(L, key=by_name) print(L2...
4e4d00fe83c79c2a65715f8aec9b46cdd991454a
terasakisatoshi/HPC
/PythonMPI/MandelbrotSeq.py
616
3.546875
4
import numpy as np import matplotlib.pyplot as plt import time def mandelbrot(x,y,maxit): c=x+y*1j#complex exporession z=0+0j#complex expression it=0 while abs(z)<2 and it<maxit: z=z**2+c it+=1 return it #main x1,x2=-2.0,1.0 y1,y2=-1.0,1.0 w,h=150,100 maxit=1025 C=np.zeros([h,w...
c4fb409129cbd273628c516f6aa3ccf817c9d1c9
mrmyothet/ipnd
/ProgrammingBasicWithPython-KCL/Chapter-7/Fibonacci-sequence(recursion).py
108
3.625
4
def fib(n): if n < 2: return n else: return fib(n - 1) + fib (n - 2) print(fib(10))
60f44a6b8288cca98929b5d9c987f5b8f498ac08
artur-oganesyan/python_basics
/lesson_1/task_5.py
527
4.03125
4
proceeds = int(input('Enter proceeds: ')) costs = int(input('Enter costs: ')) if proceeds > costs: print('You have a profit') profit = proceeds - costs profitability = profit / proceeds * 100 print(f'Your profitability {profitability:.2f} %') firm_size = int(input("Enter firm size: ")) profit_fo...
96091f2df06ce67f94273d9ca9796b2e326e9b30
talesritz/Learning-Python---Guanabara-classes
/Exercises - Module II/EX047 - Contagem numeros pares.py
301
3.734375
4
#Crie um programa que mostre na tela todos os números pares que estão no intervalo entre 1 e 50. print('\033[34m-=-'*11) print('\033[31mEX047 - Contagem de Números Pares') print('\033[34m-=-\033[m'*11) print('\n') sum = 0 for count in range(1, 50, 1): if count%2==0: print(count)
85194c50f5d5bca08626654f1831768aef8aecc5
andreikina8/eponyms_extraction
/token1.py
864
3.5625
4
class Token(object): def __init__(self, string, position): self.string = string self.position = position self.length = len(string) #self.token_type = token_type self.right_position = self.position + self.length def __repr__(self): if hasattr(self, "token_t...
5e62669a9fcb390b7f276fbcc2608e49f4850c89
lesliehealray/python_class
/script2.py
187
3.703125
4
#numbers and variables print 5 num = 5 print type(num) print str(num) new = str(num) print type(num) print len(new) print len(new) print len(num) # what is this TypeError telling you?
39dfd63c41e3323c0baf3920eeb37839f805731c
TheCoder777/instagram
/python/flask-full-stack/model.py
885
3.875
4
# @thecoder777 || Python 'model.py' """ Database managment goes here """ import sqlite3 import sys db_path = "userdata.db" # check if there are any problems with the database def check_db(): try: conn = sqlite3.connect(db_path) cur = conn.cursor() cur.execute("CREATE TABLE if not exists ...
af4db1df62e23706567375d533c91dda755808f5
edk0/ads
/util.py
3,576
3.5625
4
import math from functools import reduce, partial from itertools import starmap from operator import attrgetter def distance(p1, p2, cutoff=float('inf')): """ The distance between p1 and p2. If cutoff is supplied and is smaller than the square of the distance, don't compute the square root and return Non...
affbbaff8e55fa575b5d0fff0294d9835c411e41
jethroglaudin/FraudDetectionMicroService
/fraud_detection_model.py
2,353
3.5625
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd def run_model(): # Importing the dataset dataset = pd.read_csv('transactions.csv') X = dataset.iloc[:, [1, 2, 4, 5, 7, 8]].values y = dataset.iloc[:, 9].values # Encoding categorical data from skl...
ff9410c82c3c465fe6ed4ffd7af80c2c84311d8e
Jung0Jin/Codingdojang
/2021년1월/20210104대각선길이구하기.py
170
3.71875
4
# https://codingdojang.com/scode/672?answer_mode=hide def diagonal(): x=float(input()) y=float(input()) result=(x**2+y**2)**0.5 print(result) diagonal()
43ad6010ba04f8344c59abe135a69c566a4c21bd
JJHH06/elgamal-python-simulation
/keyUtils.py
837
3.609375
4
#Laboratorio 10, librería de funciones de útilidad # Simulación de cifrado ElGamal # Jose Javier Hurtarte 19707 # Andrei Francisco Portales 19825 # Christian Pérez 19710 from random import randrange #k: cantidad de primos a generar def fermatRandomPrime( k,min, max ,iteraciones = 25): result = [] while(k >0):...
e8db6b23c55679003e6c86dd4a8190a5776e48bf
jessidepp17/hort503
/assignments/A04/ex35.py
2,892
4.03125
4
# Text game called "Save the Princess!" from sys import exit # gold room fxn def gold_room(): print("There's a chest and a locked door in the room.") choice = input("> ") if "open chest" in choice: print("There's a shitload of gold! How many pieces of gold do you take?") elif "ignore chest" in choi...
7280bb60daf596ef3c38718104ee7030e68f9e54
Markers/algorithm-problem-solving
/BRACKETS2/free-lunch_BRACKETS2.py
1,186
3.625
4
import sys class Brackets2: def __init__(self, str): self.str = str self.bracketMap = { '(' : 0, '{' : 1, '[' : 2, ')' : 10, '}' : 11, ']' : 12, } def isValidated(self): stack = list() for c in self...
6eedb219e0eb5e9a26fd77c63e80c235fd8fe705
seanhugh/Project_Euler_Problems
/problem_7.py
509
3.625
4
#!/usr/bin/env python #Problem 6 on Euler Project. Looking for the 10,001st prime number primes = [] i = 1 q=0 def check_prime(num): if num ==1: return 'false' if num ==2: return 'true' if num % 2 == 0: return 'false' for j in range(3, int((num+1)**.5)+1, 2): if (num % j == 0) and (nu...
ec9bf1367516bcbdb055175fbc296f81f92a7606
Aasthaengg/IBMdataset
/Python_codes/p03855/s733956797.py
1,609
3.828125
4
class UnionFind(): # 作りたい要素数nで初期化 def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rnk = [0]*(n+1) # ノードxのrootノードを見つける def Find_Root(self, x): if(self.root[x] < 0): return x else: self.root[x] = self.Find_Root(self.root[x]) ...
58ef90f5c6624977f9cfa3f1bc6a5364ca40138f
Devtlv-classroom/strings-basics-annasolemani
/list.py
1,066
3.96875
4
list= [825, 262, 627, 826, 285, 221, 730, 340, 750, 989, 272, 842, 383, 575, 810] print("There are {} numbers in the list.".format(len(list))) print("The lowest number on the list is {}.".format(min(list))) print("The highest number on the list is {}.".format(max(list))) print("The sum of the list is {}.".format(sum(l...
528ca22e4625d788b17b2d232970d96e37316c57
marijadom/Projekat
/pomocne/unos.py
370
3.71875
4
def validacija_unosa_string(poruka): unos = input(poruka) while unos == "": print("Ne moze se uneti prazan string!") unos = input(poruka) return unos def validacija_unosa_broj(poruka): unos = input(poruka) while unos == "": print("Ne moze se uneti prazan string!") ...
cd9b2621354b41dab2657e8f0bae14493858399f
MaksimKulya/PythonCourse
/L4_task3.py
414
3.796875
4
# Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. Необходимо решить задание в одну строку. # Подсказка: использовать функцию range() и генератор. import random as rnd a = [rnd.randint(20, 240) for i in range(100)] print(a) b = [n for n in a if n % 20 ==0 or n % 21 ==0] print(b)
b8d11e9ff40749f2de4f0f89bc8b28bd8c7935c4
jso/py-bikevis
/bikevis/analyses/basic.py
4,872
3.609375
4
import sqlite3 import matplotlib.pyplot as plt from util import put_add, put_list, put_val, traverse from cdf import cdf def demographics(con): data = {} cur = con.cursor() cur.execute("SELECT gender, birth_year, COUNT(trip_id) trip_count " "FROM trips WHERE gender NOT NULL AND birth_year NOT NUL...
d66cb7c9ac4404d2bc4f0b2c5c0cbe2d770cfcd8
natemurthy/misc
/toy-problems/2019-08-08/question1b.py
654
4.28125
4
# /* # Given an array of integers, determine whether the array only increases or only decreases. # Examples: # [1, 2, 3] --> True # [3, 2, 1] --> True # [1, 2, 4, 4, 5] --> True # [1, 1, 1] --> True # */ ''' Here is a more elegant solution from g4g: https://www.geeksforgeeks.org/python-program-to-check-if-given-a...
d960432e7acf9e1e0de3ff591dc34fcbb2588fca
NurbaTron/psycopg2.randomData
/month1/day.17.py
3,023
4.3125
4
"""ООП композиция""" """класс композиций - это у которого атрyибут является объектом другого класса""" # class Adress: # def __init__(self, streetname, city, homenum): # self.streetname = streetname # self.city = city # self.homenum = homenum # class Job: # def __init__(self, jobnam...
85d84f0ddd2195042ac4f61baaca6c020af20f96
CodeForContribute/Algos-DataStructures
/HashCodes/sum_pair_whose_sum_is_in_arr.py
1,089
4
4
def sum_pair_whose_sum_is_in_arr(arr, n): found = False for i in range(n): for j in range(i + 1, n): if arr[i] + arr[j] in arr: print((arr[i], arr[j]), end=" ") found = True if found is False: print("Not Found:") # for k in range(n): ...
3f404677c0bd468f7f6e909217099277cc73e6b8
Frankiee/leetcode
/math/ugly_number/313_super_ugly_number.py
1,407
4.03125
4
# [Prime-Factor, Ugly-Number] # https://leetcode.com/problems/super-ugly-number/ # 313. Super Ugly Number # Write a program to find the nth super ugly number. # # Super ugly numbers are positive numbers whose all prime factors are in the # given prime list primes of size k. # # Example: # # Input: n = 12, primes = [2,...
8378a330186bec3cf847276768f4e397c4fbe694
sahilkamesh/POS-Tagging
/baseline.py
2,068
3.546875
4
""" Part 1: Simple baseline that only uses word statistics to predict tags """ def baseline(train, test): ''' input: training data (list of sentences, with tags on the words) test data (list of sentences, no tags on the words) output: list of sentences, each sentence is a list of (word...
d89a48ba05e25d612c07f13f57a4d199835d646a
FlinnBurgess/seprcph
/seprcph/goal.py
3,039
3.796875
4
""" This module contains all classes relating to the goals of the game. """ from seprcph.event import EventManager, Event class Goal(object): """ Class that describes the player's goals """ def __init__(self, start_city, end_city, turns, gold_reward, points_reward, player, desc=""): """ ...
b21e6ee7a495bb06298bf6e05f8c3c21705b0194
bkiranid4u/python
/euler_problems/Euler007_10001_Prime.py
649
3.890625
4
"""Euler 005 - Problem: By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ from math import sqrt def is_prime_number(n): if n <= 3: return n > 1 elif n % 2 == 0 or n % 3 == 0: return Fals...
297a3effd1311c6d78d1fd8abca56e50fbce301e
milotr/studying-python-files
/Object-oriented-programming/definition/privateVariable-instance.py
884
4.4375
4
class ExampleClass: def __init__(self, val = 1): self.__first = val def setSecond(self, val = 2): self.__second = val exampleObject1 = ExampleClass() exampleObject2 = ExampleClass(2) exampleObject2.setSecond(3) exampleObject3 = ExampleClass(4) exampleObject3.__third = 5 print(exampleObjec...
29a624569926e2c586113afca8360147e0340a11
zunayed/puzzles_data_structures_and_algorithms
/practice_problems_python/insertion_sort.py
428
4.125
4
def insertionSort(num_list): for item in range(1,len(num_list)): current = num_list[item] position = item print "current" print current print num_list while position > 0 and num_list[position - 1] > current: print "in" num_list[item] = num_list[position - 1] position = position - 1 num_list[p...
a83766cc721dc159d2aa2f7df2aa4236bf3f3bb4
ktaletsk/daily-problem
/191219/Python/solution.py
342
3.734375
4
def getBonuses(performance): return [1 + ((1 if performance[i]>performance[i-1] else 0) if i>0 else 0) + ((1 if performance[i]>performance[i+1] else 0) if i<len(performance)-1 else 0) for i in range(len(performance))] def main(): print(getBonuses([1, 2, 3, 2, 3, 5, 1])) if __name__== ...
5b29f5b66eb705527e330e27f1d143de275f1e7c
sMamooler/Higgs-Boson-Classification
/implementations.py
5,260
3.703125
4
import numpy as np from proj1_helpers import * def compute_gradient(y, tx, w): """Compute the gradient. Parameters: y: target lables; an array of shape (N,1). N: Number of datapoints. tx: datapoint features; an array of shape (N,D+1). N: number of datapoints, D: number of features. w...
7d81c86053c60c8a7c3026b4b2c9a6494ecae47c
BlesslinJerishR/PyCrash
/__4__WorkingWithLists__/pizzas.py
233
3.828125
4
#4.1 pizzas = ["cheese","macroni","tomato","pasta","pineapple"] if __name__ == '__main__': for pizza in pizzas: print(f"Have you tasted {pizza.title()} pizza ?\n") print("How much you like pizza ?") print("I really love pizza")
a15b901df39dcb09e40d280b97ee0d68642fe12e
mamert/pi_mover_thingy
/proof-of-concept/motors/MotorDriver.py
1,531
3.578125
4
from abc import ABC, abstractmethod # AbstractBaseClass import pigpio class MotorDriver(ABC): # is NOT aware of PWM range """ Single motor control, parent class """ def __init__(self, pi, pins): self.__pi = pi self.__pins = pins def setup(self, freq, range): for pin in (self.__pi...
8a0660166d746ba89597e9668bf9ec1d24d3687e
caiquemarinho/python-course
/Exercises/Module 04/exercise_04.py
95
4.03125
4
""" Print the square of the given number """ num = 5 print(f'Square of {num} is {num**2}')
c7a69bdb176bd05e8b2d366b9eb2c6909caf555d
JyHu/PYStudy
/PYDayByDay/Tkinter_ST/Dialg_TK/Dialg2.py
1,376
3.78125
4
#coding=utf-8 __author__ = 'JinyouHU' ''' askinteger:输入一个整数值 askfloat:输入一个浮点数 askstring:输入一个字符串 ''' from Tkinter import * from tkSimpleDialog import * root = Tk() root.geometry('220x120+0+0') reInt = IntVar reFloat = FloatType reString = StringVar def intFunc(): # 输入一个整数, # initialvalue指定一个初始值 # ...
a4be0553d393a20374a2aa20e622cd8dca309459
killian2k/MyTorch
/mytorch/dropout.py
686
3.5625
4
import numpy as np class Dropout(object): def __init__(self, p=0.5): # Dropout probability self.p = p self.mask = np.zeros(None) def __call__(self, x): return self.forward(x) def forward(self, x, train = True): # 1) Get and apply a mask generated from np.random.binomial # 2) Scale your output accordin...
90bc79514216766e260dd5fb3a8549c370d75c69
amelialin/tuple-mudder
/ex12.py
534
4.125
4
age = raw_input("How old are you? ") height = raw_input("How tall are you? ") weight = raw_input("How much do you weigh? ") # This accomplishes the same thing as: # print "How old are you?", # age = raw_input() # print "How tall are you?", # height = raw_input() # print "How much do you weigh?", # weight = raw_input()...
2fb50288fe6345afe39a9c8ce321fb3dd1e5a423
jopemachine-playground/Algorithm-HW
/Assign02/fibonacchi.py
1,263
4.03125
4
def fibonacci_recursive(n): if n == 0: return 0 if n == 1: return 1 return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2) def fibonacci_bottomup(n): if n == 0: return 0 prev1 = 0 prev2 = 1 for i in range(2, n + 1, 1): temp = prev2 prev2 = prev1 + p...
f3c0f57c750e40488318d88e0ee813d2badf3154
DanielSacro/coding-projects
/Huffman-Coding/huffman.py
5,968
3.921875
4
class TreeLeaf: """ Leaf node of a Huffman tree. Stores the value. Should store an 8-bit integer to represent a single byte, or None to indicate the special "end of file" character. """ def __init__(self, uncompressed_byte): self.__value = uncompressed_byte def getValue(self): ...
a703af8bed003172ed97bfc91dbd87ee103664a8
KlimChugunkin/PyBasics-Course
/Perper_Leonid_dz_8/task_8_4.py
859
3.8125
4
""" Задание 4 Написать декоратор с аргументом-функцией (callback), позволяющий валидировать входные значения функции и выбрасывать исключение ValueError. Замаскировать работу декоратора. """ from functools import wraps def val_checker(arg_check_func): def _val_checker(func): @wraps(func) def wrap...
bc554f261de646882249b178fa479e3ce6a844bb
ankschoubey/Personal-Developer-Notes
/leetcode-lru.py
1,436
3.578125
4
class CacheItem: def __init__(self, id, value, compValue=1, order = 1) -> None: self.id = id self.compValue = compValue self.value = value self.order = order class PriorityQueue: items = [] def add(self, item: CacheItem): self.items.append(item) se...
c1c9732df90bcd7ff7fc5eec147053219365a454
henryxian/leetcode
/reverse_words_in a_string.py
399
3.765625
4
# 151. Reverse Words in a String class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ splitted = s.split() rev_str = "" if len(splitted): rev = splitted[::-1] for word in rev: rev_str = re...
a3d6417c71bd7c3f26514940fe2b84b04b90327a
jacqxu00/SoftDevProject0
/db.py
1,451
3.546875
4
import sqlite3 #enable control of an sqlite database import csv #facilitates CSV I/O import hashlib f="storytime.db" db = sqlite3.connect(f) #open if f exists, otherwise create c = db.cursor() #facilitate db ops #========================================================== #INSERT YOUR POPULATE CODE IN THIS ...
f0e2ea9dde95edae40c32f1bdd502a3416eab142
pedrolucas-correa/ies-python-lists
/Lista2/Lista 2 - Q. 10.py
324
3.546875
4
sexo = int(input("Digite 1 para feminino e 2 para masculino: ")) altura = float(input("Digite sua altura: ")) if sexo == 2: pesoideal = (72.7 * altura) - 58 print("Seu peso ideal é: ", round(pesoideal, 2)) else: pesoideal = (62.1 * altura) - 44.7 print("Seu peso ideal é: ", round(pesoideal, 2))...
c7f5f2f650aa525ab013f5559f9d6327981bf6a0
kmandli/Neural-Networks-Implementations
/Neural_Network.py
4,109
3.609375
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 10 11:24:50 2017 @author: kavya """ # Neural Networks from math import exp from random import seed import numpy as np from collections import defaultdict from sklearn import datasets from sklearn.preprocessing import MinMaxScaler from sklearn.model_selectio...
b74826b01ce47894de071df38fc75678fd894467
akhilakr06/pythonluminar
/oop/Add.py
119
3.5625
4
class Add: def set(self,a,b): self.a=a self.b=b print(self.a+self.b) sum=Add() sum.set(4,5)
a116bbaa36505cd72877d008880df2f08981a79f
ChuanleiGuo/AlgorithmsPlayground
/LeetCodeSolutions/python/572_Subtree_of_Another_Tree.py
843
3.734375
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSubtree(self, s, t): """ :type s: TreeNode :type t: TreeNode :rtype: bool """ def is_same(sub1, sub2): ...
dd5712d29de30b8d785bf9420757d2771c548258
NegruGeorge/LFTC-labs
/lab2.py
2,037
3.625
4
f = open("input.py","r") # for line in f: # print(len(line)) # for s in line: # print(s =="\n") # print(s==" ") # break def cuvantRezervat(cuv): if(cuv =="**" or cuv == "<=" or cuv ==">=" or cuv =="==" or cuv == "!="): # print(cuv + "?/////////////////////") retur...
edbdbb39c3503c78cef153d269c89c64626ed1cc
su2me2rain/lethuylinh-fundamental-c4e16
/Session 1/Circle_area.py
106
4.09375
4
r= float(input("What is your radius? ")) area = 3.14159 * r**2 print("The area of your circle is ", area)
f678f32677b1c80188d85ef8092b7d225e11276a
GhostBat101/SomeBasicStuffs
/ClassinClass.py
406
3.625
4
class Student: def __init__(self, name, roll): self.name = name self.roll = roll self.lap = self.Laptop() def showinfo(self): print(self.name, self.roll) class Laptop: def __init__(self): self.brand = 'hp' self.ram = 16 self.cpu =...
551f98ae926c5716d72545a45036aef59558ae13
kmggh/rajbots
/robots/minmax_bot.py
375
3.71875
4
""" Attempts to win every tile (including negatives) by playing its highest or lowest card. """ from raj import Player class MinMaxBot(Player): """ MinMax will return its smallest or largest card, depending upon the current tile """ def play_turn(self): if self.board.current_tile.value < 0: retu...
dab38f37cd14c53f641ce5a453350c683e97e20a
a1424186319/tutorial
/sheng/tutorial/L3函数/递归练习2.py
233
3.53125
4
# 计算1+2+3 ....+99+100 def f(n): if n >= 0: return f(n - 1)+n else: return 0 print(f(100)) # 高斯算法公式n*(1+n)/2 def f(n): if n == 1: return 1 return f(n - 1)+n print(f(100))
d7e5111382f2368564d228026c1d212c882a5284
Fatihnalbant/deneme_2
/sozcukListe.py
649
4.1875
4
""" Bir yazı okuyunuz. Yazı boşluk karakterleriyle ayrılmış sözcüklerden oluşmuş olsun. Aynı sözcükleri atarak sözcükleri bir listeye yerleştiriniz. Örneğin girilen yazı şöyle olsun: bugün hava evet bugün çok hava güzel güzel Sonuç olarak şöyle bir liste elde edilmeli: ['bugün', 'hava', 'evet', 'çok', 'güzel']...
aef77eb30c56e746db93b9eab7767e773550fa19
mysqlbin/python_note
/2020-03-24-Python-ZST-base/2020-08-28-条件循环控制/2020-04-19-03.py
736
3.734375
4
#!/usr/bin/ptyhon #coding=gbk """ """ count = 5 while count > 0: count = count - 1 if count == 3: continue print('ݿͱÿһ,count: {}'.format(count)) """ count = 5 0count143 ݿͱÿһ,count: 4 count = 4 0count13 ѭ count = 3 0count123 ݿͱÿһ,count: 2 count = 2 0count113 ݿͱÿһ,count: 1 count = 1 0count103 ݿͱÿһ...
ac0b55b77fc3b4e7fa117d9c762c94b203959deb
liangyf22/test
/02_面向对象/类实现装饰器.py
382
4.21875
4
# 实现了__call__方法的类,允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b) class Myclass(object): def __init__(self,func): self.func =func def __call__(self, *args, **kwargs): print("洗手") self.func() print("擦嘴") @Myclass # func = Myclass() def func(): print("吃饭了") func()
2ed4c0194cd43fe92a101a848673cc78e0bd3504
lukethink/projecteuler
/problem19.py
1,772
4.3125
4
""" 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How man...
6116801d0904cc21984027d04ce470ae288cbaa1
sontung/libgeom
/math_utils.py
1,438
3.84375
4
import numpy as np def cross(a, b): """ Calculate cross product of 2 vector a and b. a, b is array has shape (3, 1) :param a: :param b: :return: """ a1, a2, a3 = a b1, b2, b3 = b ss = [a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1] return np.array(ss) def dot(a, b): """ ...
4ff279b67e4d1c545225312978b72ce5ec7f39fe
iamsamueljohnson/CP1404practicals
/Practical_01/loops.py
361
4.15625
4
for i in range(0, 101, 10): print(i, end=' ') print() for i in range(20, 0, -1): print(i, end=' ') print() for i in range(20, 0, -1): print(i, end=' ') print() number = int(input("Enter number: ")) for i in range(number): print(end='*') print() number = int(input("Enter number: ")) for i in range(1,...
40988a3f2f1b700a9b2abeddadf8bd621b8e38a0
Payiz-2022/python
/study/list.py
843
4.03125
4
# -*- coding: utf-8 -*- #列表数据类型,有序的集合,可以随时添加和删除其中的元素[] classmate = ['A','B','C'] print(classmate) print(len(classmate))#获取list元素个数 print(classmate[0]) print(classmate[-1]) classmate.append('D')#末尾添加元素 print(classmate) classmate.insert(1,'AB')#把元素插入到指定位置 print(classmate) classmate.pop() print(classmate) classmate.pop(1)...
c6b70100c057566516457c6c40dd254c018400c6
kuohan95/Virtual-Machine
/log_analysis.py
2,736
4.03125
4
#!/usr/bin/env python2 import psycopg2 DBNAME = "news" def db_connect(): """ Creates and returns a connection to the database defined by DBNAME, as well as a cursor for the database. Returns: db, c - a tuple. The first element is a connection to the database. The ...
fe74aba99649b2cd6ed6f409b9b6db880844866e
CiaranGruber/CP1404practicals
/prac_03/gopher_population_simulator.py
918
3.9375
4
""" A simulator that simulates a gopher population in a library 11/08/18 - Created by Ciaran Gruber """ import random REPEATS = 9 STARTING_POPULATION = 1000 MIN_INCREASE = 10 MAX_INCREASE = 20 MIN_DECREASE = 5 MAX_DECREASE = 25 def main(): population = STARTING_POPULATION year = 1 print('Welcome to the...
91edf62554f1736a4c982c0e11d1c4694e62be9c
candyer/exercises
/pixel.py
4,757
4.71875
5
from PIL import Image def make_shape(func, width=300, height=100): ''' take a function and use it to draw a shape :D the function will receive the arguments: - pixels: a 2d list - width: the width of the image - height: the eight of the image - black_pixel: a black pixel that can be put inside "pixels" ''' im...
5e3f6830ca212425f909c9c837a97e2f81bd3a53
adam-weiler/GA-Reinforcing-Exercises-Programming-Fundamentals-Project
/exercise.py
882
4.125
4
from project import project # print(project) # The entire dictionary # print(project.keys()) # dict_keys(['committee', 'title', 'due_date', 'id', 'steps']) # print(project['committee']) # ['Stella', 'Salma', 'Kai'] # print(project['title']) # "Very Important Project" # print(project['due_date']) # "December 14, 2...
73a38a437db32df09b4b97593012410960f41a68
Gttz/Python-03-Curso-em-Video
/Curso de Python 3 - Guanabara/Mundo 03 - Estruturas Compostas/Aula 17 - Listas (Parte 1)/080 - Lista_ordenada_BubbleSort.py
588
4.25
4
# Exercício Python 080: Crie um programa onde o usuário possa digitar cinco valores numéricos e cadastre-os em uma # lista, já na posição correta de inserção (sem usar o sort()). No final, mostre a lista ordenada na tela. lista = list() for i in range(1, 6): lista.append(int(input(f"Digite o valor para a {i...
09d19a8da7f2af72d3b7129a0155cde9780c6041
nanihari/python_lst-tple
/clone_tuple.py
203
3.953125
4
##program to create the clone of a tuple. from copy import deepcopy tuple_1=("hari", 123, [], False) tuplex_clone=deepcopy(tuple_1) tuplex_clone[2].append(56) print(tuplex_clone) print(tuple_1)
b184c919d0d4dc2ea2fef0a8a1965624511760dc
darthsteedious/adventofcode
/2018/day_2/__init__.py
474
3.5625
4
def run(): freqs = set() with open('./input', 'r') as fp: current = 0 while True: line = fp.readline() if line == '': fp.seek(0) continue value = int(line, 10) current = current + value if current in fre...
eeb0111a5ca104370396802a48b1df9a100321ff
michelledeng30/meso
/astar.py
6,001
3.796875
4
from cmu_112_graphics import * import basic_graphics, time, random import objects, frames, message, play from dataclasses import make_dataclass # astar runs the search algorithm for the humans by taking in a start and end position # and generating a path. it also sets up the grid with the obstacles # CITATION: for l...
0f5a2e36e626c2d8dab9158a93a12538ede1f642
kamil-fijalski/python-reborn
/8 - Zgaduj-Zgadula.py
908
4.03125
4
import random continues = 'T' print('Play a game... Guess my secret number.') while continues == 'T' or continues == 't' or continues == 'Y' or continues == 'y': secretNum = random.randint(0, 10) print('How do you think... What number did I choose?') try: ans = int(input()) except ValueError:...
879c952b4df7ea3799445ae4a02ddc29dae61564
harry-martins/greater
/greater.py
101
3.71875
4
x,y,z=map(int,input().split()) if x>y and x>z: print(x) elif y>x and y>z: print(y) else: print(z)