blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
673a60a297971ba7a9892ad4afc6473b800ae3f8
claudiubocioaga/python-training-aug2020
/examples/decorators.py
649
3.78125
4
def decorator(func): def inner(*args, **kwargs): print(f'Before calling {func}') return_value = func(*args, **kwargs) print(f'After calling {func}') return return_value return inner @decorator def say_hello(): print('Hello world!') @decorator def greet(name, upper=False):...
cfea059a14dbcfb9d35465141901972cfc4e11dd
andreeall00/BattleshipGame
/entities.py
2,320
3.609375
4
class Boat: def __init__(self, name, size): self.name = name self.size = size self.row = None self.col = None self.orientation = None def get_name(self): return self.name def get_size(self): return self.size def get_row(self): return sel...
d5a288d818c80ec4deb0c954038d1ff7f882463e
kristynf/Python_Training
/carpet.py
538
4.15625
4
print "This program will calculate the square footage of carpet needed for a room" length = float(raw_input("What is the length of the room: ")) width = float(raw_input("What is the width of the room: ")) cost_per_yard = float(raw_input("What is the cost per yard?: ")) print type(length) print type(width) sqft = length...
eb813fc5ca9a49bc68df82637e449beb55dc28f8
Estrada1997/clase-15
/clase 15.py
1,344
3.84375
4
class Logica: def __init__(self, lista=None): self.__lista = lista # no presenta por pantalla / privado # self. dato = 0 este si presenta por pantalla / no privado @property def lista(self): return self.__lista @lista.setter def lista(self, value): self.__l...
0a9d3132f611f2a1ad8092c677264e1418577e17
BackToTheSchool/assignment_hw
/171107_Python/001.py
243
4.15625
4
# 001 인사하기 # 이름을 입력 받아 인사말을 출력하는 프로그램 # Example # What is your name? Brain # Hello, Brain, nice to meet you print('What is your name?') name = input() print('Hello,', name, ', nice to meet you')
15f16f265f799157a2489061ef34b28dad42739f
BackToTheSchool/assignment_hw
/171108_Python/040.py
912
3.828125
4
# 040 필터링 레코드 # fName lName position sepDate # John Johnson Manager 2016-12-31 # Tou Xiong SoftEngineer 2016-10-15 # Michaela Michaelson District Man. 2015-12-19 # Jake Jacobson Programmer # Jacquelyn Jackson DBA # Sally Weber Web Developer 20...
d61f32db03b89b0137d060be2f6405504eaf1d1b
BackToTheSchool/assignment_hw
/171107_Python/009.py
609
3.859375
4
# 009 페인트 계산기 # 천장을 칠하는 데 필요한 페인트 양을 구하는 프로그램을 작성하라. # 길이와 폭을 입력 받은 다음, 1리터에 9m2을 칠한다고 가정하여 계산하자. # 그리고 천장을 칠하는 데 필요한 페인트 양을 정수로 표현해보자. # Example # You will need to purchase 2 liters of # paint to cover 10 square meters. import math length = int(input("Length? ")) width = int(input("Width? ")) print("You will need t...
3a029db0ce88e5996a88db8da666b9aa73909bc1
BackToTheSchool/assignment_hw
/171107_Python/021.py
680
4.125
4
# 021 숫자에 해당하는 이름으로 바꾸기 # 1부터 12까지의 숫자를 해당하는 달로 변환시키는 # 프로그램을 만들어보자. 먼저 숫자를 입력받은 다음 # 이에 해당하는 달 이름을 출력한다. # 만일 범위를 넘어서는 숫자를 입력 받은 경우엔 # 적절한 에러 문구를 출력하자. month = int(input("Enter a month: ")) monthInAlpha = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'Octobe...
229e4898a9758fcb7829edfe7683f8e3f0b0e88f
BackToTheSchool/assignment_hw
/171107_Python/008.py
873
3.984375
4
# 008 피자 파티 # 피자를 정학하게 나누는 프로그램을 작성하라. # 사람수, 피자 개수, 조각 개수를 입력 받는데, 이때 조각 개수는 짝수여야 한다. # 일단 한 사람이 받게 되는 피자 조각 개수를 출력해보자. # 만일 남는 조각이 있다면 그 개수도 나타내보자. # Example # How many people? 8 # How many pizzas do you have? 2 # How many pieces are in a pizza? 8 # 8 people with 2 pizzas # Each person gets 2 pieces of pizza. # The...
3c903e8c37c14c89c5d98e30a7d183960a656867
Edestus/HW_geekbrains_python
/DZ_1.py
4,085
4.03125
4
# # 1. Поработайте с переменными, создайте несколько, выведите на экран, # # запросите у пользователя несколько чисел и строк и сохраните в переменные, выведите на экран. # # a = 5 # b = "abc" # c = input("ведите число") # d = input("И еще строку") # print(a, b, c, d) # # # 2. Пользователь вводит время в секун...
af10a23992805e2e94fd147bae7de396b833c4ce
thetinshusasi/PythonTut
/print_module.py
581
3.90625
4
def print_values(*values): for item in values : print(str(item)) class Car(): def __init__(self, make , model, year): self.make = make self.model = model self.year = year def get_descriptive_name(self): """Return a neatly formatted descriptive name.""" long_n...
03f0502d89232401379d144c7b464746af1d0980
sy-tencho/algorithms_specialization
/part3/week3/huffman/index.py
854
3.5
4
import heapq import sys class Tree(): def __init__(self): self.data = None self.left = None self.right = None heap = [] for i in input[1:]: tree = Tree() tree.data = i heapq.heappush(heap, (tree.data, tree)) while len(heap) >= 2: _, t1 = heapq.heappop(heap) _, t2 = ...
2fca19a13d75b3d54a66126ef934cd7455c7032a
zztczcx/myleetcode
/easy/majority_element.py
1,280
3.671875
4
# -*- coding:utf-8 -*- # Given an array of size n, find the majority element. # The majority element is the element that appears more than ⌊ n/2 ⌋ times. # # You may assume that the array is non-empty # and the majority element always exist in the array. # beats 71% class Solution(object): def majorityElement(sel...
459cbb4840a8161df19ef204d6a7f13b185d4e1d
zztczcx/myleetcode
/rotate_list.py
1,010
3.90625
4
# -*- coding:utf-8 -*- # Given a list, rotate the list to the right by k places, where k is non-negative. # # For example: # Given 1->2->3->4->5->NULL and k = 2, # return 4->5->1->2->3->NULL. # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # s...
92e5d14353078db0bf4c5facafa2d5f1f8691101
Akmal4163/Calculator-of-Economic-Performance
/GNP-NNP.py
775
3.734375
4
print("program perhitungan NDP-NNP") GDP = float(input('masukkan nilai GDP : ')) GNP = float(input('masukkan nilai GNP : ')) depreciation = float(input('masukkan nilai depresiasi : ')) sales_tax = float(input('masukkan pajak penjualan : ')) earnings = float(input('masukkan pendapatan : ')) personal_income_tax = f...
ea27ef38e24cf49d9d5b345dffd51f2b2835dbb4
MinneStephanie2/1NMCT4-LaboBasicProgramming-stephanieminne14
/week2 selectiestructuren/werken met functies/oefening 6.py
699
3.703125
4
keuze = int (input("Welke eeneheid gebruikt u? (1: celsius, 2: fahrenheit)")) def geef_celsius(keuze): fahrenheid = (celsius - 32) * 5 / 9 print("je temperatuur in graden fahrenheid is {0}".format(fahrenheid)) print(geef_celsius(fahrenheid)) def geef_fahrenheit(keuze): celsius = (fahrenheid * 9 / 5)...
f0b97c685e84afbc23416a73e645340067b9c2ee
MinneStephanie2/1NMCT4-LaboBasicProgramming-stephanieminne14
/week2 selectiestructuren/werken met functies/oefening 4.py
233
3.671875
4
a = int( input("geef een getal: ")) b = int (input("geef een getal: ")) c = int (input("geef een getal: ")) import math def berekenMax (a,b,c): maximum = max(a,b,c) print("Het maximum {0}".format(maximum)) berekenMax(a,b,c)
5c4b1c0520aaf9b60efe3b4a7a6676f38408564a
MinneStephanie2/1NMCT4-LaboBasicProgramming-stephanieminne14
/week2 selectiestructuren/werken met functies/oefening 2.py
211
3.578125
4
naam = input("geef uw naam") # groep = str(input("geef uw groep")) def printWelkom (naam,groep ="1NMCT1"): print("welkom {0} en jij zit in groep {1}. Heb een fijne dag".format(naam,groep)) printWelkom(naam)
bbe19d9f70ecd284fef2e8dee0b603e274451a6f
MinneStephanie2/1NMCT4-LaboBasicProgramming-stephanieminne14
/week2 selectiestructuren/werken met functies/demo functies.py
1,017
3.6875
4
# lengt = 4 # breedte = 6 # oppervlaketehoek= lengt*breedte # # lengt2= 3 # breedte2 = 8 # oppervlaketehoek2= lengt2*breedte2 # lengte = int (input("geef de lengte")) # breedte = int( input("geef de breedte")) # #functie schrijven def berkenoppervlakteRechthoek (lengte =0, breedte=0): #eventueel kan je een default mee...
9c0a088dbdd7e8bb2a43abcbf930c0dd902026fd
chitrakakkar/Lab3_UnitTesting_Coffee
/main.py
5,289
4.125
4
""" This class displays the interface""" from drink import Drink from food import Food from validator import * def show_menu(): """ displays the menu for the user checks if user has chosen the right choice from the list and calls methods to complete the action""" menu = ('\t1) choose a drink\n' ...
23164cd131f8e3903ffea46d6400a3648b88475b
Bernadette321/algorithm012
/Week_02/94_中等_二叉树的中序遍历_binary-tree-inorder-traversal.py
3,230
3.90625
4
# https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ # Definition for a binary tree node. from typing import List class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None ''' 法1: 递归 时间复杂度: O(n), n为节点数, 访问每个节点恰好一次 递归遍历: + 前序遍历: 打印-左-右 + 中序遍历: 左-打...
069bf46d398d68f5c1fbed4f7a917666e6279e21
LukeJakielaszek/PA3
/pa3.py
11,236
3.578125
4
''' Add the code below the TO-DO statements to finish the assignment. Keep the interfaces of the provided functions unchanged. Change the returned values of these functions so that they are consistent with the assignment instructions. Include additional import statements and functions if necessary. ''' import c...
ae882fccd5b7c9e45473650c9af5d22e17b6acb8
tomtom285/untitled1
/tameshini.py
506
3.875
4
value = input("身長をcmで入力してください:") tall = float(value) print("身長:",tall,"cm") value = input("体重をkgで入力してください:") weight = float(value) print("体重",weight,"kg") bmi = round(weight / ((tall / 100) * (tall / 100)),2) print("BMIは",bmi,"で") if bmi > 25: hantei = '肥満' elif bmi >= 18.5: hantei = '標準' else: hantei = '痩...
ad035120a4c7684aa1315d29cb1124d6c4175528
jiangchenrui1994/pythonProject
/python_class/demo08_抽象类.py
1,092
3.84375
4
from abc import ABCMeta,abstractmethod #抽象类 #1、抽象类要有抽象方法 #2、要有抽象定义语句 #3、抽象类是用来被继承的,如果没有被继承,是毫无意义的 class animal(metaclass= ABCMeta): #这种写法子类必须实现父类的抽象方法 # __metaclass__ = ABCMeta #抽象声明 这种写法子类不是强制性必须要实现抽象方法 def __init__(self,name,age): self.name = name self.age = age #抽象方法 @abstractmeth...
1b1f1b3336568d9b2b6d545cdfd1163db177b831
jiangchenrui1994/pythonProject
/python_class/demo09_抽象类案例.py
889
3.953125
4
from abc import ABCMeta,abstractmethod # 学生----去教室读书 # 老师----去教室上课 # people:name age 方法:goto_class class people(metaclass=ABCMeta): def __init__(self,name,age): self.name = name self.age = age @abstractmethod def goto_class(self): pass class student(people): def __init__(self...
ef081aa7b26a2eac259597544d8e3ab649ede4ea
jiangchenrui1994/pythonProject
/Charpo1/demo03.py
1,038
3.796875
4
# #多继承 一个子类有多个父类 # # 人类 --老师--司机 # class people: # def __init__(self,name): # self.name = name # def say(self): # print('我是人类,我会说话') # def sleep(self): # print('我需要睡觉') # # class teacher: # def __init__(self,courseName): # self.courseName = courseName # def say(se...
813910455e4c059e5c72404204dc0a5d0adde5ee
nicholas1026/PythonStudy
/chapter08/e8-12.py
197
3.5625
4
def show_stuff(*stuffs): for stuff in stuffs: print("There are "+stuff+" in the sandwichs") show_stuff("apple") show_stuff("banana","orange") show_stuff("berry","watermelon","lemon")
047866011b1c8ec15bd7fafe200207e50505d081
nicholas1026/PythonStudy
/chapter09/e9-1/restaurant.py
728
4.15625
4
class Restaurant(): """一个简单的餐馆类""" def __init__(self,restaurant_name,cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print("This restaurant name is:"+self.restaurant_name+" and it's cuisine type is:"+self.cuisine...
3e0dbb3fd503288630740fe3f3efb41710f1f8a0
churskir/JFiK
/validator.py
879
3.640625
4
from ClassesExpressions import * def validate(lines): for line in lines: validateLine(line) def validateLine(line): word = line.pop(0) print(word) if word == "SubClassOf": return SubClassOf(line) elif word == "EquivalentClasses": return EquivalentClasses(line) elif wo...
a0179659426d262fe7c69f2e94d9d7ba676e4c65
snhuber/ib-api-project
/modules/timeit.py
399
3.65625
4
# # DESCRIPTION # Measures time of function execution import functools import time def timeit(func): @functools.wraps(func) def newfunc(*args, **kwargs): startTime = time.time() func(*args, **kwargs) elapsedTime = time.time() - startTime print('function [{}] finished in {} min...
afa648880bb44005b3bb5075eb598328ccd6879d
bounpraseuthh9003/02-RPS-Game
/08_RPS_Instructions.py
1,359
4.3125
4
played_before = "" instructions = "**** How To Play ****\n" \ "\n" \ "- Choose the amount of rounds you want to play \n" \ "or press <enter> for infinite mode\n" \ "\n" \ "For each round, choose from rock / paper / scissors (or xxx to quit)\n" \...
b63c743d618d7dd0bb61abf56cc5b6b54650ccd1
the-st0rm/coding-challenges
/Restoring_Password_cd.py
424
3.671875
4
#!/usr/bin/env python #http://codeforces.com/problemset/problem/94/A pass_phrase = raw_input() counter = 0 d = {} pf = list() while counter < len(pass_phrase): pf.append(pass_phrase[counter:counter+10]) counter +=10 password = list() for i in range(10): d[raw_input()]=(i) for p in pf: if p in d: ...
cfa0e241634b6ce621b2f1b523c01e1725919656
the-st0rm/coding-challenges
/stack_class.py
820
3.734375
4
#!/usr/bin/env python import os class stack: ll = None cursor = -1 MAX_SIZE = 10 def __init__(self, size=10): self.MAX_SIZE = size self.ll = [None]*size self.cursor = -1 def pop(self): if self.cursor ==-1: print "ERROR STACK UNDERFLOW" ...
87d5d5b62163ca1addb0a3f0a8bed73f96b5a844
the-st0rm/coding-challenges
/Sinking_Ship_cd.py
424
3.65625
4
#!/usr/bin/env python #http://codeforces.com/problemset/problem/63/A import Queue q = Queue.PriorityQueue() n = input() evac = list() ranks = {"captain":3, "man":2, "woman":1, "child":1, "rat":0} evac = [0]*4 for i in range(4): evac[i]=[] for i in range(n): name, rank = raw_input().split(' ') r = ranks...
50cb803d9060c68ac2fee874bc4449babdd04446
soil-physics-okstate/automated_soil_moisture_mapping
/static_data/soil_properties/meso_soil/cache_mesosoil.py
705
3.53125
4
from pandas import read_excel # input file fname = 'MesoSoilv2_0.xlsx' # skip the first row (describes file) and third row (describes units) # and turn missing data (-9.9) into NaNs df = read_excel(fname, header=0, skiprows=[0,2], na_values=['-9.9']) # make the columns use lowercase df.columns = [c.lower() for c in ...
59821cfb8244ed4e7d94537fc925076e98578156
tarekait1996/python
/Oop.py
1,127
4
4
''' this is question 1 of the assignment''' import math class Line(object): def __init__ (self, coor1, coor2): self.coor1 = coor1 self.coor2 = coor2 def distance(self): distance = abs( ((self.coor1[0] - self.coor2[0])**2 +(self.coor1[1] - self.coor2[1])**2)**(1/2)) return dist...
4fd36f91f1e9fe5256cf99c2202e21fd3fbd006d
onikun94/atcoder
/abc201/a/main.py
184
3.65625
4
A1, A2, A3 = map(int, input().split()) if A3 - A2 == A2 - A1: print("Yes") elif A2 - A1 == A1 - A3: print("Yes") elif A1 - A3 == A3 - A2: print("Yes") else: print("No")
846a12ee2d265c5474e451a354a948590d62b4d8
nvv11/algorithms_and_data_structures_in_python
/Lesson_9/task_2.py
766
3.765625
4
from binarytree import bst def search(bin_search_tree, number, path=''): if bin_search_tree.value == number: return f'Число {number} обнаружено по следующему пути:\nКорень{path}' if number < bin_search_tree.value and bin_search_tree.left != None: return search(bin_search_tree.left, number, p...
86528193986930d68fcea89c5db57f3fbc05d16b
nvv11/algorithms_and_data_structures_in_python
/Lesson_1/task_3.py
1,681
4.15625
4
# Написать программу, которая генерирует в указанных пользователем границах: # случайное целое число, # случайное вещественное число, # случайный символ. # Для каждого из трех случаев пользователь задает свои границы диапазона. # Если надо получить случайный символ от 'a' до 'f', то вводятся эти символы. # Програ...
ae55e97e62d8b1898dd194d14c97e325cdac362f
nvv11/algorithms_and_data_structures_in_python
/Lesson_9/task_8.py
737
4.28125
4
# Определение количества различных подстрок с использованием хеш-функции. # Пусть на вход функции дана строка. Требуется вернуть количество различных # подстрок в этой строке. def count_substring(s: str): set_hash = set() for i in range(len(s) - 1): for j in range(i + 1, len(s) + 1): set...
76357b150594eec9606af47253bcf96b91f06a06
nvv11/algorithms_and_data_structures_in_python
/Lesson_2/task_4.py
352
3.984375
4
# Найти сумму n элементов следующего ряда чисел: 1, -0.5, 0.25, -0.125,… # Количество элементов (n) вводится с клавиатуры. n = int(input('Сколько элементов сложить: ')) item = 1 summ = 0 for i in range(n): summ += item item /= -2 print(summ)
ae83ddacb88098fb1db1447ae0bb97af0dbe9b09
gmauricio/game-of-life
/tests.py
2,636
3.5625
4
import unittest from game import World, Cell class WorldTest(unittest.TestCase): def test_counting_0_corner_cell_neighbours(self): world = World(2, 2) world.set([ [Cell(0), Cell(0)], [Cell(0), Cell(0)] ]) self.assertEqual(0, world.get_neighbourhoods()[0][0]) def test_counting_3_corner_cell_neighbour...
76506199dc8d3bb15891f475ad5706f3fc429832
CLindo01/Integration-Project
/main.py
9,039
4.5
4
"""This program will allow a user to choose from a variety of shapes and calculate them.""" # Shape Calculator # Hello this program will ask for what shape you'd like to calculated import math __AUTHOR__ = "Christian Lindo" # Used in order to run math.pi def circle_diameter_circumference_area(radius): """ :...
851881f7fc4a1dc482098497b46ca3b17f26dfd4
lizhenfen/works
/elasticsearchs生产/web/comm/comm.py
1,251
3.625
4
import time import functools import datetime import calendar def outer(func): @functools.wraps(func) def inner(*args, **kwargs): start_time = time.time() res = func(*args,**kwargs) end_time = time.time() if isinstance(res,dict): res["time"] = '{:.2f}'.format(end_time...
c70393bb2c811bc351f70ff0ac98c7928bd40461
shreeprem4u/studies-python
/text_to_map.py
492
3.5625
4
from shapely.geometry import Point, LineString, Polygon import csv import numpy as np import matplotlib import matplotlib.pyplot as plt file = open("/home/researcher/Documents/Premkumar/python/check_data.csv", "r") myreader = csv.reader(file) header = myreader.next() x = header.index("x") y = header.index("y") data ...
0f90cd5d04615c8470b933b4f45ee2590c70866f
finkmoritz/pythonExamples
/fibonacci.py
348
4.0625
4
def fibo(n): if n in [0,1]: return n else: return fibo(n-1)+fibo(n-2) n = 3 print(str(n)+'th Fibonacci number = '+str(fibo(n))+'\n') def fibonacci_numbers(max): a,b = 1,1 while a < max: print(a) a,b = b,a+b nMax = 10 print('Fibonacci numbers smaller than '+str(nMax)+'...
14cc6c405ed3c56a351fd2079d5230456e67eb20
Nur-A-Alam1997/BioInformatics-Algo-UCSD
/Finding Hidden message in Dna/motif in matrix preparation.py
431
3.78125
4
String="TCGGGGgTTTttcCGGtGAcTTaCaCGGGGATTTtCTtGGGGAcTTttaaGGGGAcTTCCTtGGGGAcTTCCTCGGGGATTcatTCGGGGATTcCtTaGGGGAacTaCTCGGGtATaaCC" print(len(String)) Motif=[[0 for i in range(12)]for x in range(10)] c=0 for i in range(10): for j in range(12): Motif[i][j]=String[c] c=c+1 #print("...
b332b1fb826ff51f2a9b5d284466e6f81e248ed6
Nur-A-Alam1997/BioInformatics-Algo-UCSD
/Finding Mutations In DNA/Higherarchical clustering.py
4,752
3.546875
4
import sys import numpy as np from copy import deepcopy ''' Implement HierarchicalClustering. Input: An integer n, followed by an n x n distance matrix. Output: The result of applying HierarchicalClustering to this distance matrix (using Davg), with each newly created cluster listed on each line...
f4c47f37103c49bc0282ecedaf9e58fd86d7ce62
UsualMistake/LPTHW3_Solutions
/ex5.py
792
3.984375
4
my_name = "Nelson A. J." my_age = 28 # Fucking True my_height = 68 # Inches my_height_cm = round(my_height * 2.54) my_eyes = 'dark-brown' my_weight = 155 #lbs my_weight_kg = round(my_weight * 0.454) my_teeth = 'white' my_hair = 'black' print(f"Let's talk about {my_name}.") print(f"He's {my_height} inches tall.") print...
9548228cbacd35ed6c716f7c0bc3f620d12538a9
aayush19973636/Introduction
/More on Loops/Number_pyramid.py
443
3.75
4
n = int(input()) for i in range(1, n+1): count = 1 for j in range(1, i): print(" ", end="") count += 1 num = i for j in range(count, n+1): print(num, end="") num += 1 print() for i in range(n-1, 0, -1): count = 1 for j in range(1, i): print(" ", end=...
1c43decc21346811b68392fab823d3c234498b7d
aayush19973636/Introduction
/Searching and Sorting/Second_Largest.py
651
3.546875
4
from sys import stdin def secondLargestElement(arr, n): #Your code goes here largest = second = -2147483648 for i in range(n): largest = max(largest, arr[i]) for i in range(n): if arr[i] != largest: second = max(second, arr[i]) return second #Taking Input Usi...
ff7d61fa92606a00499874d0c347ee4543b3ef1e
aayush19973636/Introduction
/More on Loops/Print_the_pattern.py
337
3.5
4
n = int(input()) start = 1 for i in range(1, n+1): for j in range(start, start+n): print(j, end=" ") print() if i == (n+1)//2: if n%2 != 0: start = n*(n-2)+1 else: start = n*(n-1)+1 elif i>(n+1)//2: start = start - 2*n else: start...
2a31b7ee20606a686cdb5441c7f1dca3524ebd94
aayush19973636/Introduction
/Array and Lists/Array_Unique.py
508
3.546875
4
import sys def findUnique(arr, n): #Your code goes here n = len(arr) dup = 0 for i in range(n): dup = dup ^ arr[i] return dup #Taking Input Using Fast I/O def takeInput(): n = int(sys.stdin.readline().rstrip()) if n == 0: return list(), 0 arr = list(map(int, sy...
ebb7ae46c16a49b03eb879ba7ec55485480dfdbd
Cade-McPartlin/AdventOfCode2020
/DAY3.py
2,986
4.5
4
# https://adventofcode.com/2020/day/3 # Determine the number of trees you would encounter if, # for each of the following slopes, you start at the top-left corner # and traverse the map all the way to the bottom: # # Right 1, down 1. # Right 3, down 1. (This is the slope you already checked.) (Question 1) # Right 5, do...
d220ea6a97bf4d5102c587fca091e4453663a2fd
llggtty/quant_exercise
/game_show.py
2,469
3.984375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Oct 21 12:38:43 2018 @author: annhuang Game show You participate in a game show. The game consists of n rounds. During each round, the game show host proposes you a prize of a known value (in USD). You have two choices:  You can take the prize and en...
d79c0277d624ddadac061fec2a04859e6b688654
MaxOvcharov/python_desing_patterns
/behavioral_patterns/template_method_pattern/template_method_exp2.py
1,370
3.65625
4
#!/usr/bin/env python3 # coding: utf-8 """ EXAMPLE - https://github.com/pkolt/design_patterns/blob/master/behavior/template_method.py. Шаблонный метод (Template method) - паттерн поведения классов. Шаблонный метод определяет основу алгоритма и позволяет подклассам переопределить некоторые шаги алгоритма, не изменяя ег...
2901886327df7d041dcafe620a7f2926ba20857c
MaxOvcharov/python_desing_patterns
/structural_patterns/decorator/fun_decorator_with_args.py
1,654
3.546875
4
import functools import time def timer(repeat_num: int=0, meta: bool=False): print(f"START INIT timer: {time.time()}") def create_timer(func): print(f"START INIT create_timer: {time.time()}") results = set() @functools.wraps(func) def wrapper(*args, **kwargs): ts...
70a8e8fc09efbee16f1be53064dbf4118984b94c
MaxOvcharov/python_desing_patterns
/structural_patterns/facade/facade_exp3.py
1,500
3.546875
4
# coding: utf-8 """ Example from - https://github.com/pkolt/design_patterns/blob/master/structural/facade.py Фасад (Facade) - паттерн, структурирующий объекты. Предоставляет унифицированный интерфейс вместо набора интерфейсов некоторой подсистемы. Фасад определяет интерфейс более высокого уровня, который упрощает исп...
fe488ceeb6215a2b0b75dcbf7b4c7d9eb63c9b12
TooAboil/FiveInARowRobot
/python/test.py
158
3.71875
4
d = {'a':1,'b':4,'c':2} print(sorted(d.items(),key = lambda x:x[1],reverse = True)) mydict_new = dict([val,key] for key,val in d.items()) print(mydict_new)
4cdde2757429f2cf830078893427981f5bdbdf9c
data602sps/assignments
/05_assignment.py
9,366
3.75
4
''' Assignment #5 1. Add / modify code ONLY between the marked areas (i.e. "Place code below") 2. Run the associated test harness for a basic check on completeness. A successful run of the test cases does not guarantee accuracy or fulfillment of the requirements. Please do not submit your work if test cases fail. 3. T...
e2adfd5344b2ba0be0c12d9d1aec88072cf4cbd3
mmrraju/Problem-solving-with-python
/44 CheckStrictSuperset.py
219
3.71875
4
def issuppersubset(a, b): return b.issubset(a) and not (a.issubset(b)) a = set(input().split()) n = int(input()) res = True for _ in range(n): b = set(input().split()) res &= issuppersubset(a, b) print(res)
8bf569ca01a65a0bf356b2c4cf1a511539cffd44
mmrraju/Problem-solving-with-python
/17 Time_delta.py
2,596
3.9375
4
from datetime import datetime def time_delta(t1, t2): fmt = '%a %d %b %Y %H:%M:%S %z' t1 = datetime.strptime(t1, fmt) t2 = datetime.strptime(t2, fmt) diff = (t2-t1).total_seconds() return abs(int(diff)) for _ in range(int(input())): print(time_delta(input(), input())) '''Directive M...
e2b73542cc72c4169b1982b2dfb43495175ccc2f
pantagrel/uw_python
/ch6/six.py
1,233
3.921875
4
import math def fibonacci(n): space = ' ' * (4 * n) print space, 'fibonacci', n if not isinstance(n, int): print 'only numbers, frenchman!' elif n < 0: print 'only positive numbers, frenchman!' elif n == 0: print space, 'returning 1' return 0 elif n == 1: print space, 'returning 0' ...
dd5a257450910bb0ac68a5c97b602257808a478e
pantagrel/uw_python
/ch11/eleven.py
3,233
3.640625
4
import random #-------------------------------------------------------------------------------- #ex. 11.1 """ read words in 'words.txt' and store them as keys in a dictionary. values irrelevant. then use 'in' to check whether string is stored in dictionary. """ def crosswordDictionary(file): fin = open(file) d = di...
eb07e26235a7457539d98b971ae9fb25111a1de9
ramyasutraye/python-programming-13
/Hunter level/display an second smallest number in an array.py
217
3.84375
4
store = [] amount = int(input("please enter the amount of numbers you want to sort ")) for a in range(amount): num = int(input("please enter a number ")) store.append(num) b=sorted(store) print (b) print (b[1])
05f196398f34651711a599c08ca72e9cb725a550
ramyasutraye/python-programming-13
/games/RANDOM NUMBER GUESSING.py
689
3.984375
4
print("Are you ready to play?") a=str(input()) if(a=='yes'): print("continue") else: exit() s=0 print("Hi buddy, what is your name?") myname=str(input()) print('hi'+ '_' +myname) guessnumber=3 print("Take a guess and my number is between is 1 and 20") print(myname+'_'+"you have a three chances.ALL the best??") wh...
5aec933b2f54a28c1f05a8e7647058c22fe7989e
ramyasutraye/python-programming-13
/games/stone,,paper and scissor with loop.py
981
3.828125
4
print("ready to play") count1=0 count2=0 a=str(input('yes or no')) if (a=='yes'): print ("continue") else: print("exit") exit() player1=str(input("enter your name:")) player2=str(input("enter your name:")) print("player1 name is:"+player1) print("player2 name is:"+player2) l=['stone','paper','scissor'] s=0 while...
a1b871bee06af93ff0aab4f4f3e2e0107ccffc72
DeveloperAchu/TDS-task-2
/find_opening_hours.py
2,998
4
4
# this function calculates the opening time and closing time in minutes of the day and append that to # the list whose reference is passed def find_opening_hours(day_index, queries, open_at, open_at_meridiem, close_at, close_at_meridiem): # start by initializing that the opening time is at the 0th minute of the day...
a0cad773d1cc09e7e993ceb3c2f07488b805a1dc
demoanddemo/haiyang
/acwing-collect-codes/143.py
1,084
3.5
4
AcWing 143. 最大异或对python3    原题链接    简单 作者:   xanxus1111 ,  2020-05-05 23:35:18 ,  阅读 104 0 def insert(x): global idx p = 0 i = 30 while i >=0: u = x >> i & 1 if not son[p][u]: idx += 1 son[p][u] = idx p = son[p][u] i-=1 def query(x): p ...
d047b8d86c885aec2c8f609baf3e794877d067e4
MrBenz2005/School_Tasks
/Game_of_Life.py
4,513
3.75
4
"""Kostya Derebensky""" from copy import deepcopy class LifeGame: def __init__(self, array: list): self.__array = array self.array = deepcopy(array) self.height = len(array) self.length = len(array[0]) def get_next_generation(self): for i in self.__array: ...
b346ded18a46bb6c1124c25683a9266bbccad59a
liszewskinorbert/portfolio
/opcjewyb.py
1,910
3.640625
4
from tkinter import * class Application(Frame): def __init__(self, master): """Inicjalizacja""" super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(self): """Etykiety z opisem""" Label(self, text = "Wybie...
46ce9db9b2d34ca1f258e1675d61c98cd46ccc78
blmayer/daily-solutions
/9.py
730
4.15625
4
""" This problem was asked by Airbnb. Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative. For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5. Follow-u...
12bf99640c2064f9936dbbe2bbd05995d2cddae3
ktjell/CDC21CloudControlGarbling
/obliviousTransfer.py
2,007
3.515625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 17 10:42:09 2021 @author: kst """ import numpy as np class OT: def __init__(self, bitlen, elg, mod): self.bitlen = bitlen self.elg = elg self.mod = mod def choose(self, inputs): r''' First fase of O...
5fa3893d4383c4aeec7d7b27f369b96c8e429fb7
xiongbob/fizzbuzz
/simpleEliza.py
209
3.765625
4
while True: chat = input("Good day. What is your problem? Enter your response here or Q to quit: ") print(chat) if chat.upper().startswith("Q"): print("You exit to chat!") exit()
709ace886df33731267da3299f8db0b8ea473bdd
rodoufu/btc-rawtx-rest
/select_utxo.py
2,111
3.734375
4
class SelectUtxo(object): """ Generic class for selecting UTXO before creating a transaction. Given a list of transactions and a value, use some criteria to choose the UTXO. """ def select(self, unspent: list, value: int) -> (list, int): raise NotImplementedError("Implement select") class BiggerFirst(SelectUt...
a08f76c3b575c2028714f89ff13495e14cca6b9b
zcrenshaw/Crenshaw_Coding_Examples
/Computer_Vision/hw2/hw2.py
21,510
4.0625
4
import numpy as np from canny import * from sys import maxsize import matplotlib.pyplot as plt from math import pi """ INTEREST POINT OPERATOR (12 Points Implementation + 3 Points Write-up) Implement an interest point operator of your choice. Your operator could be: (A) The Harris corner detector (Szeli...
42b79a0f206829a14e3bfd03bd174c71eddf5a84
Cafemug/gabin
/baekjoon/1003/1003.py3.py
507
3.765625
4
def fibo1(n): def loop(n,first,second): if n==0: return 0 elif n==1: return second elif n>=2: return loop(n-1,second,first+second) return loop(n,0,1) def fibo0(n): def loop(n,first,second): if n==0: return 1 elif n==1: return second elif n>...
23c2340f9db5f22162d94e15a4cfd359fd095176
procendp/Code_Study
/Programmers/Python/LV1/같은 숫자는 싫어.py
763
3.625
4
def solution(arr): new = [] new.append(arr[0]) for i in range(1, int(len(arr))): if arr[i] != arr[i-1]: new.append(arr[i]) else : continue return new print(solution([1,1,3,3,0,1,1])) print(solution([4,4,4,3,3])) # def solution(arr): # for i in range(1, int(l...
aedd0e39ae793388581fd82e787bedb18d5573a4
procendp/Code_Study
/BaekJoon/Python/맞은사람순/24_숫자의합.py
244
3.71875
4
N = input() num = input() num_list = list(num) int_num_list = list(map(int, num_list)) total = sum(int_num_list) print(total) # 리스트 문자열을 숫자로 전환 ['5', '4', '3'] ....> [5, 4, 3] # num_list = list(map(int, num_list))
d2a3461dfafa0023ff9fd835185ce9c106f314c0
procendp/Code_Study
/Programmers/Python/LV2/폰켓몬.py
375
3.765625
4
def solution(nums): answer = 0 nums_setlist = list(set(nums)) # 집합으로 중복 제거 후 다시 리스트화 if len(nums_setlist) > len(nums) // 2: answer = len(nums) // 2 else: answer = len(nums_setlist) return answer print(solution([3,1,2,3])) # 2 print(solution([3,3,3,2,2,4])) # 3 print(solu...
578c7c9968c7955fa1ffc82d5a69f888b1fccf22
procendp/Code_Study
/Programmers/Python/LV1/두 개 뽑아서 더하기.py
614
3.703125
4
def solution(numbers): new = [] for i in range(0, int(len(numbers))): for j in range(1, int(len(numbers)-1)): new.append(int(numbers[i-j]) + int(numbers[i])) new = list(set(new)) new.sort() return new print(solution([2,1,3,4,1])) print(solution([5,0,2,7])) print(so...
2c2ee911e899d0519493ea72061d05cff2af904d
Shelzi99/Guess_the_number2
/Guess number.py
1,293
4.125
4
import random print ('Hello, this is a guessing game. The computer chose a number between 1-20, you need to guess what it is.') def main(): computer = random.randint(1, 20) def raffle(): return (random) raffle() def user_guess(prompt): guess = input(prompt).strip().lower() whi...
e37a0eda95986f0c2a61ae0042e67754216c1b65
SFoskitt/python_extra
/ex_17_more_pali.py
1,090
4.15625
4
# Write a version of a palindrome recognizer that also accepts phrase palindromes such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori", "Rise to v...
05bdea5137ef54a30ee0c50289f8c2b567f2bd9c
wjosephmark/Games
/Black_Jack.py
1,803
3.65625
4
import random dealer_cards = [] player_cards = [] player_total = sum(player_cards) dealer_total = sum(dealer_cards) player_move_array = ['placeholder'] while len(dealer_cards) != 2: dealer_cards.append(random.randint(1, 11)) if len(dealer_cards) == 2: print(" ") print("The visible dealer car...
4963308bdfeae5ecd943d16aafd637f177a5a13a
ntujvang/AirBnB_clone
/tests/test_models/test_state.py
1,398
3.515625
4
#!/usr/bin/python3 ''' This is the 'test_state' module. test_state uses unittest to test the 'models/state' module. All credit for this module goes to Danton Rodriguez (https://github.com/p0516357) ''' import unittest from models.state import State import datetime class TestBaseModel(unittest.TestCase): """Test ...
ab87f9b3049b054578a5d0a5b2426cfbf8b928c1
bill-filler/python-examples
/loops.py
1,297
3.9375
4
import random prices = [2.50, 3.50, 3.25] total = 0 for price in prices: total = total + price #print every character of the word on a new line word = 'Welcome!' for char in word: print(char) average_price = total / len(prices) print("Total=", total) print("Average Price=", average_price) #random int betwe...
160567235a7a92955166acf61efff2e82c2358f6
Nidhogglin/Python
/practice/动态给类和实例绑定方法.py
750
3.640625
4
#!/usr/bin/env python # coding: utf-8 # 方法可以直接定义在class中,但动态绑定允许我们在程序运行的过程中动态给class加上功能,这在静态语言中很难实现。 class Student(object): pass if __name__ == '__main__': s = Student() # 给实例绑定属性,只对该实例生效 s.name = 'lin' # 给实例绑定方法,只对该实例生效 def set_age(self, age): self.age = age from types import M...
e6fcbbbdad128e635dc320a7695ec039f4b68624
Nidhogglin/Python
/practice/代码提升小组/股票利润3_1.3.py
540
3.546875
4
#!usr/bin/env python3 # coding: utf-8 # @time :2020/10/12 15:15 from typing import List import time class Solution: def maxProfit(self, prices: List[int]) -> int: buy_p1, buy_p2 = float('inf'), float('inf') max_p1, max_p2 = 0, 0 for i in prices: buy_p1 = min(i, buy_p1) ...
c921494245030e47807a25447f1122122b003077
Nidhogglin/Python
/practice/力扣练习题/数组/26-删除排序数组中的重复项.py
1,196
4
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 时间:2021/3/4 21:42 __author__ = 'Nidhogg' """ 26. 删除排序数组中的重复项 给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array 著作权归领扣网络所有...
f6891bd58c9df8dad7a5f6782dbbc41b51b73d52
Nidhogglin/Python
/practice/常用内建模块/collections_1.py
2,217
3.984375
4
#!usr/bin/env python3 # coding: utf-8 # @time :2020/9/18 12:51 from collections import namedtuple, deque, defaultdict, OrderedDict, Counter # namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。 # 这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。 # 可以验证创建的Point对象是tuple的一种子类: de...
2e0bec4c3846e5dc0b25fd8e9ddb68fc0e9a4148
Nidhogglin/Python
/study/max.py
414
3.59375
4
# 找出数组中相邻两个数之和最大的一组 def fmax(a): max = a[0] + a[1] index = 0 for i in range(1, len(a) - 1): if (a[i] + a[i+1]) > max: max = a[i] + a[i+1] index = i return index a = [-1, 2, -1, 3, -1, 4, -5, 1, 6, -3] index = fmax(a) print("相加最大值的组合下标为:%d,%d,最大值为%d" % (index, index+1,...
40784e6c08b877cc03e232dea564122f061f2ada
Sharon131/Theory-of-Compilation
/Lab5/Memory.py
1,749
3.96875
4
class Memory: def __init__(self, name, parent=None): # memory name self.vars = dict() self.name = name def has_key(self, name): # variable name if name in self.vars: return True else: return False def get(self, name): # gets from memory c...
0fe36c05b5fe8afea40a946b7ffab2146107b15a
simrankaushik/pythonCodes
/map function.py
245
4
4
# map function is an inbuild function #map(function,iterable) #doesnt require boolean # suppose find out the squares def square(x): return x*x numbers=[1,2,3,4,5] list_of_squares = map(square,numbers) print(list(list_of_squares))
61860fc1c9a36c6d7c1654cd4e4a7bea6897e987
simrankaushik/pythonCodes
/list_comprehension.py
805
4.34375
4
# use to make code small-list comprehension fruits=["banana","apple","orange","mango","kiwi"] print(fruits) newfruits=[] # now printing the names of the fruits which contain "a" in them for x in fruits: if "a" in x: newfruits.append(x) else: print("none") print(newfruits) ...
6915a2372a52e3d5fde5b615d8dd76f5f9b43bd4
simrankaushik/pythonCodes
/practic.py
419
4.125
4
num = int(input("enter the number: ")) print(num) if num % 2 == 0: if num in range(2, 5): print("Not Weird") elif num in range(6, 20): print("Weird") elif num > 20: print("Not Weird") else: print("weird") n = int(input()) if n % 2: print("Weird") elif 2 <= n <...
36c610fd7057be0bf7244b476ac9ef370a5ad51c
twood1/LeetCode
/Medium/LargestValueEachTreeRow.py
696
3.71875
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def largestValues(self, root): treeHash = self.valuesHash(root, 0, {}) maxVals = [] for i in range(0, len(treeHash)): ...
b0f8b8390e7186ce408cd6a10f21ae3b99f6e843
twood1/LeetCode
/Medium/LongestPalindromicSubstring.py
1,699
3.859375
4
# Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000. # # Example 1: # # Input: "babad" # Output: "bab" # Note: "aba" is also a valid answer. # Example 2: # # Input: "cbbd" # Output: "bb" class Solution: def checkPalindrome(self, s, startIdx, endId...
6cae3f26984509fd2200e632f4ec14ee8ab5fdcd
kakouto4eJluk/homework1
/homework3/3_2.py
1,113
3.6875
4
''' Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия, год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы. Реализовать вывод данных о пользователе одной строкой. ''' ''' name = input('Введите имя: ') surname ...
ff6a2186755b03cff2cdafaf6148eca3292d3527
kakouto4eJluk/homework1
/homework8/8_2.py
1,802
3.5625
4
''' Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. Проверьте его работу на данных, вводимых пользователем. При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. ''' class DivisionByNull: def __init__(self, n...
02aa1be7e17e38a8166dab06f499c7f73ef85579
kakouto4eJluk/homework1
/homework2/2_2.py
442
3.65625
4
my_list = list(input("Впишите любые символы: ")) print(my_list) n = 0 if len(my_list) % 2: z = my_list[len(my_list) - 1] my_list.pop(len(my_list) - 1) while n < len(my_list): my_list.insert(n, my_list[n + 1]) my_list.pop(n + 2) n += 2 my_list += z else: while n < len(my_list...