blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
5dc0ca50f55cc6967821f52336deffda5530ad04
airuchen/python_practice
/raise_error.py
444
3.8125
4
import sys def displaySalary(salary): if salary<0: raise ValueError('positive') print('Salary = '+str(salary)) while True: try: Salary = float(input('enter Salary:')) displaySalary(Salary) break except OSError as err: print('OS Error: {0}'.format(err)) except...
feefbfb35b341b204fddcbe7dbd8d31acbc13b89
adpoe/CupAndChaucerSim
/INITIAL_EXPERIMENT/time_advance_mechanisms.py
28,390
3.8125
4
import Queue as q import cupAndChaucArrivs as cc """ Discrete time advance mechanisms for airport simulation project. This class will generate 6 hours worth of passenger arrivals, and store the data in two arrays: - One for commuters passengers - One for international passengers For each passenger, also need to gener...
261a80f5080e6ad40aacc3f4921d7e140d19fedd
imran436/Projects-Portfolio-master
/Tech Academy/python projects/#13.py
555
3.9375
4
import time X = 5 print(X) X = X**5 print(X) if X<10: print("our number X is a small value") elif X<100: print("The number is an average value") else: print("the number holds a big value") counter = 0 for counter in range(0, 100,5): print(counter) time.sleep(.25) counter = 0 while counter < X: p...
70c66c6ddb26d1ddad9409d84c4932e7dfd718af
Sasithorn04/Python
/ตารางหมากฮอส.py
604
3.9375
4
#โปรแกรมจำลองตารางหมากฮอส #ปรับจากสร้างภาพวาด4เหลี่ยมจตุรัส number = int(input("ป้อนขนาด :")) for row in range(1,number+1) : for column in range(1,number+1) : if (column%2 == 0) & (row%2 == 0) : print("o",end='') elif (column%2 != 0) & (row%2 != 0): print("o",end='') ...
ebcd50508c0690db480ba215a31c764c84db3988
harshit-tiwari/Python-Codes
/Simple Calculator/addition.py
689
4.09375
4
import calculate def addFunc(): print("You have chosen Addition") operands = [] number = 0 while True: try: number = int(input("How many numbers do you want to add? : ")) break except ValueError: print("Please enter a number as your input") for i...
e978a7977ddfd0f0e7559618d3aa1f5282f8ab91
chrissowden14/bank
/FileStore.py
1,592
3.90625
4
class FileStore: def __init__(self): # This creates an open list everytime the program is opened self.cusnames = [] self.cusspaswords = [] self.cusbalance = [] # opening the stored file that collects the old data from customer self.namefile = open("cusnamesfile.txt",...
b58ef87371085284143fbb0d28d9251d8d97b01f
Subhashriy/python
/11-07-19/substitute.py
200
3.5
4
import re n=int(input("Enter no. of lines:")) a=[] for i in range(n): a.append(input()) str1=re.sub(r'&&','and',a[i]) str1=re.sub(r'\|\|','or',a[i])
0de46d21ae522160a24e89e11919f60365b32288
Subhashriy/python
/17-07-19/tcpclient.py
752
3.5625
4
import socket def main(): host='127.0.0.1' port=5000 #Creting a socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print("Socket Created.") #connect to the server s.connect((host,port)) print('Connected to server.') #send msg to the server data=input...
07617bf9783632e43ce3e5e585bc5d844e29f8e1
Subhashriy/python
/17-07-19/avg.py
128
3.90625
4
lst=[int(x) for x in input('Enter the list: ').split(' ')] print('The average of the list is : {}'.format((sum(lst)/len(lst))))
1687e6c73055cb78bb5399468addc38065edfc4f
Subhashriy/python
/17-07-19/random.py
199
3.75
4
import random def randomnum(i,n): print(random.randint(i,n+1)) #print(random.randint(1,100)) i=int(input('Enter the start range:')) n=int(input('Enter the end range:')) randomnum(i,n)
70b744b963b558041e7e60fb910eaa3260c619e9
zacharymollenhour/Fitness_Tracker
/test.py
2,323
3.984375
4
import numpy as np import pandas as pd import csv from datetime import date #Get User Name class Person: "This is a persons data class" def __init__(self): self.userData = [] self.name = '' self.age = 0 self.weight = 0 #Greet User for data about the individual def gree...
ce0dada2eadce554808ced1d97e1c8b88e2a9b7e
devsben/Neopets-Multi-Tool
/classes/__init__.py
288
3.5
4
import sys if sys.version_info[0] < 3: """ If a Python version less than 3 is detected prevent the user from running this program. This will be removed once the final tweaking is completed for Python 2. """ raise Exception("Python 3 is required to run this program.")
39c5729b31befc2a988a0b3ac2672454ae99ea9a
krsatyam20/PythonRishabh
/cunstructor.py
1,644
4.625
5
''' Constructors can be of two types. Parameterized/arguments Constructor Non-parameterized/no any arguments Constructor __init__ Constructors:self calling function when we will call class function auto call ''' #create class and define function class aClass: # Constructor with arguments def...
bcde27b2f96aff6d73cf8cb2836416b57c3e0e56
krsatyam20/PythonRishabh
/filehandling.py
1,001
3.734375
4
''' open(mode,path) mode r :read read() => read all file at a time readline() => line by line read readlines() => line by line read, but line convert into list w :write write() a :append open(path,'a') write() ...
5be464d262f21413b369dc140cae381540470ef0
krsatyam20/PythonRishabh
/forloop.py
590
4.09375
4
''' loop : loop is a reserved keyword it`s used for repetaion of any task types of loop 1. For loop 2.while loop ''' for i in range(0,10): print("Rishab %d " %(i)) for i in range(1,21): print(i) #use break keyword print("===========break keyword=================") for i in ran...
fa517e9e021b1d701a23211c569e6fd201bdb42c
gsingh84/Adventure-Game
/Adventure-game.py
10,666
4.25
4
#All functions call at the end of this program import random treasure = ['pieces of gold!', 'bars of silver!', 'Diamonds!', 'bottles of aged Rum!'] bag = ['Provisions'] #yorn function allow user to enter yes or no. def yorn(): yinput = "" while True: yinput = input("Please Enter Yes or No (Y/N): ") ...
34f5750734878b8d0d100a5882e2b4a70fbb13f9
nicklip/Google_Python_Developers_Course
/copyspecial.py
4,485
3.828125
4
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re import os import shutil import commands """Copy Special exercise The c...
5bd5df1910a6c6765dfeff536eba03ca4878dc6e
TiwariSimona/Hacktoberfest-2021
/g-animesh02/cartoon3.py
2,243
4.0625
4
import cv2 class Cartoonizer: """Cartoonizer effect A class that applies a cartoon effect to an image. The class uses a bilateral filter and adaptive thresholding to create a cartoon effect. """ def __init__(self): pass def render(self, img_rgb): img_rgb = cv2...
5152927f8f259d1d78645fdec94330753225833a
TiwariSimona/Hacktoberfest-2021
/Aryan810/new_search_algorithm.py
1,268
3.71875
4
from threading import Thread import time class SearchAlgorithm1: def __init__(self, list_data: list, element): self.element = element self.list = list_data self.searching = True self.index = None def search(self): Thread(self.forward()) self.reverse() ...
f2744631653064a83857180583c831b187a8f53c
TiwariSimona/Hacktoberfest-2021
/ajaydhoble/euler_1.py
209
4.125
4
# List for storing multiplies multiplies = [] for i in range(10): if i % 3 == 0 or i % 5 == 0: multiplies.append(i) print("The sum of all the multiples of 3 or 5 below 1000 is", sum(multiplies))
bbfe214cd8be2137032f9f2fa056302865a9ada2
TiwariSimona/Hacktoberfest-2021
/akashrajput25/Some_py_prog/count_alphabet.py
178
3.671875
4
name=input("Enter your name\n") x=len(name) i=0 temp="" for i in range(x) : if name[i] not in temp: temp+=name[i] print(f"{name[i]}:{name.count(name[i])}")
16ad6fbbb5ab3f9a0e638a1d8fd7c4469d349c11
TiwariSimona/Hacktoberfest-2021
/parisheelan/bmi.py
957
4.15625
4
while True: print("1. Metric") print("2. Imperial") print("3. Exit") x=int(input("Enter Choice (1/2/3): ")) if x==1: h=float(input("Enter height(m) : ")) w=float(input("Enter weight(kg) : ")) bmi=w/h**2 print("BMI= ",bmi) if bmi<=18.5: print("Under...
c5a68da4e7ffdc1ddc86d247e3092c5eb7d09699
TiwariSimona/Hacktoberfest-2021
/CharalambosIoannou/doubly_linked_list_helper.py
2,632
4
4
class DListNode: """ A node in a doubly-linked list. """ def __init__(self, data=None, prev=None, next=None): self.data = data self.prev = prev self.next = next def __repr__(self): return repr(self.data) class DoublyLinkedList: def __init__(self): """ ...
1c7ecdea2b8d027f39b67355f76a7b6e9c7fce47
SiyandzaD/analysehackathon
/tests/test.py
494
3.875
4
from analysehackathon.recursion import sum_array from analysehackathon.recursion import fibonacci def test_sum_array(): """ make sure sum_aray works correctly """ assert sum_array([1,2,3]) == 6, 'incorrect' print(sum_array([1,2,3])) assert sum_array([1,2,3,4]) == 10, 'incorrect' ...
932042d87adfba2bdb8d437b2c20d98d2afd7c22
VinayagamD/PythonBatch3
/hello.py
74
3.5
4
a = 10 b = 20 sum = a +b print(sum) print('Hello to python programming')
b6d05ea933a068a2a1716aee977af795764eeaa7
quirosnv/PROYECTO
/Proyecto Buscador en proceso/Buscador.py
5,085
3.890625
4
data = int(input("ingrese 1 si quiere buscar por cantante, 2 por cancion, 3 por album, 4 por año, -1 SALIR: ")) cantante = ['KALEO', 'kaleo', 'Coldplay', 'COLDPLAY', 'The Beatles', 'beatles'] contador = 0 while data != -1: if data == 1: print("Eligio buscar por cantante:") cant= input("Ingre...
169e431b852089fcda8a72114582cba0f847afbe
whyalwaysmeee/Machine-Learning-Sklearn-Linear-Model
/Linear Model(Least Square Mothod).py
1,274
4.03125
4
import matplotlib.pyplot as plt from sklearn import datasets, linear_model import numpy as np from sklearn.metrics import mean_squared_error, r2_score # Load the diabetes dataset price = datasets.load_boston() # Use only one feature price_x = price.data[:,np.newaxis,5] # Split the data into training/testi...
08947ee21f916756c6edf64e0f1d1ad5730b59bd
LiangChen204/pythonApi_Test
/runoob/baseException.py
1,868
3.921875
4
#!//usr/local/bin python # -*- coding:utf-8 -*- # 走try try: fh = open("testfile", "w") fh.write("这是一个测试文件,用于测试异常!") except IOError: print("Error: 没有找到文件或读取文件失败") else: print("内容写入文件成功") fh.close() # 捕获异常 try: fh = open("testfile", "r") fh.write("这是一个测试文件,用于测试异常!") except IOError: print...
5f285c43fbeb0489a57c0c703201abfb2df3a575
andfanilo/streamlit-sandbox
/archives/app_styling.py
567
3.734375
4
import pandas as pd import streamlit as st # https://stackoverflow.com/questions/43596579/how-to-use-python-pandas-stylers-for-coloring-an-entire-row-based-on-a-given-col df = pd.read_csv("data/titanic.csv") def highlight_survived(s): return ['background-color: green']*len(s) if s.Survived else ['background-col...
00eb68cef452b9026f89936170f6c21e7ef09e2c
TeenaThmz/List
/list2.py
64
3.5
4
list2=[12,14,-95,3] list=[i for i in list2 if i>=0] print(list)
18785e22dbae3eed4affb39e74eaf9aaffadf949
kooose38/pytools_table
/xai/eli5.py
1,384
3.578125
4
from typing import Any, Dict, Union, Tuple import eli5 from eli5.sklearn import PermutationImportance import numpy as np import pandas as pd class VizPermitaionImportance: def __doc__(self): """ package: eli5 (pip install eli5) support: sckit-learn xgboost lightboost catboost lighting purpose: Vi...
c6ea76ace41ca74098a6562ee75c1e6216cb6fe2
plukis/merge_sort
/controllers/merge_sort.py
1,177
3.84375
4
# -*- coding: utf-8 -*- class MergeSort: a_list = [] def _merge_work(self, alist): print("delimito ", alist) if len(alist) > 1: mid = len(alist) // 2 lefthalf = alist[:mid] righthalf = alist[mid:] self._merge_work(lefthalf) self._m...
42a76e11702d791ddbff3b132710144b3d684323
qqinxl2015/leetcode
/112. Path Sum.py
1,036
3.859375
4
#https://leetcode.com/problems/path-sum/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int...
91ac4bcae6d6e1ba52e2145bdc158800e31d5d6e
qqinxl2015/leetcode
/009. Palindrome Number.py
470
3.796875
4
#https://leetcode.com/problems/palindrome-number/ class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x ==0: return True if x < 0: return False if int(x%10) == 0 and x !=0: return False ...
0e5abd4e1435664f4b626bc96a4d57fd2b5f2374
susanpinch/Read-and-Process-Data-Python
/pinchiaroli_susan_assign9_fileioio.py
1,952
3.96875
4
""" file_io_nested.py Write data from a set of nested lists to a file, then read it back in. By: Susan Pinchiaroli Date: 28 Nov 2018 """ data = []#empty list # This is our data data.append(['Susan','Davis',23,7])#append data data.append(['Harold','Humperdink',76,9]) data.append(['Lysistrata','Jones',40,12]) data.appe...
0211584a0d5087701ee07b79328d4eb6c101e962
pintugorai/python_programming
/Basic/type_conversion.py
438
4.1875
4
''' Type Conversion: int(x [,base]) Converts x to an integer. base specifies the base if x is a string. str(x) Converts object x to a string representation. eval(str) Evaluates a string and returns an object. tuple(s) Converts s to a tuple. list(s) Converts s to a list. set(s) Converts s to a set. dict(d) Creates...
ac7016757e19991066147e75b923b1ef734beb6d
zags4life/tableformatters
/tableformatters/tabledataprovider.py
776
3.75
4
# table_formatters/data_provider.py from abc import ABC, abstractproperty class TableFormatterDataProvider(ABC): '''An ABC that defines the interface for objects to display by a table formatter. Any object displayed by a TableFormatters must implement this ABC. Classes that implement this ABC c...
22c30808220f095b21eca67c444dc2b46b4026b0
gmayock/kaggle_titanic_competition
/gs-titanic-7-final-submission-code.py
11,102
3.515625
4
# # Load data # Ignore warnings to clean up output after all the code was written import warnings warnings.filterwarnings("ignore") import numpy as np import pandas as pd import os print(os.listdir("../input")) ['train.csv', 'gender_submission.csv', 'test.csv'] # Step 1 is to import both data sets training...
f172ed025705f196ebe0c394595dee382a415ccf
jaaaaaaaaack/zalgo
/zalgo.py
1,428
3.96875
4
# zalgo.py # Jack Beal, June 2020 # A small module to give any text a flavor of ancient doom from random import random def validCharacter(char, stoplist): """ Helps to prevent unwanted manipulation of certain characters.""" if char in stoplist: return False else: return True def uniform...
cf37344075ac3ebcd091fcfe24de0444742a01be
elliotgreenlee/advent-of-code-2019
/day10/day10_puzzle1.py
2,365
3.734375
4
import math def read_puzzle_file(filename): with open(filename, 'r') as f: points = set() for y, line in enumerate(f): for x, point in enumerate(line): if point is '#': points.add((x, y)) return points def n...
5976699fa85e8eb7237467f8732bdca6df5d350d
jasoncwells/Test_2
/scraper.py
230
3.578125
4
myvar = 'What is happening today' myage = 46 mylist = ['how','now','brown','cow'] mynumlist = [1,2,3,4,5] print myvar print myage print mylist listlength = len(mylist) print listlength stringlength = len(myvar) print stringlength
dd793f5d7f0d88d1a6446c8ce2025904144c2136
cybera/data-science-for-entrepreneurs-workshops
/helpers/color.py
820
3.640625
4
def hex2rgb(color): return tuple(int(color.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4)) # Decimal number to HEX str def dec2hex(n): n = int(n) if (n > 16): return str(hex(n).split('x')[-1]) else: return "0" + str(hex(n).split('x')[-1]) # Gradient starting at color "start" to color "stop...
ca8162f61acd25fc40f57615225c78c2d1ad0623
sambapython/batch53
/modules/file1.py
199
3.546875
4
print("name:",__name__) a=100 b=200 c=a+b d=a-b def fun(): print("this is fun in file1") if __name__=="__main__": def fun1(): print("this is fun1") print("this is file1") fun() print(a,b,c,d)
38da743b5276b4924cc7e40aa237daef479aaed8
sambapython/batch53
/app.py
89
3.515625
4
a=raw_input("Enter a value:") b=raw_input("Enter b value:") a=int(a) b=int(b) print (a+b)
b483de5c6c42f4c9234be3dacd50c8828437b260
aishraj/slow-learner
/python/pythonchallenge/001.py
614
3.53125
4
import string import collections def decrypt(cyphertext): values = '' keys = '' for i in range(ord('a'),ord('z')+1): keys += chr(i) j = i - ord('a') values += chr(ord('a') + (j + 2) % 26) transtable = string.maketrans(keys,values) return string.translate(cyphertext,transta...
cdb57be6cb1e664d937ecc44efcd00095bdb7407
azbrainiac/PyStudy
/third.py
702
3.953125
4
for item in [1, 3, 7, 4, "qwerty", [1, 2, 4, 6]]: print(item) for item in range(5): print(item ** 2) wordlist = ["hello", "ass", "new", "year"] letterlist = [] for aword in wordlist: for aletter in aword: if aletter not in letterlist: letterlist.append(aletter) print(letterlist) sqlist = [] for x in range(4,...
ad94bc21b8b6a213a11e455e666325fdcf95d890
patpalmerston/Algorithms-1
/making_change/making_change.py
2,323
4.0625
4
#!/usr/bin/python import sys def making_change(amount, denominations=[1, 5, 10, 25, 50]): # base case if amount <= 2: return 1 # starting a cache equal to the size of the amount, plus an initial default of 1 for index of zero cache = [1] + [0] * amount # loop through the coins in our li...
5f89f65fa211fff9288edd96e534a90baaca6919
hklgit/PythonStudy
/pythonCodes/com/coocaa/study/类/Student.py
885
3.9375
4
class Student(object): # 把一些我们认为必须绑定的属性强制填写进去。 # 通过定义一个特殊的__init__方法,在创建实例的时候,就把name,score等属性绑上去: # 特殊方法“__init__”前后分别有两个下划线!!! # 注意到__init__方法的第一个参数永远是self,表示创建的实例本身,因此,在__init__方法内部,就可以把各种属性绑定到self,因为self就指向创建的实例本身。 # 这个跟构造器很类似 def __init__(self, name, age): self.name = name s...
becc6a966f455b1d32d7633c9f7cfb53e110b033
kelvinng2017/chat1
/test2.py
225
3.890625
4
while True: print("請輸入密碼:", end='') password = input() if int(password) == 1234567: print("歡迎光臨!敬請指教") break else: print("密碼錯誤!請在重新輸入")
c538c8864abefaab9f3e97af43283c2bc0efc63f
randeeppr/fun
/desired_days.py
1,188
4.0625
4
#!/usr/bin/python # # This program prints the desired day(s) in between start date and end date # import datetime,sys,getopts def getDesiredDay(start_date,end_date,desired_day): v1 = value_of_start_day = weekdays[start_date.strftime("%a")] v2 = value_of_desired_day = weekdays[desired_day] #print(v1) #print(v2...
0d261b64fc0fee1629ebb3e24483ea4ecd89ad07
Jav10/Matplotlib-Plotting
/UNO/backToBackBarCharts.py
488
3.59375
4
#Matplotlib Plotting #Autor: Javier Arturo Hernández Sosa #Fecha: 30/Sep/2017 #Descripcion: Ejecicios Matplotlib Plotting - Alexandre Devert - (18) #Gráficas de barras espalda con espalda import numpy as np import matplotlib.pyplot as plt women_pop=np.array([5., 30., 45., 22.]) men_pop=np.array([5., 25., 50...
1e618d71d615ae0f419c6d78f9684f028d8f4aa6
jip174/cs362--Software-Eng-2
/week4/test/teststring_testme.py
480
3.765625
4
import testme from unittest import TestCase import string class teststring(TestCase): def test_input_string(self): ts = testme.inputString() count = 0 for x in ts: if x.isalpha() == True or x == '\0': count += 1 print(x) el...
b74c84a5554423d4fcb488945748ebbe64bdd716
jip174/cs362--Software-Eng-2
/week4/test/tester_testme.py
864
3.8125
4
import testme from unittest import TestCase import string class testchar(TestCase): def test_input_char(self): tc = testme.inputChar() letters = string.ascii_letters if (tc.isalpha() == True): #print(tc) self.assertTrue(tc.isalpha() == True) else...
4891587a4606af3b4d6e284ac033185117abbf14
peluche/mooc_algo2
/graphs/dfs_topological_search.py
1,058
3.875
4
#!/usr/bin/env python3 explored = {} current_label = 0 def is_explored(vertex): return explored.get(vertex) != None def explore(vertex): explored[vertex] = True def tag(vertex): global current_label explored[vertex] = current_label current_label -= 1 def dfs(graph, vertex): explore(vertex) ...
d902702bc0e0c3168d745fdf7dfda52fbff1c3d0
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 3a week/Tarefa de programação/Exercícios 2 - FizzBuzz parcial, parte 1.py
100
4.1875
4
num = int(input("Digite um número inteiro: ")) if num % 3 == 0: print ("Fizz") else: print (num)
29781302370b185924aca0e0384ab49f4af4764c
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 7a week/Tarefa de programação Lista de exercícios - 6/Exercício 2 - Retângulos 2.py
456
4
4
larg = int(input("Digite o número da largura do retângulo: ")) alt = int(input("Digite o número da altura do retângulo: ")) x=larg y=alt cont=larg while y > 0: while x > 0 and x <= larg: if y==1 or y==alt: print ("#", end="") else: if x==1 or x==cont: print ...
1d326577cedbfe93c61026649efd049a720ded66
Jeniffersc/Curso-Introducao-a-Ciencia-da-Computacao-com-Python-Parte-1
/Programas da 3a week/Praticar tarefa de programação Exercícios adicionais (opcionais)/Exercício 1 - Distância entre dois pontos.py
277
3.828125
4
import math x1 = int(input("Digite o primeiro x: ")) y1 = int(input("Digite o primeiro y: ")) x2 = int(input("Digite o segundo x: ")) y2 = int(input("Digite o segundo y: ")) dis = math.sqrt ((x1 - x2)**2 + (y1 - y2)**2) if dis > 10: print("longe") else: print ("perto")
2c6eb6b2fbcc6a1cd440d3c0fff85fdb58e0d72f
maimoonmaimu/codeketa
/set1-5.py
104
3.546875
4
m,a,i=input().split() if(m>a): if(m>i): print(m) elif(a>i): print(a) else: print(i)
91cbaa9c8b92230b76a14a687875b71358fe260f
lx36301766/AtlanLeetCode
/src/pl/atlantischi/leetcode/medium/Medium486.py
2,964
3.78125
4
""" 给定一个表示分数的非负整数数组。 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,……。 每次一个玩家只能拿取一个分数,分数被拿取之后不再可取。直到没有剩余分数可取时游戏结束。最终获得分数总和最多的玩家获胜。 给定一个表示分数的数组,预测玩家1是否会成为赢家。你可以假设每个玩家的玩法都会使他的分数最大化。 示例 1: 输入: [1, 5, 2] 输出: False 解释: 一开始,玩家1可以从1和2中进行选择。 如果他选择2(或者1),那么玩家2可以从1(或者2)和5中进行选择。如果玩家2选择了5,那么玩家1则...
0b241bfd9a912c87ef304cb43ace9ffb90cce82c
cyro809/trabalho-tesi
/sentimusic/distance_utils.py
1,284
4
4
#! /usr/bin/env python # -*- coding: utf-8 -*- import math # --------------------------------------------------------------------------- # Função calculate_distance(): Calcula a distancia euclidiana entre dois pontos # - vec1: Vetor 1 # - vec2: Vetor 2 # - num: Número de dimensões espaciais # ------------------------...
7faefdd7192a19669f3b7a0e73e08b2b769ed15c
chulhee23/today_ps
/hanbit/dfs_bfs/ice_frame.py
810
3.640625
4
# 얼음 틀 모양 주어졌을 때 # 생성되는 최대 아이스크림 수 # 2차원 배열 # 1은 막힘 -> 방문. # 0은 열림 -> 아직 방문X. # 0 인접한 0들 묶음 갯수를 파악 def dfs(x, y): # 범위 벗어나면 종료 if x <= -1 or x >= n or \ y <= -1 or y >= m: return False # 방문 전 if graph[x][y] == 0: # 방문 처리 graph[x][y] = 1 # 상하좌우 재귀 호출 ...
3b05df07dcddc639466ba683231cfeff56ba44d8
chulhee23/today_ps
/data_structure/stack/stack.py
547
3.921875
4
class Stack: def __init__(self): self.top = [] def __len__(self): return len(self.top) def __str__(self): return str(self.top[::1]) def push(self, item): self.top.append(item) def pop(self): if not self.isEmpty(): return self.top.pop(-1...
101eea3d60903038cf55472c0ef04b5591e0190e
chulhee23/today_ps
/BOJ/15000-19999/17413.py
1,793
3.515625
4
from collections import deque import sys word = list(sys.stdin.readline().rstrip()) i = 0 start = 0 while i < len(word): if word[i] == "<": # 열린 괄호를 만나면 i += 1 while word[i] != ">": # 닫힌 괄호를 만날 때 까지 i += 1 i += 1 # 닫힌 괄호를 만난 후 인덱스를 하나 증가시킨다 elif wor...
3597f00172708154780a6e83227a7930e034d166
csu100/LeetCode
/python/leetcoding/LeetCode_225.py
1,792
4.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 10:37 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-stack-using-queues/ 使用队列实现栈的下列操作: push(x) -- 元素 x 入栈 pop() -- 移除栈顶元素 top() -- 获取栈顶元素 ...
0efc9e2b00e3c6ad7251b21c0dbdda5fe5a748ff
csu100/LeetCode
/python/leetcoding/LeetCode_206.py
994
3.984375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/24 14:42 # @Author : Zheng guoliang # @Site : # @File : LeetCode_206.py # @Software: PyCharm """ 1.需求功能: https://leetcode.com/problems/reverse-linked-list/description/ 2.实现过程: """ from leetcoding.ListNode import ListNode class Solution: ...
0768a12697cd31a72c3d61ecfa4eda9a1aa0751e
csu100/LeetCode
/python/leetcoding/LeetCode_232.py
1,528
4.46875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/1/31 17:28 # @Author : Zheng guoliang # @Version : 1.0 # @File : {NAME}.py # @Software: PyCharm """ 1.需求功能: https://leetcode-cn.com/problems/implement-queue-using-stacks/submissions/ 使用栈实现队列的下列操作: push(x) -- 将一个元素放入队列的尾部。 pop() -- 从队列首部移除元素。 ...
0341229309f1cf0e9add85b69c248e2f13e9f819
ZhouYzzz/TF-CT-ResCNN
/test/test_decorator.py
328
3.734375
4
def print_args(func): def wrapped_func(*args, **kwargs): print(func.__name__, func.__doc__) for a in args: print(a) for k, v in kwargs: print(k, v) return func(*args, **kwargs) return wrapped_func @print_args def add(x: int, y: int): """:Add two integers""" return x + y print(add...
71a23a3ac6f35438be6d943dad386d2f33c01c84
DenisoDias/python-password-generator
/password_gen.py
1,181
3.734375
4
from random import choice import argparse import string arg = argparse.ArgumentParser(add_help=True) arg.add_argument('-s', '--size', default=20, nargs="?", type=int, help='Parameter to set size of password you will generate') arg.add_argument('-q', '--quantity', default=10, nargs="?", type=int, help="Parameter to set...
ef0de30520dcecfae1031318a469f4202c02091c
jeanjoubert10/Atwood-machine
/atwood machine1.py
3,357
3.5
4
# Simple atwood machine in python on osX import turtle from math import * import time win = turtle.Screen() win.bgcolor('white') win.setup(500,900) win.tracer(0) win.title("Atwood machine simulation") discA = turtle.Turtle() discA.shape('circle') discA.color('red') discA.shapesize(3,3) discA.up() discA.goto(0,30...
708e40f6392f05d6e0b04e32c600328e052d153e
IracemaLopes/Data_Visualiazation_with_Matplotlib
/annotating_a_plot_of_time_series_data.py
444
3.984375
4
import pandas as pd import matplotlib.pyplot as plt fig, ax = plt.subplots() # Read the data from file using read_csv climate_change = pd.read_csv("climate_change.csv", parse_dates=["date"], index_col=["date"]) # Plot the relative temperature data ax.plot(climate_change.index, climate_change["relative_temp"]) # Annot...
995c55f01fcece72677e88b3518bcce98e8f4522
yassir-23/Algebre-application
/Systemes.py
1,765
3.703125
4
from os import * from Fonctions import * def Systemes(): while True: system('cls') print(" #-----------------------------# Menu #-----------------------------#") print(" 1 ==> Système de n équations et n inconnus.") print(" 0 ==> Quitter.") print(" #----------------...
3a9a3220f024406f7120421cb00e17427810bb09
devdw98/TIL
/Language/Python/파이썬으로 배우는 알고리즘 트레이딩/lesson05.py
913
3.546875
4
#5-1 def myaverage(a,b): return (a+b)/2 #5-2 def get_max_min(data_list): return (max(data_list), min(data_list)) #5-3 def get_txt_list(path): import os org_list = os.listdir(path) ret_list = [] for x in org_list: if x.endswith("txt"): ret_list.append(x) return ret_list #5-4 def BMI(kg,...
6e42680389e94466abc769aec4e8eba49d9a853d
hexavi42/eye-see-u
/proofOfConcept/grayscale.py
782
3.546875
4
import argparse from os import path from PIL import Image def main(): parser = argparse.ArgumentParser(description='Grayscale an Image') parser.add_argument('-p', '--path', type=str, default=None, help='filepath of image file to be analyzed') parser.add_argument('-o', '--outFile', type=str, default=None, h...
0be7bc8211b56c825d410b76816af2d89eb19f6d
Alb4tr02/holbertonschool-higher_level_programming
/0x03-python-data_structures/10-divisible_by_2.py
318
3.984375
4
#!/usr/bin/python3 def divisible_by_2(my_list=[]): new_list = [] if my_list is None or len(my_list) == 0: return (None) else: for i in my_list: if (i % 2) == 0: new_list.append(True) else: new_list.append(False) return (new_list)
c537a01c9337f80af03e9209217d1a7dd25fbad9
Alb4tr02/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/0-square_matrix_simple.py
221
3.625
4
#!/usr/bin/python3 def square_matrix_simple(matrix=[]): if matrix is None: return newm = matrix.copy() for i in range(0, len(newm)): newm[i] = list(map(lambda x: x*x, newm[i])) return newm
2003141f132187e8281b81d69561fe78131a948a
Alb4tr02/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/6-print_sorted_dictionary.py
216
4.03125
4
#!/usr/bin/python3 def print_sorted_dictionary(a_dictionary): if a_dictionary is None: return list = (sorted(a_dictionary.items())) for i in list: print("{}{} {}".format(i[0], ":", i[1]))
cc43bddce55b547f89fb76b6636a278204121d0f
Alb4tr02/holbertonschool-higher_level_programming
/0x01-python-if_else_loops_functions/8-uppercase.py
194
4.09375
4
#!/usr/bin/python3 def uppercase(str): for a in str: c = ord(a) if c >= ord('a') and c <= ord('z'): c -= 32 print("{:c}".format(c), end="") print("")
74c99c3b0c9b9bd9adc3d84ec71d466169be8a1f
PuchatekwSzortach/convolutional_network
/examples/mnist.py
2,112
3.546875
4
""" A simple MNIST network with two hidden layers """ import tqdm import numpy as np import sklearn.utils import sklearn.datasets import sklearn.preprocessing import net.layers import net.models def main(): print("Loading data...") mnist = sklearn.datasets.fetch_mldata('MNIST original') X_train, y_tra...
9003c2fc01c18745533b9995186de30fc99f4fc4
KulaevaNazima/files
/files4.py
1,348
3.859375
4
#Cоздайте текстовый файл python.txt и запишите в него текст #1 из Classroom: #Затем, считайте его. Пробежитесь по всем его словам, и если слово содержит #букву “t” или “T”, то запишите его в список t_words = [ ]. После окончания списка, #выведите на экран все полученные слова. Подсказка: используйте for. python = open ...
5cb813598d9e52af2c1f514da781de4d22285190
singediguess/my-python-note
/using_str/using_str.py
495
4.0625
4
str1 = 'I am {}, I love {}' str2 = str1.format('k1vin', 'coding') print (str2) print('---') #using index str3 = '{0:10} : {1:3d}' table = {'c++':16, 'html':15, 'python':17} for name, nmb in table.items(): print (str3.format(name, nmb)) print('---') #using '%' import math print ('pi = %6.4f' % math.pi) print('---')...
d57b48fe6ebac8c1770886f836ef17f3cadf16c7
alma-frankenstein/Grad-school-assignments
/montyHall.py
1,697
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #to illustrate that switching, counterintuitively, increases the odds of winning. #contestant CHOICES are automated to allow for a large number of test runs, but could be #changed to get user input import random DOORS = ['A', 'B', 'C'] CHOICES = ["stay", "switch"] de...
050b97bea9846acccb6ec7abafbab7505c6fd462
ColinSidberry/Learning-to-Code
/KS2.py
1,208
3.6875
4
import csv with open('Santee-Surrounding-Cities.csv','w',newline = '') as f: thewriter = csv.writer(f) file = input('Please enter raw.csv: ') opened = open(file) file2 = input('Please enter new.txt: ') opened2 = open(file2) s = str() old = ['san diego','santee','del mar','carlsbad','san marcos','encinitas','pen...
141011f37de069a56eb23f0aa5cf9b1c18fa6c72
JMR96/Ciclo2LP
/PalavraContraria.py
263
4.0625
4
# -*- coding: latin1 -*- def fraseInvert(frase): invert = frase.split() for i in xrange(len(invert)): invert[i] = invert[i][::-1] return ' '.join(invert) frase = 'Estou no ciclo 2 fazendo Linguagem de Programacao' print fraseInvert(frase)
b36cc808695e667d53ed0d274ee5faec1dd139ba
skluzada/school_projects
/Image Editor/image_editor/image_editor.py
8,324
3.84375
4
import numpy as np from PIL import Image MIRROR_VERTICAL = 0 MIRROR_HORIZONTAL = 1 # coefficients by which the corresponding channels are multiplied when converting image from rgb to gray TO_GRAY_COEFFICIENTS = { 'RED': 0.2989, 'GREEN': 0.5870, 'BLUE': 0.1140 } class ImageEditor: """ A class use...
31188f137dc8be0688b2a3042f04226bca65e202
mamorales10/Python-Guide-for-Beginners
/SortingAlgorithms/merge_sort.py
674
4.03125
4
def mergeSort(listToSort): if(len(listToSort) > 1): mid = len(listToSort)//2 lower = listToSort[:mid] upper = listToSort[mid:] mergeSort(lower) mergeSort(upper) i = 0 j = 0 k = 0 while(i < len(lower) and j < len(upper)): if(lower[i] < upper[j]): listToSort[k] = lower[i] i = i + 1 els...
f8096a50065547373b754f7c3c3ea43367434d88
psykid/computational-physics
/romberg.py
664
3.5
4
import math import numpy as np fun="1.0/x" lb, ub=1, 2 def f(x): return eval(fun) def T(m,k): if k==0: return T_0(m) return def T_0(m): N=2**m step=(ub-lb)*1.0/N i, summ=lb+step,0 while i<ub: summ+=f(i) i+=step summ+=0.5*(f(lb)+f(ub)) return summ*step #0.69314718055994529 def main(): #_n=int(raw...
ffdba064734aa4cb7193f7121fa5c28cd06a32cc
Shio3001/koneta
/99.py
619
3.6875
4
import random print("九九計算して") def loop(): i1 = random.randint(0, 9) i2 = random.randint(0, 9) m = random.randint(0, 2) correct = 0 if m == 0: correct = i1 * i2 print("{0} x {1}".format(i1, i2)) if m == 1: correct = i1 + i2 print("{0} + {1}".format(i1, i2)) ...
8b8644a5fbc3a44baff3a5ad1156c5a644b60f56
drod1392/IntroProgramming
/Lesson1/exercise1_Strings.py
1,026
4.53125
5
## exercise1_Strings.py - Using Strings # # In this exercise we will be working with strings # 1) We will be reading input from the console (similar to example2_ReadConsole.py) # 2) We will concatenate our input strings # 3) We will convert them to upper and lowercase strings # 4) Print just the last name from the "nam...
df9cea82395dfc4c540ffe7623a0120d2483ea9e
imyogeshgaur/important_concepts
/Python/Exercise/ex4.py
377
4.125
4
def divideNumber(a,b): try: a=int(a) b=int(b) if a > b: print(a/b) else: print(b/a) except ZeroDivisionError: print("Infinite") except ValueError: print("Please Enter an Integer to continue !!!") num1 = input('Enter first number') num2...
abcb2f242d5b48cae08848eba99bec9249cd7f98
servemoseslake/serve
/sml/sml/serve/utils.py
873
3.5
4
from datetime import datetime, date def date_from_string(value, format='%Y-%m-%d'): if type(value) == date: return value return datetime.strptime(value, format).date() def datetime_from_string(value, format='%Y-%m-%dT%H:%M'): alternate_formats = ( '%Y-%m-%dT%H:%M:%S', ) all_fo...
c9586c078a3bd35ebab6a145de6b6a0a934f501f
zmadil/Random_snippets_2019
/bubblesort.py
242
4.0625
4
list1=[5,3,7,22,5,9,1] def bubblesort(list1): for i in range(len(list1)): for j in range(i+1,len(list1)): if list1[j] < list1[i]: temp=list1[j] list1[j]=list1[i] list1[i]=temp return list1 bubblesort(list1) print(list1)
4b8332d14517a5e339ea61207ed710d8e7cd7e78
zmadil/Random_snippets_2019
/fibonacci.py
214
3.8125
4
#0,1,1,2,3,5,8,13,21 print('Please enter how many numbers you want ') user=int(input()) print('----------------------------') a=0 b=1 print(a) print(b) for i in range(2,user): c=a+b a=b b=c print(c)
0953e7600c11fb8059e602fb948107fbc801065b
makstar1/low
/pro4.py
329
3.8125
4
from random import randint as ri a = int(input( "введите длину списка: ")) b = int(input("введите максимальное значение элемента списка: ")) def listFunc (x,y): list = [] for i in range(x): list.append(ri(0,y+1)) return list print(listFunc(a,b))
e822856efebb234650fa9d22e4e233757ec01acb
liweiwei1419/Algorithms-Learning-Python
/binary-search/binary-search-4.py
549
3.890625
4
# 查找最后一个小于等于给定值的元素 def binary_search_4(nums, target): size = len(nums) # 注意,right 向左边减了 1 位,因为 target 可能比 nums[0] 还要小 left = -1 right = size - 1 while left < right: mid = left + (right - left + 1) // 2 if nums[mid] <= target: left = mid else: right = m...
8c83a11c95c69da1e3d09e44130af2457d4bf91b
liweiwei1419/Algorithms-Learning-Python
/unweighted-graph/DenseGraph.py
1,211
3.578125
4
from iterator import DenseGraphIterator class DenseGraph: def __init__(self, n, directed): assert n > 0 # 结点数 self.n = n # 边数 self.m = 0 # 是否是有向图 self.directed = directed # 图的具体数据 self.g = [[False for _ in range(n)] for _ in range(n)] de...
7a6ce3a681aeabe5b7758972546666d6be3ef641
2KNG/old_freshman
/python_source/수업/문제1.py
518
4
4
def calc(a, op, b): x = a y = b if op == "+": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a+b)) elif op == "-": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a-b)) elif op == "*": print("{:.2f}{}{:.2f}={:.2f}".format(a, op, b, a*b)) elif op == "/": print("{:.2...
f092c8017f618eb44d2c6c5a48248909b067eb68
2KNG/old_freshman
/python_source/수업/엑셀입출력.py
835
3.71875
4
import csv # in_file = open("excel_data.csv", "r") # data = csv.reader(in_file) # for i in data : # print(i) # in_file.close() # with open("aa/excel_data2.csv", "w", encoding="utf-8-sig", newline="") as out_file: # newlinee 을 안박으면 개손해 # data = csv.writer(out_file, delimiter=",") # data.writerow([i for i in...
6885e4e26929aae57d69b5db41ca2971aacbf0fd
2KNG/old_freshman
/python_source/수업/문제3.py
198
3.828125
4
def plus(f, t): # from 으로 함수를 작성할 수 없어 f, t로 변경 sum = 0 for i in range(f, t+1): sum += i return sum print(plus(1,10)) print(plus(1, 3) + plus(5, 7))
094c36fab0d52ecac6cdee01896f54c1ec414c10
2KNG/old_freshman
/python_source/딥러닝/문제 210630.py
1,320
3.5
4
import random i = random.randint(1,15) print(i) while x != i : x = int(input('줘요')) k = x if x == i : print('정답띠') elif i < 7 : if 7 < x: print("i는 7보다 작다") elif x < i < 7 : print("i는 7보다 작고 {}보다 커욤".format(x)) elif i < x < 7 : print(...
f2e6ca8c1e4b7f263d07c18e437f7b376498d4c3
jky007/py_learn
/test3-12.py
274
3.78125
4
a = 'hello,world' # hello,world b = 1.414 # 1.414 c = (1 != 2) # True d = (True and False) # False e = (True or False) # True #1 print(a,b,c,d,e) #2 print("a:%s; b:%.2f; c:%s; d:%s; e:%s" % (a,b,c,d,e)) #3 s="\'hello,world\'\n\\\"hello,world\"" print(s)