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
c60df7c6d2aa3eaecdc1c95bc7bba9a96eff1add
kasemodz/RaspberryPiClass1
/LED_on_off.py
831
4.125
4
# The purpose of this code is to turn the led off and on. # The LED is connected to GPIO pin 25 via a 220 ohm resistor. # See Readme file for necessary components #! /usr/bin/python #We are importing the sleep from the time module. from time import sleep #We are importing GPIO subclass from the class RPi. We are ref...
99f64a174783c4a4f8a4a304672a096b0fe04ccc
Poter0222/poter
/PYTHON/03.04/string.py
697
4.1875
4
#coding=UTF-8 # 03 # 字串運算 # 字串會對內部的字元編號(索引),從 0 開始 s="hello\"o" # \ 在雙引號前面打入,代表跳脫(跟外面雙引號作區隔) 去避免你打的字串中有跟外面符號衝突的問題 print(s) # 字串的串接 s="hello"+"world" print(s) s="hello" "world" # 同 x="hello"+"world" print(s) # 字串換行 s="hello\nworld" # /n代表換行 print(s) s=""" hello world""" # 前後加入“”“可將字串具體空出你空的行數 print(s) s="hello"*3+"w...
e799fbff3d6be502d48b68fb1094b6dd4bcc4079
yihangx/Heart_Rate_Sentinel_Server
/validate_heart_rate.py
901
4.25
4
def validate_heart_rate(age, heart_rate): """ Validate the average of heart rate, and return the patient's status. Args: age(int): patient'age heart_rate(int): measured heart rates Returns: status(string): average heart rate """ status = "" if age < 1: tachyca...
59af5bd8671e37f88a8d870dafb252a31d19feb8
julminen/aoc-2020
/day_15.py
1,095
3.59375
4
#!/usr/bin/python3 from collections import namedtuple def read_file(day: str): with open(f"input/day_{day}.txt") as file: lines = [line.strip() for line in file] numbers = [int(n) for n in lines[0].split(",")] return numbers def play(input, until): # A bit slow print(f"Initial: ...
214209cf95f808f20e613ff30529a04a4c0d1094
julminen/aoc-2020
/day_23.py
8,448
3.609375
4
#!/usr/bin/python3 # Tried different variations for phase 2, none which is especially fast from typing import List from collections import namedtuple Cup = namedtuple('Cup', ['value', 'next']) class ListNode: def __init__(self, node_id: int): self.node_id = node_id self.next_node = None ...
83bba9ae93acb35a1789d734cdf7acc0349a08d4
JamesKing9/NewHeart-NewLife
/Study/Python/JCP027.py
273
3.734375
4
#!/usr/bin/python # -*-coding: UTF-8-*- ''' 需求: ''' def palin(n): next = 0 if n <= 1: next = input() print print next else: next = input() palin(n-1) print next i = 5 palin(i) print
7d0799241a47e78342643a0ed708ae9e5ff4c777
nabilahap/Labpy03
/Latihan1.py
187
3.53125
4
from random import random n = int(input("Masukan Nilai N: ")) for i in range(n): while 1: n = random() if n < 0.5: break print("dara ke: ",i, '==>', n)
519f6444488b6478ac2c09ded5f689c63ba21dd7
SifatIbna/codeforces-problems
/Boboniu Plays Chess/main.py
1,096
3.65625
4
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. def print_hi(name): # Use a breakpoint in the code line below to debug your script. print(f'Hi, {name}') # Press ...
76db64ba5a47301aeaae345e43b6e528037e369c
yanigisawa/python-morsels
/format_fixed_width.py
3,630
3.90625
4
# This week I'd like you to write a function, format_fixed_width, that accepts rows of columns (as a list of lists) # and returns a fixed-width formatted string representing the given rows. # For example: # >>> print(format_fixed_width([['green', 'red'], ['blue', 'purple']])) # green red # blue purple # The paddin...
e56c47a35358601f048e68397fa45658523a1469
TechKrowd/sesion1python_03062020
/operadores/06.py
465
4.09375
4
""" Pedir dos datos numéricos reales al usuario y calcular la suma, resta, producto y división de los mismos. """ n1 = float(input("Introduce un número real:")) n2 = float(input("Introduce otro número real:")) suma = n1 + n2 resta = n1 - n2 producto = n1 * n2 division = n1 / n2 print("La suma es {:.2f}".format(suma...
fe0364c9796f13da242bb31a99cd74ed21ca33c8
TechKrowd/sesion1python_03062020
/operadores/05.py
201
4.0625
4
""" Pedir un número entero por teclado y calcular su cuadrado. """ n = int(input("Introduce un número: ")) #cuadrado = n ** 2 cuadrado = pow(n,2) print("El cuadrado de {} es {}".format(n,cuadrado))
08edecc297ce651d8e7178941aa00e01de2b8ef7
halfozone007/repoA
/PythonProjects/RegularExpressions/1Regex.py
420
3.796875
4
#Regular Expressions are a very powerful method of matching patterns in a text import re def main(): fh = open('raven.txt') for line in fh.readlines(): if re.search('(Neverm|Len)ore', line): print(line, end = '') for line in fh.readlines(): match = re.search('(Neverm|Len)ore', ...
112fcd917a53cbc7da8ce27c1055bfa577b93458
halfozone007/repoA
/PythonProjects/Loops/enumerate.py
151
3.5625
4
def main(): string = "this is a string" for i, c in enumerate(string): print(i, c) if __name__ == '__main__': main()
5b014f4393fb6048c8f2d7546fe03a3d5625b28d
halfozone007/repoA
/PythonProjects/VariablesObjectAndValues/2UsingString.py
232
3.796875
4
def main(): n = 24 s = "This is a {} string".format(n) print(s) s1 = ''' Hello hello1 hello2 ''' #Print strings on different lines print(s1) if __name__ == '__main__':main()
8604414ab76375a1977f0b49929df80184b2fb9c
sagarnil1989/DemoProjects
/Customer Churn for Bank Customer/Classification_Solution_Sagarnil.py
2,586
4.03125
4
#Evaluating, Improving, Tuning Artificial Neural Network # Part 1 - Data Preprocessing # Import libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt #Set working directory & import data dataset = pd.read_csv("Churn_Modelling.csv") X=dataset.iloc[:,3:13].values Y=dataset.iloc[:,13].values ...
cb9c3f9e12220ab7a64692d3d4a2fa22860152c6
zxy1013/creat_mode
/creat_mode/factory.py
1,234
4
4
# 简单工厂模式 from abc import ABCMeta, abstractmethod # 抽象产品角色 class Payment(metaclass=ABCMeta): @abstractmethod def pay(self, money): pass # 具体产品角色 class Alipay(Payment): def __init__(self, use_huabei=False): self.use_huabei = use_huabei def pay(self, money): if self.use_huabei: ...
c45a016425d84fc6eda59d6d82c359b0eb3d49a6
iayushbhartiya/iayushbhartiya
/Guessing the number.py
739
3.96875
4
#Guessing the number nam = input('Enter your name: ') print('Welcome to guessing game', nam) num = 18 i = 0 while(True): count = 9 - i if count<0: print('Game over') break i += 1 val = int(input('Enter a number: ')) if val>18: if val>30: print('You...
4b4076ce66e3a70a7c36bc4c5aa87699a9f30995
Bayaz/flasktaskr
/project/db_create.py
780
3.625
4
#project/db_create.py import sqlite3 from _config import DATABASE_PATH with sqlite3.connect(DATABASE_PATH) as connection: #get cursor object to execute SQL commands c = connection.cursor() #create table c.execute("""CREATE TABLE tasks(\ task_id INTEGER PRIMARY KEY AUTOINCREMENT, \ n...
4f7f761819b008ab5a09eb51272fcfaeb974c12f
Ad0rian/Python-Voice-input-test
/venv/app.py
2,076
3.75
4
""" Este pequeño programa tiene el objetivo de probar el servicio de voz que permite usar python, en concreto este pequeño programa te permite realizar dos funciones, la primera es la de apagar tu equipo si le dices 'Apagar' y la otra funcion es la de buscar en internet, para activar esta funcion le tienes que decir 's...
85dcf64aed58d3d0f44bf12a86430788e684838e
Jayem-11/machine-learning-scratch
/machine_learning/neural_network/ann/perceptron/multiclass_perceptron.py
5,428
3.828125
4
import itertools import numpy as np from sklearn.datasets import make_classification import matplotlib.pyplot as plt from sklearn.metrics import f1_score from sklearn.model_selection import train_test_split from sklearn.linear_model import Perceptron as sklearn_perceptron class multiClassPerceptron: """ Perce...
43382e8fe8fac375b8bdbbda97a67d853a5a7e19
eleanorpark/Python-Dec-2018-CrashCourse
/areaofcircle.py
348
4.125
4
def area_of_circle(radius): 3.14*radius*radius radius=2 area = 3.14*radius*radius area_of_circle(radius) print('area of circle of radius {} is:{}'.format(radius,area)) def area_of_circle(radius): 3.14*radius*radius radius=10 area = 3.14*radius*radius area_of_circle(radius) print('area of circle of radius {} ...
6f89741abdec32b48b49bb52fa494c944e2ad541
mugiritsu/deepl-tr-pyppeteer
/deepl_tr_pp/browse_filename.py
972
3.578125
4
r"""Browse for a filename. https://pythonspot.com/tk-file-dialogs/ filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes=(("jpeg files","*.jpg"),("all files","*.*"))) """ # import sys from pathlib import Path import tkinter from tkinter import filedialog # fmt: off def browse_filename( ...
d84ff4475eee0708a755242c6019a381a1aa7c5f
carinapetcu/University-Projects
/Fundamentals of Programming/Game of Life/Validator/Validate.py
673
3.640625
4
import math from Exceptions.Exceptions import ValidatorError class Validate: def __init__(self): pass @staticmethod def validateBoards(board, boardWithPattern, row, column): dimension = int(len(boardWithPattern)) for index1 in range(dimension): for index2 in range(dim...
6832c702badf29d98eed86d234df1ba0183f9f4f
Deepak995/python
/bacic_exception.py
501
3.8125
4
class division: def divi(self, a,b): try: # a=int(input("enter the value of a ")) #b=int(input("enter the value of b")) c=a/b except ArithmeticError : print("enter the right value of b") else: return c print("this is a free stateme...
4add69787b4ad852eb7511ddbcdf5664ea1b2917
Deepak995/python
/iterator.py
173
3.796875
4
a=[1,2,2,3,2,'eraju','baju'] """for i in a: print (i)""" b=iter(a) print(b) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b)) print(next(b))
137bcdcadc480592f4a3c50240146b6fe9126313
Deepak995/python
/ansss.py
1,287
3.59375
4
###P- Replace somthing from given input # s1 = 'how are you' # s1 = s1.replace('how', 'who') # print(s1) # # list = ['where are you'] # list = list[0].replace('where','who') # print(list) ###################################################### ###P- output should be ----->[4, 5, 6, 1, 2, 3] # input = [1,2,3,4,...
16e7156b501609938163fcdc287b256589830413
nilloc95/Graphing-with-python
/d_graph.py
11,906
4.09375
4
# Course: CS261 - Data Structures # Author: Collin Gilmore # Assignment: 6 # Description: This file contains a class for an directed graph using a matrix to store links between nodes # along with the weight. It also has methods to add vertices, edges, remove edges, # find out if a path is v...
0f7cfefeb124d76ef25dc904500246c9e843658d
xg04tx/number_game2
/guessing_game.py
2,282
4.125
4
def main(): while True: try: num = int( input("Please, think of a number between 1 and 1000. I am about to try to guess it in 10 tries: ")) if num < 1 or num > 1000: print("Must be in range [1, 100]") else: computer_guess...
76b9e0167bf76c50015b4359665b33f495e85c81
echo-1234/code-complete-MIT60001
/assignments/ps0/ps0.py
191
3.953125
4
## input ## data type ## numerical operation import numpy x = int(input("Enter a number x: ")) y = int(input("Enter a number y: ")) print("x**y = ", x**y) print("log(x) = ", numpy.log2(x))
3beab522b6c62c0302f7a436bd2da893889d87d4
rickmansfield/U5.2-M3
/U5-2-M3-Homework/Task4b.py
799
3.734375
4
def csWordPattern(pattern, a): # print(a.split()) words = a.split() # print("words split", words) if len(words) != len(pattern): return False char_to_word = dict() for i in range(len(pattern)): char = pattern[i] word = words[i] if char in char_...
3d2acafdebab21cb2ff8c5b0b08e26ba47ed8b44
vtheno/zuse_sim
/MainMenu.py
4,269
3.796875
4
import Tkinter as Tk import App class MainMenu(object): def __init__(self, master): self.master = master self.width = master.winfo_width() self.height = master.winfo_height() f_text = Tk.Frame(master, bg = 'white', width = self.width, height = self.height / 6,bd=1) f_text.gr...
d3030ce858b421aa3b7d4f86874063ed0d862890
akshayjoshii/LeetCode_Coding_Interview
/Pos_Neg_Array.py
942
3.578125
4
import numpy as np import timeit #O(n^2) - Simple solution def pos_neg_simple(arr): t = [] #2 for loops for i in range(len(arr)): for j in range(i+1, len(arr)): if(abs(arr[i]) == abs(arr[j])): t.append(abs(arr[i])) if(len(t)==0): return "No Positive/Negative ...
4659470dc6b39f197e43b358b5bd8f196157dec1
Parkhomets/Python
/Stepic/2/DateAndTime.py
208
3.765625
4
import datetime x = input().split(" ") for i in range(3): x[i] = int(x[i]) data = datetime.date(x[0], x[1], x[2]) data = data + datetime.timedelta(int(input())) print(data.year, data.month, data.day)
1c1b4cd1dda92e6aef9fe38236a45a856776f082
ConorMB93/Python1
/AirportDistance/Airports.py
635
3.734375
4
''' Airports by Conor Byrne ''' class Airports: def __init__(self, airport_code, name, city, country, lat, long): self.airport_code = airport_code self.name = name self.country = country self.city = city self.lat = float(lat) self.long = float(long) def __str...
d8d59642182dbba4388cdfd81ab97e99efa92cc5
rchaskar/PycharmWork
/Functions.py
742
4.0625
4
'''def average(a,b): return (a+b/2) print(average(20,10)) ''' '''def calculate(a,b): x=a+b y=a-b z=a*b r=a/b return x,y,z,r print(calculate(10,20)) ''' #function inside another function ''' def message(name): def gretting(): return "How are u " return gretting() + name prin...
98f3f92f67791def2251246bccb8770c73320dae
rchaskar/PycharmWork
/assignment1.py
117
3.5625
4
Name = "Rahul Chaskar" City = "Pune" Age = 26 height = 179 Weight = 80 print("Name is" + Name , "City:" +City, Age, Weight)
6c111511875ad1fd6eb2c23a7206122a73f23e76
kexinxin/Defect
/genetic-hyperopt/mahakil/Distance.py
348
3.578125
4
class Distance: def __init__(self,distance,label): self.__distance__ = distance self.__label__= label def get_distance(self): return self.__distance__ def get_label(self): return self.__label__ def __str__(self): return str("distance:{} label:{} ".format(self.__...
dc0b326cbbd52603b780b087d8f2fe9ab7e3c63a
kexinxin/Defect
/SoftwarePrediction/OverSampleAlgorithm/smote.py
3,030
3.5625
4
from sklearn.neighbors import NearestNeighbors import random import numpy as np class Smote: """ Implement SMOTE, synthetic minority oversampling technique. Parameters ----------- sample 2D (numpy)array class samples N Integer amount of SMOTE N%...
760e2277fae9977374f73331293fb6efd1d7cddd
kexinxin/Defect
/SoftwarePrediction/OverSampleAlgorithm/BorderlineOverSamplling.py
4,098
3.5625
4
import random from sklearn.neighbors import NearestNeighbors import numpy as np class BorderlineOverSampling: """ RandomOverSampler Parameters ----------- X 2D array feature space X Y array label, y is either 0 or 1 b float in...
4092786eb3254dc3dcddd09bbe6892d5a0ccb717
cksrb1616/Algorithm_past_papers
/DFSBFS/DFSBFS_5-5_factorial.py
265
3.921875
4
#반복적으로 구현한 n! def factorial_iterative(n): result=1 for i in range(1,n+1) result *= i return result #재귀적으로 구현한 n! def factorial_reculsive(n): if n<=1: return 1 return n*factorial_reculsive(n-1)
513540cee31c1fbd3c2dbb95ffb4ed2bf3473b2c
TanyaGerenko/T.Gerenko
/Ex4.py
555
3.8125
4
#ДЗ-4 #N-школьников делят k-яблок поровну, неделящийся остаток остается в корзинке. #Сколько яблок достанется каждому, сколько останется в корзинке? k = int(input("Сколько всего яблок? ")) n= int(input("Сколько всего школьников? ")) print("Каждому школьнику достанется ", k//n, "яблок") print("В корзинке останет...
6eae59d3f1e4f73b5563fc1979024d0cbd612705
TanyaGerenko/T.Gerenko
/Ex6.py
636
3.859375
4
#ДЗ-6 #Дано целое, положительное, ТРЁХЗНАЧНОЕ число. #Например: 123, 867, 374. Необходимо его перевернуть. #Например, если ввели число 123, то должно получиться на выходе ЧИСЛО 321. #ВАЖНО! Работать только с числами. #Строки, оператор IF и циклы использовать НЕЛЬЗЯ! n = int(input("Ввести целое, положительное, ТРЁ...
66c3ffce7cface103349ba9d972521cbe57c883c
MateusValasques/AlgoritmosPython
/Ordenação/Quase ordenados.py
11,576
3.8125
4
from array import * import time import random cont_selection = 0 cont_insertion = 0 cont_shell = 0 cont_quicksort = 0 cont_heap = 0 cont_merge = 0 def selection_sort(array): global cont_selection for index in range(0, len(array)): min_index = index for right in range(index + 1, len(array)): ...
0bd28c58aec4f2d5ebb0428cb3da2929239206b7
zhangxingxing12138/web-pycharm
/pycharm/改版.py
737
3.90625
4
from collections import Iterable class MyList(object): def __init__(self): self.items = [] self.index = 0 def add(self, name): self.items.append(name) self.index = 0 def __iter__(self):#加这个方法变成了可迭代对象(iterable) return self #返回一个迭代器(MyIterator(self)) def __next__...
2e3b067497ab8a8005abecbcea9606bb56d43493
licebmi/extra-projects
/number-printer.py
1,416
4.0625
4
#!/usr/bin/env python3 import argparse import random def parse_arguments(): parser = argparse.ArgumentParser(description="Generate a range of random integers") parser.add_argument( "-o", "--ordered", action="store_true", dest="ordered", help="Returns an ordered range", ...
4280e622f18a3eac097f5773902f30ba2c8cb6d3
uva-sp2021-cs5010-g6/finalproject
/project01/question3.py
7,685
3.796875
4
""" This module provides the functions and code in support of answering the question "How do popular food categories fare with corn syrup?" The `main()` function provides the pythonic driver, however this can be run directly using python3 -m project01.question3 after the files have been fetched from the USDA (see `pro...
4deedfe0dea559088f4d2652dfe71479fce81762
saman-rahbar/in_depth_programming_definitions
/errorhandling.py
965
4.15625
4
# error handling is really important in coding. # we have syntax error and exceptions # syntax error happens due to the typos, etc. and usually programming languages can help alot with those # exceptions, however, is harder to figure and more fatal. So in order to have a robust code you should # handle the errors and ...
1e922122a376fe94be19ce450289691680dfc55a
MuraliSarvepalli/Squeezing-reptile
/my_func_ex3.py
176
3.984375
4
def myfunc3(a,b): if (a+b)==20 or a==20 or b==20: return True else: return False a=input('Enter a') b=input('Enter b') r=myfunc3(a,b) print(r)
dce7935bd17f8f27baf4cda9a2eb2f0db19c00b7
MuraliSarvepalli/Squeezing-reptile
/my_func_ex_7.py
370
3.9375
4
#Given a list of ints, return True if the array contains a 3 next to a 3 somewhere def three_conseq(ls): count=0 while count<len(ls): if ls[count]==3 and ls[count+1]==3: return True count+=1 ls=[] for i in range(0,5): num=int(input('Enter the values')) ls.append(n...
55f4fc114333b02e47285ac8d06aac4889ae403a
MuraliSarvepalli/Squeezing-reptile
/try_except_fianlly.py
245
3.84375
4
#try except finally def ask(): while True: try: n=int(input("Enter the number")) except: print("Whoops! Thats not a number") else: break return n**2 print(ask())
d5d16ef90534d51086eb9966710e794b39265ef7
MuraliSarvepalli/Squeezing-reptile
/my_func_ex_19.py
171
4.15625
4
#palindrome def palindrome(st): if st[::]==st[::-1]: return True else: return False st=input('Enter the string') print(palindrome(st))
a21b9e2173759cf993bcc77f445b4c2fedc10348
MuraliSarvepalli/Squeezing-reptile
/my_func_ex_17.py
225
4.03125
4
#Write a Python function that takes a list and returns a new list with unique elements of the first list. def unique(mylist): un_list=set(mylist) return un_list print(unique([1,1,1,1,3,3,5,4,9,5,6,7,8,7,2]))
f545e77bc882b7dacb6ba522f354531b8a3206ad
zdrasteenastya/utils
/patterns/strategy.py
1,443
3.71875
4
import types # Option 1 class Strategy: def __init__(self, func=None): self.name = 'Patter Strategy 1' if func is not None: self.execute = types.MethodType(func, self) def execute(self): print(self.name) def execute_replacement1(self): print(self.name + 'replace wit...
483f62eacc57d12e1542ef8bf8265896ef921323
zdrasteenastya/utils
/requests_to_db.py
1,821
3.6875
4
# coding: utf-8 import sqlite3 import psycopg2 conn = sqlite3.connect('Chinook_Sqlite.sqlite') cursor = conn.cursor() # Read cursor.execute('SELECT Name FROM Artist ORDER BY Name LIMIT 3') results = cursor.fetchall() results2 = cursor.fetchall() print results # [(u'A Cor Do Som',), (u'AC/DC',), (u'Aaron Copland ...
21fb03593c46ab3dee1bbfc36bf93698a0d87286
returnpointer/trainsim
/user_interface/menu_sim.py
1,826
3.5
4
""" Simulation Menu """ from PyInquirer import prompt from user_interface.menu_questions import style, sim_questions1, sim_questions2 from sim_engine.simulation import sim_run def sim_menu(railway, graph): """Simulation Menu""" if not railway['stations'] or \ not railway['tracks'] or \ ...
6c0b90765de1de097e3da9a5434649929ee01b7a
newpheeraphat/banana
/Algorithms/String/T_ReverseStringInList.py
147
3.609375
4
class Solution: def reverseWords(self, s: str) -> str: s3 = s.split() res = [i[::-1] for i in s3] return " ".join(res)
a9a4f9e454711353a969c827b8c3a6226ced3bf9
newpheeraphat/banana
/Algorithms/List/T_ChangeValuesInList.py
340
3.546875
4
def check_score(s): import itertools # Transpose 2D to 1D res = list(itertools.chain.from_iterable(s)) for key, i in enumerate(res): if i == '#': res[key] = 5 elif i == '!!!': res[key] = -5 elif i == '!!': res[key] = -3 elif i == '!': res[key] = -1 elif i == 'O': res[key] = 3 elif i == '...
aee829e9b7b2796c39884a76f4dc1a8fe0b6aca7
newpheeraphat/banana
/Algorithms/Integer/Prime/10001st_prime.py
311
4
4
def nth_prime(nums): counter =2 for i in range(3, nums**2, 2): j = 1 while j*j < i: j += 2 if i % j == 0: break else: counter += 1 if counter == nums: return i int1 = int(input()) print(nth_prime(int1))
a61fb10a9c8b3dc6244a01c7296a2de90fde246a
newpheeraphat/banana
/Algorithms/Map-FIlter/T_Zip.py
307
3.640625
4
class Solution: def convert_cartesian(self, x : list, y : list) -> list: res = [[i, j] for i, j in zip(x, y)] return res if __name__ == '__main__': print(Solution().convert_cartesian([1, 5, 3, 3, 4], [5, 8, 9, 1, 0]) ) print(Solution().convert_cartesian([9, 8, 3], [1, 1, 1]) )
41ff3ef5de93046c9836bfb2ea81435539244849
newpheeraphat/banana
/Algorithms/Dictionary/T_FindMax.py
308
3.84375
4
country = ['Brazil', 'China', 'Germany', 'United States'] dict1 = {} my_list = [] _max = 0 for i in country: int1 = int(input()) my_list.append(int1) dict1[i] = int1 if _max < int1: _max = int1 print(dict1) for key in dict1: if dict1[key] == _max: print(key, dict1[key])
339523698a51d97b56c9419d2f2a7ac90231edfb
bajca/pyladies
/Import_piskvorky/piskvorky.py
1,392
3.71875
4
def tah(herni_pole, cislo_policka, symbol): return herni_pole[:cislo_policka] + symbol + herni_pole[cislo_policka + 1:] def tah_pocitace(herni_pole): while True: cislo_policka = random.randrange(len(herni_pole)) if herni_pole[cislo_policka] == "-": return tah(herni_pole, ci...
fa1354ec7e81123f76e33054103be26e6d644e6d
bormanjo/Basic-Scrabble-Word-Aid
/Main.py
3,199
3.71875
4
scrabbleScores = [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ] def letterScore(letter, scorelist): ...
0b2de788f6be653826240f287578a86d2070893d
Donovan1905/Ants-colony-search-algorithm
/ants.py
3,237
3.78125
4
from AntsAlgo.const import ALPHA, BETA, RHO, CUL import random class Ant: # the ant class def __init__(self): # initialize visited and to visit cities lists as well as the time self.visited = list() self.toVisit = list() self.time = 0 """[summary] Function to choose the next c...
ef9848abae877105114ff60a86f33f40a7fc5a6a
Scottycags/Scott-Cagnard---Assignment-2
/Scott.Cagnard---Assignment.2.py
4,508
4.3125
4
#Scott Cagnard #Assignment 2 #2.1 practice str = "hello, i am a string" #Create any certain string x = str.find("am") #Set x to find the position of "am" in str print(x) #Print the location of "am" print(str.replace("i", "me")) #Replace "i" with "me" in the string and pr...
218cd58e485e9a4dee468613d738c5c84613ffc1
gopiselvi30/Python
/to find common elements in two elements.py
315
4.0625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Nov 29 22:46:58 2016 @author: gopi-selvi """ list1= range(1,100) list2= range(50,150) list3=[] for a in list1: if a in list1: list3.append(a) for b in list2: if b not in list1: list3.append(b) print(list3)
227510fcca18ea1c2a74af631cb1ba532ea3522b
oamole/Projects
/Iocane.py
9,848
3.796875
4
#!/usr/bin/env python # coding: utf-8 # # Iocane Powder # # ## Overview # # > Man in Black: All right. Where is the poison? The battle of wits has begun. It ends when you decide and we both drink, and find out who is right... and who is dead. # # The line above is from the perennial favorite 1980s movie adaptation...
b595630701a103250cb67649b0182040c982d1cf
Prink0054/Assignment-Python
/practice/practice.py
708
4.03125
4
""" #Question-1 a = int(input("Enter year to check it is leap year or not")) if((a%4) == 0): { print("Yes it is leap year") } else: { print("no it is not a leap year") } """ """ #Question-2 a = int(input("Enter Length of box")) b = int(input("Enter Width of box")) if(a == b): p...
a202ac88914984267b1065b58c388b2a69e4af2e
Prink0054/Assignment-Python
/Assignment11/Assignment11.py
1,346
3.96875
4
#Question1 import threading from threading import Thread import time class Th(threading.Thread): def __init__(self,i): threading.Thread.__init__(self) self.h = i def run(self): time.sleep(5) print("hello i am running",self.h) obj1 = Th(1) obj1.start() obj2 = Th(2) obj2.start() ...
0a8a9a0a4c6ca24fde6c09886c52d1d5c7817a24
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex40b.py
974
4.53125
5
cities = {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville'} cities['NY'] = 'New York' cities['OR'] = 'Portland' def find_city(themap, state): if state in themap: return themap[state] else: return "Not found." # ok pay attention! cities ['_find'] = find_city while True: print "State? (ENTER to qui...
5892f0c1c6cb36853a85e541cb6b3259346546e9
Trietptm-on-Coding-Algorithms/Learn_Python_the_Hard_Way
/ex06.py
898
4.1875
4
# Feed data directly into the formatting, without variable. x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" #Referenced and formatted variables, within a variable. y = "Those who know %s and those who %s." % (binary, do_not) print x print y #r puts quotes around string print "I said: %r."...
15eb6a39ec8e85689d6dc60f8bed506d68955634
pellertson/scripts
/bin/fenparser
1,712
3.5625
4
#!/usr/bin/python3 # parser for printing properly formatted chess boards from a FEN record # assumes piped input from json2tsv(2) import fileinput import sys # uppercase letters are white; lowercase letters are black def parse_square(sq): if sq == 'k': return '♚' elif sq == 'K': return '♔' elif sq == 'q': re...
b67a4bd391591382eeadec48c55e5db6e9417f1f
samyumobiMSIT/ads-2
/practise/m3/Bonus _ Hamilton Path/Hamilton Path/HamiltonianPath.py
1,684
3.71875
4
from __future__ import print_function from data_structures.adjacency_list_graph import construct_graph class HamiltonianPath(object): '''Find the hamiltonian path in a graph''' def __init__(self, graph): self.graph = graph self.vertices = self.graph.adjacency_dict.keys() self.hamiltonia...
59c54a778af80dc495ed27f83006893f36e9a9e7
saurabhslsu560/myrespository
/oop3.py
1,028
4.15625
4
class bank: bank_name="union bank of india" def __init__(self,bank_bal,acc_no,name): self.bank_bal=bank_bal self.acc_no=acc_no self.name=name return def display(self): print("bank name is :",bank.bank_name) print("account holder name is:",self.name) ...
31ebe8918dd39a56be55d7d73315ea3a1e0e292b
ftuyama/AIproblems
/Lab5/DiffEvolution.py
7,634
3.703125
4
# -*- coding: utf-8 -*- # !/usr/bin/env python """Algoritmo das N-Rainhas.""" from random import randint from copy import deepcopy from graphics import * import timeit def print_board(board): u"""Desenha o grafo de rotas a partir do mapa lido.""" win = GraphWin('N-Rainhas', 850, 650) win.setBackground(col...
5d14097892b10f631944b82dbe03262a26d84021
dariokl/firebase-flask-ponzi
/ponzi.py
2,355
3.546875
4
""" PONZI. A pyramid scheme you can trust YOU HAVE UNLIMTED TRIES THE 4 DIGITS IN THE NUMBER DONT REPEAT THERE IS NO LEADING ZERO YOUR GUESS CANNOT HAVE REPEATING NUMBERS THE FASTER YOU ARE DONE THE BEST THE RETURNS ARE ALLOCATED ACCORDING TO YOU ABILITY TO SCAPE THE PYRAMID FROM THE TOP KILLED MEANS THE NUMBER IS PR...
263c7fb994dca4aeb198f87793683ef6630b267a
kdolder79/maze_game
/rooms/room10.py
3,951
3.5
4
import adventure_game.my_utils as utils from colorama import Fore, Style # # # # # # ROOM 10 # # Serves as a good template for blank rooms room10_description = ''' . . . 10th room ... This looks like another hallway. Not much is in this room. ''' room8_state = { 'door locked': Fal...
b42c601cfb574a4d8f6f4f5c37b117385bd350ee
KevinBorah/Python_for_Absolute_Beginners
/Python_Code/RPS_Game-v1.py
1,614
4.09375
4
print("----------------------------") print(" Rock Paper Scissors v1") print("----------------------------") print() player_1 = input("Enter Player 1's name: ") player_2 = input("Enter Player 2's name: ") rolls = ['rock', 'paper', 'scissors'] roll1 = input(f"{player_1} what is your roll? {rolls}: ") rol...
638ba2a42c0aae6fa5a250d6aeaac2a81c264180
szerem/pySolve100Exercises
/45.py
201
3.546875
4
import os, string if not os.path.exists("letters"): os.makedirs("letters") for letter in string.ascii_lowercase: with open("letters/{}.txt".format(letter), "w") as f: f.write(letter)
3fe58aa1750f43479050a19efe175cbffcf60d9a
szerem/pySolve100Exercises
/79.py
293
3.796875
4
import platform import string print(platform.python_version()) while True: psw = input('--> ') if any( i.isdigit() for i in psw) and any( i.isupper() for i in psw) and len(psw) >= 5: print("Password is fine") break else: print("Password is not fine")
02a81d00904de7e79c311d05919ad55012d903af
CHENHERNGSHYUE/pythonTest
/tkinter/tkinter_09_messagebox.py
1,260
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 12:00:12 2019 @author: chenmth """ import tkinter as tk window = tk.Tk() window.title('messagebox test') window.geometry('600x300') def answer(): print(input('')) def messageBoxShowing(): tk.messagebox.showinfo(title='info box', message='一般顯示') tk.messag...
525bea426bd338a87b1c0b2a76c833fd2eedae49
CHENHERNGSHYUE/pythonTest
/class.py
566
3.578125
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 5 15:33:44 2019 @author: chenmth """ class Calculator: #class名稱第一個字母要大寫 Name = 'kenny' def add_function(a,b): return a+b def minus_function(a,b): return a-b def times_function(a,b): return a*b def divide_function(a,b): ...
9a0d3d86d0390f77a0533b36d751799489a582e3
CHENHERNGSHYUE/pythonTest
/pandas/a.py
450
3.734375
4
# -*- coding: utf-8 -*- """ Created on Tue Jan 15 20:18:54 2019 @author: chenmth """ #list = ['3','4','a','-1','b'] # #try: # total = 0 # for i in list: # # if type int(i) is int: # total = total + int(i) # else: # pass # print(total) #except: # ValueError list = ['3', ...
982bf085f43b2e0d3c48701b3df06e8edb66cd76
CHENHERNGSHYUE/pythonTest
/copy_id.py
767
3.53125
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 14:46:21 2019 @author: chenmth """ import copy a = [1,2,3] b = a print(id(a)) #id表示秀出該物件存放記憶體的位置 print(id(b)) print(id(a)==id(b)) b[0]=111 print(a) #因為空間共用, 所以互相影響 c = copy.copy(a) #copy a 的東西, 但存放記憶體空間位置不同 print(c) print(id(a)==id(c)) c[0] = 1 print(a) #c是copy a來的 ...
d11526d684d51e31950e0220c01d977fde90a8f6
CHENHERNGSHYUE/pythonTest
/pandas/pandas_07_merge04_index.py
542
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 12:05:55 2019 @author: chenmth """ import pandas as pd import numpy as np A = pd.DataFrame({'A':[0,1,2], 'B':[3,4,5], 'C':[0,1,2]}, index=['X','Y','Z']) B = pd.DataFrame({'C':[0,1,2], 'M':['A','A','...
5a8526d077625013a78de556b1c3f86f6f628860
CHENHERNGSHYUE/pythonTest
/numpy/numpy_01.py
404
3.71875
4
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 15:20:54 2019 @author: chenmth """ import numpy as np array = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) print(array) #秀出矩陣形式 array不能有逗號且必須是矩形 print(array.ndim) #2 多少維度 print(array.size) #12 (4*3) 多少個元素 print(array.shape) #(4,3) (x,y)->(矩陣數、行、row, 矩陣內部元素、列、colum...
beebefcc521dfb5aafbb12b0d67d9a6516c831d5
natahlieb/adventofcode2017
/Day2/day2.2.py
540
3.625
4
import sys def findDivisor(row): max = 0 min = sys.maxsize for k in range(0, len(row), 1): for j in range(k+1, len(row), 1): print(' comparing k {} j {}'.format(row[k], row[j])) if(int(row[k]) > int(row[j])): if (int(row[k]) % int(row[j]) == 0): return int(row[k]) / int(row[j]) el...
7b10d33efe740095c60a6d108f704c85d413eefd
natahlieb/adventofcode2017
/Day13/day13.0.py
1,645
3.53125
4
import sys def calculateScannerLocation(cycleNubmer, depth): currentLocation = 0 count = 0 direction = "down" depth = depth - 1 while(count != cycleNubmer): if (direction == "down"): if currentLocation+1 <= depth: currentLocation += 1 else: direction = "up" currentLocation -= 1 elif di...
1b344f93dd4970ffba799d08516651b0958a7ba2
joshwinebrener/clock-math
/clockmath.py
3,148
3.53125
4
""" Created to compute all the meaningful mathematical arrangements of a sequence of integers. Specifically, this script is made to find the percentage of such meaningful arrangements in 12- and 24-hour time formats. E.g. 6:51 : 6 - 5 = 1 """ import sys class Mode: twelve_hour = 0 twentyfour_hour = 1 d...
750870bd2e4bdfc1ca690ec6a09cf37245f0ad59
Binary-Developers/Dark-Algorithms
/Count_Inversions/countInversion.py
249
3.78125
4
n=int(input('Enter number of elements\n')) a=[] print('Enter n elements\n') count = 0 for i in range (0,n): a.append(int(input())) for i in range(0,n): for j in range(0,i): if a[j]>a[i]: count+=1 print(count)
344023505df184a5c5dca70610b0f77c116b3158
antonioanerao/python-codecademy
/aula2.py
459
3.578125
4
def applicant_selector(gpa, ps_score, ec_count): if (gpa >= 3.0) and (ps_score >= 90) and (ec_count >= 3): return "This applicant should be accepted." elif (gpa >= 3.0) and (ps_score >= 90) and (ec_count < 3): return "This applicant should be given an in-person interview." else: return "This applicant...
3a0fdd4a1bcc83eb0501f91cdc0da8abebfd8172
Gabriel-Teles/Mercado
/Mercado.py
799
3.5625
4
#coding: utf-8 from Estoque import estoque class mercado: def mercado(self): esto = estoque() while True: print("\n= = = = Bem-vindo(a) ao EconomizaTec= = = =\n") print("Digite a opção desejada\n") print("1. Cadastrar um Produto") print("2...
00dc2338120ff076d7e0f1e7a16e1affbec35fb7
Pallavirampal/python_games_programs
/exercise 6.py
2,562
3.765625
4
import random comp=['Rock','Paper','Sicssor'] # print(comp_choice) user_score=0 comp_score=0 i=1 while i<=6: comp_choice = random.choice(comp) print('*** ROUND',i,'***') user_choice = input('Press (r) for rock (p) for paper and (s) for scissor:') if user_choice == 'r': if comp_choice == 'Rock':...
f0b9981c887e5a642a1479a2ae52da120b79d3dc
MarlenXique/lab-10-more-loops
/hanoi.py
872
4
4
def move(f,t): #from,to.A value passed to a function (or method) when calling the function. print("move from {} to {}".format(f,t)) #.format is amethod because of the dot. ots a strong, class of data. move("A","C") def moveVia(f,v,t): #from,via,to. move(f,v) #function call to move(): move from step1 to step 2 (...
79b5d599291b8b0ec5532134e2f382177e935d3b
Chih-YunW/Full_Name
/name.py
174
4.15625
4
def full_name(f: str, l:str): full_name = f + ' ' + l return full_name f = input("What is the first name: ") l = input("What is the second name: ") print(full_name(f,l))
c4167ce0440026258141ff33fb5c0ba2404938fa
Artarin/study-python-Erick-Metis
/operation_with_files/exceptions/words_counter.py
488
3.96875
4
"""this program search and counting quontity of simple word in text.file""" pre_path = "books_for_analysis//" books = ["Életbölcseség.txt", "Chambers's.txt", "Crash Beam by John Barrett.txt" ] for book in books: print (book +':') with open (pre_path+book, 'r', encoding='utf-8...
71a2fe42585b7a6a2fece70674628c1b529f3371
pltuan/Python_examples
/list.py
545
4.125
4
db = [1,3,3.4,5.678,34,78.0009] print("The List in Python") print(db[0]) db[0] = db[0] + db[1] print(db[0]) print("Add in the list") db.append(111) print(db) print("Remove in the list") db.remove(3) print(db) print("Sort in the list") db.sort() print(db) db.reverse() print(db) print("Len in the list") print(len(db)) pr...
97745f9a33b8e5653d050d3a5c875c57bc4e5780
WangMingJue/StudyPython
/Test/Python 100 example/Python 练习实例6.py
1,134
4.25
4
# 题目:斐波那契数列。 # # 程序分析:斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……。 # # 在数学上,费波那契数列是以递归的方法来定义: # F0 = 0 (n=0) # F1 = 1 (n=1) # Fn = F[n-1]+ F[n-2](n=>2) # 普通方法 def method_1(index): a, b = 1, 1 for i in range(index - 1): a, b = b, a + b return a # 使用递归 def method...
e87c204af85487af4753814f850156fd414b36b8
WangMingJue/StudyPython
/Test/Python 100 example/Python 练习实例8.py
260
3.796875
4
# 题目:输出 9*9 乘法口诀表。 # # 程序分析:分行与列考虑,共9行9列,i控制行,j控制列。 for i in range(1, 10): result = "" for j in range(1, i + 1): result += "{}*{}={} ".format(i, j, i * j) print(result)
16ea342f088dabb6af5c4f932144b9904e417cd3
ueoSamy/Python
/lesson4/easy.py
1,552
4.09375
4
# Все задачи текущего блока решите с помощью генераторов списков! # Задание-1: # Дан список, заполненный произвольными целыми числами. # Получить новый список, элементы которого будут # квадратами элементов исходного списка # [1, 2, 4, 0] --> [1, 4, 16, 0] list_a = [1, 2, 4, 0] list_b = [elem ** 2 for elem in list_a]...
678e8e9b2995324a8c7fd091d1a9b2cc7dde8171
KIMZI0N/bioinfo-lecture-2021-07
/src/016_1.py
811
3.59375
4
#! /usr/bin/env python file_name = "read_sample.txt" ''' #1 with open(file_name, 'r') as handle: for line in handle: print(line) #line에 이미 \n가 들어있음. #print()도 디폴트end가 \n이므로 enter가 두번씩 쳐짐. #print(line, end' ')하면 end를 띄어쓰기로 바꿀 수 있음. #2 #print(line.strip()) #line의 \n를 없앨 수 있음. #3 handle = open(file_name,'r') for line in...