blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
ba420df5d51cba68dc5236664f5defd623b903e5
amberrevans/pythonclass
/chapter 3 programs/miles_per_gallon.py
347
4.4375
4
# Amber Evans #9/9/2020 # This program calculates MPG #gets miles driven from user miles= float(input('Enter the miles driven: ' )) #gets gallons of gas used from user Gas= float(input('Enter gallons of gas used: ')) #calcluate MPG for user Miles_per_gallon = miles / Gas #display the MPG for user print('Your MPG wa...
b67f7ba6ea231c774c2c9a9ef7cf48c56981a170
NolanMcD/ClassWork
/Homework8.py
3,838
3.546875
4
import matplotlib.pyplot as plt #map plotting import numpy as np # Array def GenerateDrifterFileName (location): #file name given tag fname = "VirginiaKey8723214_meantrend.txt" print (fname) # show name before positions ...
eaa0752bc60ccc37178d7b45b0e6a6814c8ffb5b
loganetherton/quiz_exercise
/classes/Subject.py
996
3.90625
4
from random import choice, randrange class Subject(object): def __init__(self): """ Subject on which a class can be based, and for which proficiency is determined for each student and teacher """ self._subjects = ['math', 'science', 'reading', 'writing', 'history'] @pr...
44fdc68dfdef979c42fb78fdfa526b1385c78fb2
paladiinga/HW1
/sds.py
419
3.75
4
# EX 1.1 a = int(input()) if a == 2: print(29) elif a == 8: print(31) elif a % 2 == 0: print(30) else: print(31) # EX 1.2 a = int(input()) b= str(input()) if a % 2 == 0 and a != 2 and a != 8: print(30) elif a == 2: if int (b[-1]) == 0 or int(b[-1]) == 4 or int(b[-1]) == 8: ...
9e8c4925891a09f02048a7b98715a5e83cf01101
5antoshernandez/Housekeeping-Service-Estimate
/deletedb.py
313
3.59375
4
import sqlite3 conn = sqlite3.connect("housekeeping.db") curr = conn.cursor() deletedb = input("Are you sure you want to delete the DB?") if deletedb == "Y" or deletedb == "y": curr.executescript(''' DROP TABLE IF EXISTS House; DROP TABLE IF EXISTS Clients; ''') print("Deleted DB succesfully.")
cfe8d614ef6e52d945cb056178ede7b3a41473fc
Drux-maker/cursoPython_V2
/ejemplo 9/ejemplo9.py
137
3.765625
4
print ("Elige un numero para hacer su fibonachi:") x = int(input()) y = x + (x-1) print ("Su fibonachi es",y) print("═╬╦")
17ac927c9960311136b2f7d8556b18ceae2feaf0
seriadiallo/python_mysql_crud
/select.py
611
3.5625
4
from connection import CONNECTION try: with CONNECTION.cursor() as cursor: SQL = """ SELECT * FROM clients """ cursor.execute(SQL) clients = cursor.fetchall() # recupere toutes les lignes renvoyees par le select # print(clients) for client in clients: # for key,...
160adde2b37a937011de3cb00c559f0134c0d3a4
misohu/python_basics_examples
/14_files.py
1,505
4.125
4
# Files consists of data and EOF # Files are stored at the path, the path differs accros windows and unix # File lines ends with line endings CR LF, \r\n (WINDOWS :'()) or just the LF \n (MAC) file_reader = open('FileFolder/data_file.txt') file_reader.close() # Dont forget to close PLEASE # Using the python manager...
667c275edd48c46b0a862a795b063e752c862731
misohu/python_basics_examples
/07_conditions.py
2,117
4.4375
4
is_programmer = True is_student = False type(is_programmer) ''' Basic conditions - beware the double equal sign - beware the indentation (4 spaces = one tab after colon sign) - colon after if and else line ''' if is_student == True: print("He is a programmer") if is_programmer == False: print("He is a p...
fb9eaf9b85eaed513796d765bf55a1a598ead135
MCoffey1129/Clustering
/Clustering_compare_K_means_with_Hierarchical.py
7,219
3.96875
4
"""The below code looks at how the K-means and Hierarchical clusters are calculated in Python""" """# Importing packages""" import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.cluster import KMeans import scipy.cluster.hierarchy as sch from sklearn.cluster import...
01489fe2233ab674aa84c652c7c00d7597b54c2e
pablovfds/alg_adv15.1
/grafos/MrKitayutasColorfulGraph.py
1,471
3.65625
4
# -*- coding: utf-8 -*- # Universidade Federal de Campina Grande # Aluno: Diego Adolfo Silva de Araújo # Matricula: 113210090 # Disciplina: Algoritmos Avançados # Codeforces # Problem: 505B - B. Mr. Kitayuta's Colorful Graph # Time limit per test: 1 second # Memory limit per test: 256 megabytes # Input: standard in...
f8ac3fc2e347f0c56fbcfc989e302d503bc7dcc2
pablovfds/alg_adv15.1
/mix1/CaseOfFakeNumbers.py
671
3.5625
4
# -*- coding: utf-8 -*- # Universidade Federal de Campina Grande # Aluno: Diego Adolfo Silva de Araújo # Matricula: 113210090 # Disciplina: Algoritmos Avançados # Codeforces # Problem: 556B - B. Case of Fake Numbers # Time limit per test: 2 second # Memory limit per test: 256 megabytes # Input: standard input # Outpu...
3b7714b33ed54320c51ebeccd643b1dc52116ac5
pablovfds/alg_adv15.1
/math/LajotasHexagonais.py
453
3.9375
4
# -*- coding: utf-8 -*- # Universidade Federal de Campina Grande # Aluno: Diego Adolfo Silva de Araújo # Matricula: 113210090 # Disciplina: Algoritmos Avançados # Problema: Lajotas Hexagonais # Nivel: 2 def fibonacci(): a, b = 1, 2 while 1: yield a a, b = b, a+b while 1: ...
84f49d263d79ae50109bfc166a55f8452bd2aaff
pablovfds/alg_adv15.1
/edados-e-bibliotecas/EuPossoAdivinharEstruturaDados.py
1,327
3.84375
4
# -*- coding: utf-8 -*- # Universidade Federal de Campina Grande # Aluno: Diego Adolfo Silva de Araújo # Matricula: 113210090 # Disciplina: Algoritmos Avançados # Problema: Eu Posso Adivinhar a Estrutura de Dados! # Nivel: 4 from heapq import _heapify_max, heappush, heappop def answer(n): stk = [] ...
dc249f4e3cfdff412c66ff03b104417ff4b2a9a5
pablovfds/alg_adv15.1
/math/Figurinhas.py
497
3.640625
4
# -*- coding: utf-8 -*- # Universidade Federal de Campina Grande # Aluno: Diego Adolfo Silva de Arajo # Matricula: 113210090 # Disciplina: Algoritmos Avanados # Problema: Figurinhas # Nivel: 2 def mdc(x, y): if x > y: ddd = x div = y else: ddd = y div = x while d...
071870ab7a70f6c1e8cd9a51f2e1c5223a5e8be9
pablovfds/alg_adv15.1
/mix3/GeorgeAndAccommodation.py
660
3.5625
4
# -*- coding: utf-8 -*- # University Federal of Campina Grande # Student: Diego Adolfo Silva de Araújo # Registry: 113210090 # Discipline: Algoritmos Avançados # Code forces # Problem: 567A - A. George and Accommodation # Time limit per test: 1 second # Memory limit per test: 256 megabytes # Input: standard input # O...
5361ce7b32755e12e14bfbff0bc39c55352a5fb0
suryanshkumar/PythonTutorial
/linear_model/backprop_pytorch.py
1,709
3.953125
4
#Suryansh Kumar, Australian National University #Example to find optimal w using backpropagation using computational graph way #The only change is instead of using gradient function, we will use inbuild library to perform #backpropagation using computational graph #I am using pytorch library to achieve this. #import t...
b28aa432b9793f9f6a39cd637f1cea344a1cb7d0
suryanshkumar/PythonTutorial
/basics/listBasics.py
463
4.125
4
#declare list of numbers num = [53, 12, 11, 22, 99] print (num) #accessing the elements of the list, indexing starts with 0 print(num[2]) #modify the entries of the list num[2] = 0 print(num) #add the elements to the available list num = num + [6, 7, 8, 9] print(num) #or num.append(1000) print(num) #remove the eleme...
f57b84e60b6b757535c2802a532b09858b1b0f99
suryanshkumar/PythonTutorial
/data_loader/data_loader_csv_example.py
1,519
3.515625
4
#Author: Suryansh Kumar, Australian National University #Rythm of making dataloader in in pytorch import torch import csv import numpy as np from torch.autograd import Variable from torch.utils.data import Dataset, DataLoader class csvDataset(Dataset): #arrange your dataset in __init__ such as reading and setting...
2c63ea52d45abc107b8856d403c6785e5dd62dc2
apdaza/patrones-gof-python
/creacionales/abstract_factory/productos.py
2,965
3.890625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from abc import ABC, abstractmethod class Memoria(ABC): def implementacion(self): print("instalando memoria") @abstractmethod def operacion(self): pass class Board(ABC): def implementacion(self): print("instalando board") @abs...
172ae5e65ec8290e7887443bbc58379d3cc060dd
apdaza/patrones-gof-python
/creacionales/factory_method/productos.py
352
3.921875
4
from abc import ABC, abstractmethod class Producto(ABC): @abstractmethod def operacion(self): pass class ProductoConcreto1(Producto): def operacion(self): return "Operacion de Producto concreto 1" class ProductoConcreto2(Producto): def operacion(self): return "O...
e791c5736fa95418234203177b4c9f11f8be6f31
JasonAJordan/AlienInvader
/ryan_f.py
1,063
3.921875
4
import sys import pygame def make_ryans(ai_settings, screen, ryan): ryan = Ryan(ai_settings, screen) def create_star(ai_settings, screen, stars, star_number): """Create star and place it in its location in the row.""" star = Star(ai_settings, screen) star_width = star.rect.width ...
2b101e6def67a4acab0f9f363a37c6cdbf916247
zcstl/tempSave
/httpserver.py
769
3.5625
4
#!/bin/env python from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer PORT_NUMBER = 8080 #This class will handles any incoming request from #the browser class myHandler(BaseHTTPRequestHandler): #Handler for the GET requests def do_GET(self): self.send_response(200) self.send_header(...
f673a1a35f89dcf35ab9c47d61fc41394ab601bc
digi360/DicePoker
/dieview.py
1,952
4.125
4
from graphics import * class DieView: """DieView is a widget that displays a graphical representation of a standard six-sided die.""" value = 1 def __init__(self, win, center, size): """ create a view of a die e.g: d1 = DieView (myWin, Point(40,50), 20). This creates a die centered at (40,50) with length 20. ""...
f235bb2206c7c02f20aa22aa32f11b4f43490829
daniiomir/multilayer_perceptron
/src/modules/layers.py
8,081
3.765625
4
import numpy as np from typing import Union, Tuple class Layer: def __init__(self): self.shape = None self.require_grad = False self.name = None self.weights_shape = None self.bias_shape = None self.weights = None self.biases = None self.weights_grad...
b44b0dadfbe44c16a85ffd865937613da0ad6e40
vishwavijetha/PythonTutorials
/venv/PythonTutorials/4_String Manipulations.py
1,863
4.0625
4
""" ================================================================================================================================ Author: Vishwa Date Created: 01/04/2019 -------------------------- Topic: String Manipulations -- -------------------------- Methods: --> {join(), reversed(), upper(), lower(), startswit...
1350bb464d4d4bc9c324cbaa87ebf1f2cddd19b9
Ingenico-ePayments/connect-sdk-python3
/ingenico/connect/sdk/webhooks/secret_key_store.py
420
3.515625
4
class SecretKeyStore(object): """ A store of secret keys. Implementations could store secret keys in a database, on disk, etc. """ def get_secret_key(self, key_id): """ :return: The secret key for the given key ID. Never None. :raise: SecretKeyNotAvailableException: If the secre...
be6f382a3d56afbe543dbd6c7e66219eb8f18564
ivoryli/myproject
/class/phase1/day08/exercise02.py
881
3.890625
4
# class Enemy: # ''' # 敌人 # ''' # def __init__(self,name,hp,atk,atk_speed): # self.name = name # self.hp = hp # self.atk = atk # self.atk_speed = atk_speed # # def print_self(self): # print(self.name,self.hp,self.atk,self.atk_speed) # # L = [] # while True:...
c660112ff4e1a39d7544f899274c3bd93e3525f5
ivoryli/myproject
/class/phase1/day04/exercise03.py
441
3.796875
4
''' 输入字符串,显示第一,中间(奇数才有),最后一个,倒数后第3个,倒叙字符 ''' # n = input("输入一串字符") # print(n) # print(n[0]) # print(n[-1]) # if len(n) % 2 == 1: # print(n[len(n)//2]) # print(n[-1:-4:-1]) # print(n[::-1]) ''' 输入一个数,打印以那是为边的矩方形 ''' n = int(input("输入一个数")) print('*' * n) for i in range(n-2): print('*' + ' '*(n-2) + '*') prin...
699aa3b29fd2f6f8431b98a6c7a39daa7b9a8f6e
ivoryli/myproject
/class/phase1/day15/exercise02.py
1,095
3.890625
4
''' 员工管理器 ''' # class Employee: # def __str__(self): # return "Employee()" # # class EmployeeIterator: # def __init__(self,employess_list): # self.target = employess_list # self.index = 0 # # def __next__(self): # if self.index >= len(self.target): # raise Sto...
225b7779bd67baabd1a55d0de1278c08c86eda5c
ivoryli/myproject
/class/phase1/day02/温度换算器.py
524
3.625
4
''' 温度换算器(华氏度,摄氏度,开氏度) 摄氏度 = (华氏度 - 32) / 1.8 华氏度 = 摄氏度 * 1.8 + 32 开氏度 = 摄氏度 + 273.15 获取华,得摄氏度 获取摄氏度,得华氏度 获取摄氏度,得开氏度 华氏度 fahrenheit 摄氏度 centigrade ''' fahrenheit = float(input("华氏度")) print("摄氏度:",(fahrenheit -32)/1.8) centigrade = float(input("摄氏度")) print("华氏度:",centigrade * 1.8 +32) centigrade = float(input("...
da6a92d0a4ea93ed4398660fe716486266655a88
ivoryli/myproject
/class/phase1/day09/code01.py
415
3.796875
4
''' 实例成员 ''' #__dict__显示所有 对象的属性(实例变量) 字典 class ICBC: meneys = 100 def __init__(self,meney): self.meney = meney self.meneys -= meney @classmethod def print_meney(cls): print(cls.meneys) i1 = ICBC(5) # print(i1.meneys) #95 ICBC.print_meney() i1.meneys = 50 #没进__init__ i2...
12f44327b982473340a7c71c1d1367ecc7c90586
ivoryli/myproject
/class/phase1/day11/exercise04.py
1,025
3.734375
4
''' 1. 定义父类:武器,数据:攻击力,行为:购买(所有子类都一样).攻击(不知道怎么攻击) 定义子类:枪,数据:射速,行为:攻击 定义子类:手雷,数据:爆炸范围,行为:攻击 创建相应对象,调用相应方法. 画出内存图 ''' class Weapon: ''' 武器类 ''' def __init__(self,atk): self.atk = atk def buy(self): print("购买") def attack(self): raise NotImplementedError() ...
2ab1f4ccaf81ff82215e38a6d4ac945eb4e61214
ivoryli/myproject
/class/phase1/day09/exercise03.py
1,256
4
4
class Enemy: ''' 敌人 ''' def __init__(self,name,hp,atk,atk_speed): self.name = name self.hp = hp self.atk = atk self.atk_speed = atk_speed @property def name(self): return self.__name @name.setter def name(self,value): self.__name = val...
7c2f6b02a6df965d2fef1616d02187c62793690b
ivoryli/myproject
/class/phase1/day05/exercise07.py
1,699
3.65625
4
''' 猜拳 ''' ''' 思路: 1.设定胜利法则 2.对比 1)若 电脑 = 键 自己=值 则 电脑赢 2)若 自己 = 键 电脑=值 则 自己赢 ''' import random # 不建议用字典保存victory # L = ["剪刀","石头","布"] # victory = { # "石头":"剪刀", # "剪刀":"布", # "布":"石头", # } # # while True: # randq = L[random.randint(...
90d57e844ba5b5510fd08fbdf37ed50d8fc83b87
ivoryli/myproject
/class/phase1/菜鸟100例/exercise04.py
1,079
4.1875
4
#输入某年某月某日,判断这一天是这一年的第几天? #myself # month_of_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # # def is_leap_year(year): # return year % 4 ==0 and year % 100 != 0 or year % 400 == 0 # # def get_day(year,month,day,list_target): # total_day = 0 # if is_leap_year(year): # list_target[1] = 29 # ...
474941dae06f79bda21d44e4ec6c11e79820631b
ivoryli/myproject
/class/phase1/project_month01/game2048_01.py
3,975
3.515625
4
''' 2048核心算法 ''' #------------------------------------------------------------------------------------------------- #练习1:定义函数,将零元素移动到末尾 #20 20 --> 2200 #02 20 --> 2200 #myself ok # def move_zero_right(L): # for x in range(len(L) - 1): # for y in range(x + 1,len(L)): # if L[x] == 0: # ...
408716bf81cc4fa63f304265463ff8d8eedc9a14
ivoryli/myproject
/class/phase1/day07/code02.py
1,259
3.703125
4
''' 形参传递方式 默认形参 位置形参 -- 星号元组形参:位置实参数量无限 命名关键字形参:要求必须使用关键字实参 --双星号命名关键字形参形参:关键字实参数量无限 ''' def fun01(a,b,c): pass def fun02(*args): #对于方法而言,就是元组 #对于调用者而言,可以传递数量无线的位置实参 print(args) fun02() fun02(1) fun02(1,2,3,4) #命名关键字形参 #a,b是命名关键字形参 #*代表后面是命名关键字形参,不能传入任意对象 def fun0...
991e6128bd5476afe94bdee152abae3b8a24be7e
ivoryli/myproject
/class/phase1/day13/exercise03.py
816
3.796875
4
''' 输入出生日期,计算出生多少天 ''' import time def get_day(year,month,day): #lockaltime 参数:秒 返回:时间元组 time.struct_time(tm_year=2019, tm_mon=4, tm_mday=18, tm_hour=19, tm_min=32, tm_sec=58, tm_wday=3, tm_yday=108, tm_isdst=0) # print(time.localtime(time.time())) #UTC只是比北京时间提前了8个小时 time.mktime((1970, 1, 1, 8, 0, 0...
fb88dd5b122b8dccd86cc31bc0a49c813958816e
ivoryli/myproject
/class/phase1/day04/exercise05.py
259
3.5
4
L = [12,59,84,17,26,51,36,72] max = L[0] min = L[0] # for x in L: # if max < x: # max = x for i in range(1,len(L)): if max < L[i]: max = L[i] for i in range(1,len(L)): if min > L[i]: min = L[i] print(min) print(max)
13e4634fb63fa93a038620a9c001178b39132cc8
AliOsm/shakkelha-website
/helpers.py
196
3.71875
4
def split_list(sequence, splitter): group = [] for item in sequence: if item != splitter: group.append(item) elif group: yield group group = [] if group: yield group
6877d142a29f021caf1ffcb5622f48bdb18f2cdb
xc21/Algorithms
/even_odd_Nov4_2018.py
598
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 4 09:31:56 2018 @author: Xun Cao """ #Arrary #Q1: your input is to reoder the arrary of integers, and you have to make even number appear first # do it in O(1) space #Strategy: take the advance of the both ends of the arrary, #start from two ends, do the ...
aa6e96b263d338b272ccba640379caa910476538
vy3191/Data_Structures
/linked_list/problems/check_for_cycle/check_for_cycle.py
401
3.734375
4
from linked_list import LinkedList def check_for_cycle(ll): pass # Tests ll = LinkedList() print(check_for_cycle(ll)) # should print False ll.add_to_tail(1) print(check_for_cycle(ll)) # should print False ll.add_to_tail(2) ll.add_to_tail(3) ll.add_to_tail(4) print(check_for_cycle(ll)) # should print False ...
4e75a3afaa82aa117c9ce51a1495aac4d2d5cc1d
fosterj14/movieFinder
/movie.py
431
3.796875
4
class movie: name = 0 year = 0 rating = 0 description = 0 def __init__(self, name, year, rating, description): self.name = name self.year = year self.rating = rating self.description = description def print_info(self): print("Name: ", str(self.name), "\n...
21593ecf1159f0109c40b483c05cc434536e62c7
vishnuak15/Assignment1
/1.py
280
4.09375
4
num = int(input("enter the number:")) temp = num rev = 0 while(num > 0): dig = num % 10 rev = rev * 10 + dig num = num // 10 if temp == rev: print(f'The number:{temp} is a palindrome') else: print(f'The number:{temp} is not a palindrome')
ee7da1518f20590faf5ee2bff31ea7c59ea9e6d8
t4gforce/t4gforce-algorithms
/programming-contest/subset/subset.py
668
3.734375
4
def subset(k, N, a): if k < N: # 全ての選択肢を再帰で取得する a[k] = 0 subset(k + 1, N, a) a[k] = 1 subset(k + 1, N, a) else: # どの要素が選択されているか? for i in range(4): print(a[i], end=' ') print() # 表示処理 print('{', end='') initial...
40fdcd272c718ab7a8265783ce49f7bccccd2c25
hnjang/turbo-octo-couscous
/py/programmers/ex3_counting_cc/counting_cc_new_imcompleted.py
787
3.546875
4
#!/usr/bin/python3 from pprint import pprint def connected_components(neighbors): seen = set() def component(node): nodes = set([node]) while nodes: node = nodes.pop() seen.add(node) nodes |= neighbors[node] - seen yield node for node in n...
1bb6a292a5d9d3f40360e40c5082c62feed71f50
TommieHG/Exercism-Python
/bob/bob.py
466
3.640625
4
import re def response(hey_bob): #carve out everything that is not whitespace q = re.findall(r"\S", hey_bob) if hey_bob.isupper() and hey_bob.endswith("?"): return "Calm down, I know what I'm doing!" elif hey_bob.isupper(): return "Whoa, chill out!" elif len(re.findall(r"\s", ...
d8e35497fda2a823c56d7dd532165246d82ecbe6
nagygeri97/zernike-moments
/src/Transformations.py
3,036
3.5
4
import numpy as np from Utility import * class OldTransformation: """ Transform square inside circle ([]) """ def __init__(self, N, img): # img is unused self.N = N self.c1 = np.sqrt(2) / (N - 1) self.c2 = -1 / np.sqrt(2) def getPolarCoords(self, x, y): """ Return the polar coordinates corresponding ...
2b60f6190d9ea250d323a0af0f3aa356d5bf9d83
ai-spring-2019/project-4-elis-p4
/project4.py
9,835
3.703125
4
""" Elias Griffin Project 4 - Neural Network This code currently doesn't work - when I run it on a dataset, it tends to give an accuracy of around 50%, but isn't constant - it ranges between 45% and 60%. To me, this says that it might be an indexing issue, because it is clearly changing values, but it ...
c07ccbee81d4df50097cad1937ab8bc3e3f00447
guifrrs/INE5416
/Atividade III/problema6.py
386
3.875
4
x = int(input("Primeiro numero: ")) y = int(input("Segundo numero: ")) z = int(input("Terceiro numero: ")) maiorX = (lambda x, y, z: x if (x > y) and (x > z) else 0) maiorY = (lambda x, y, z: y if (y > z) and (y > x) else 0) maiorZ = (lambda x, y, z: z if (z > y) and (z > x) else 0) maior = (lambda x, y, z: maiorX(x,...
59fb34ca3c2b01ebb25ccd3b88e0b52607175413
shreya-sridhar/ProblemSolving
/problem73.py
1,257
3.75
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def __str__(self): if self == None: return str(None) return f"TreeNode: {{val: {self.val}, Left: {str(self.left)}, Right: {str(self.right)}}}" from queue import Queue def ...
d739b7d0f724698d80b8d07d47f8b50db83e6f71
cdodiya/Stone-Paper-Scissors
/stone_paper_scissor.py
570
4.09375
4
import random l=["Stone","Paper","Scissor"] while(True): choice=str(input("Do you want to continue?(Y/N) ")) if(choice=="y" or choice=="Y"): l1=random.choice(l) i=str(input("Enter your choice: ")) print("Computer chose: ",l1) if((l1=="Stone" and i=="Paper") or (l1=="Paper...
49fba4421763df67349e916b3dc58f1510f95400
CavalcanteM/Social_Network_Analysis-Project
/exercise3/distribution_generator.py
4,998
3.75
4
import csv import random # For the first distribution we assume that the node s represents the label 1 and the node t represents the # label 2 and 3. # We assume that the values have a probability D+(x) related how much is high the mean of the three score in respect # with a threshold value defined to be 2 for the cut...
1277a98014a22c382244f667badf42e42f763595
CavalcanteM/Social_Network_Analysis-Project
/exercise1_final/friedkin.py
2,304
3.53125
4
import random # Friedkin Johnsen dynamics # In this function belief and stubborness are defined as random # numbers for all the nodes def FriedkinJohnsen(G): belief = {i:random.random() for i in G.nodes()} stubborness = {i:random.random() for i in G.nodes()} t = 0 # time step stop = 0 # stop condition ...
bcf2b4c26945f4a226aa478a955b7d4771e7e10e
sanju5445/python_program.github.io
/Function.py
1,366
4
4
# def greeting(name): # print("hello",name +" good morning") # print("whats going on!!") # # # greet('sanju') # def add(x,y): # sum=x+y # print("the sum of the given two number is:",sum) # # add(25,25) # # def greet(name,msg): # print("hello", name +" ," +msg) # # greet('sanju','who are you?') # # #...
764d6a7e9b45d97b014d82d97f91bba444fd3953
sanju5445/python_program.github.io
/some_basic_pr.py
3,606
4.1875
4
# FIND THE EVEN NUMBER def even(start,end): for i in range(start,end): if i%2==0: print(i) # FIND THE ODD NUMBER def odd(start,end): for i in range(start,end): if i %2 !=0: print(i) # FIND THE ADDITION def add(n): sum=0 while n>0: x=int(input...
e6aace8b93a7fbddaf656a831222ef87826258bf
sanju5445/python_program.github.io
/arrayy.py
826
3.53125
4
import array as ay ar=ay.array('i',[1,2,4,5,6]) # print(ar) # ar.append(7) # print(ar) print(ar.buffer_info()) # print(ar[2]) # ar.reverse() # print(ar) # new=ay.array(ar.typecode,(i*i for i in ar)) # print(new) # ar.append(4) # print(ar) # ar.pop(4) # print(ar) # del ar[1] print(ar) # x=ar ar.reverse() print(ar) # pri...
f253815985b1ab5173daa218525690653ee066d4
olakiril/Python
/gabor.py
1,060
3.546875
4
def gabor(size, lambda_, theta, sigma, phase, trim=.005): """Create a Gabor Patch size : int Image size (n x n) lambda_ : int Spatial frequency (px per cycle) theta : int or float Grating orientation in degrees sigma : int or float gaussian standard deviation (i...
a03fd78b48f37f08e9478ff5fedc5ad2e88612f3
krishna13052001/python_projects
/openCV.py
410
3.53125
4
import cv2 #to know about image img=cv2.imread("C:/Users/jvskr/Desktop/python projects/screenshot1.jpg") print(img.shape) #to open image img=cv2.imread("C:/Users/jvskr/Desktop/python projects/screenshot1.jpg",1) # 1 for color and 0 for black and white image cv2.resize(img,(300,300)) print(img.shape) c...
ebdcf6774602d330bc743d691e36b56896f022d9
samuelbeaubien/comp551-project1
/src/testing.py
401
3.828125
4
import numpy x = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) for row in x: print (row) # b = numpy.array([[[8, 9]], [2], [3]]) # print (b) # a = numpy.array([1, 2, 3]) # print (a.shape) # a = a.transpose() # a = a.transpose() # print (a) # x = numpy.array([[1, 2, 3], [4, 5, 6]]) # a = numpy.array([[1,...
8fabcc035d501d122253075038f400382ced8b02
AshimaSEthi/Tkinter_Programs
/Buttons.py
382
3.671875
4
import tkinter as tk def addition(): a=40 b=50 add_num = a+b label.configure(text=str(add_num)) root = tk.Tk() root.title("Buttons in Tkinter") root.geometry("500x400") button = tk.Button(root,text="Add Button",command=addition) button.pack(padx=20,pady=20) label = tk.Label(root,text="Hi ! I am...
e6f432a0445316839325b33dd1576fca0f802cbb
gioms/corso-intro-python
/blackjack.py
2,292
3.59375
4
from random import randint class Blackjack: def __init__(self, mode = "40"): suites = ['clubs', 'spades', 'hearts','diamonds'] values = range(2,12) cards = list() if mode == "40": for s in suites: for v in values: cards.append((s, v))...
d58e5b600327c52a8ede6cba53caef087bddf463
allanleung/codingChallenge
/rabbit_eating.py
6,006
3.625
4
import math class Solution(object): def findStartingPosition(self, arr): """ :type arr: Array[Array[int]] :rtype: (int, int) """ height = len(arr) width = len(arr[0]) startingX = 0 startingY = 0 # Height is EVEN and Width is EVEN ...
b7c1995320f299b521d94c5d6d1c0e2ce1f7f8f3
vahellame/vtb_hack
/demo.py
1,106
3.546875
4
# -*- coding: utf-8 -*- from cryptography.fernet import Fernet # Fernet гарантирует, что сообщение, зашифрованное с его помощью, не может быть обработано или прочитано без ключа. # Fernet -это реализация симметричной (также известной как "секретный ключ") аутентифицированной криптографии. # # https://cryptography.io/...
baf7f9e1a6cd38fc6f465c4361b3fa22ff6bdc03
DeshawnN/python-progs
/palindrome_checker.py
625
4.0625
4
def main(): print 'Please enter a string and I\'ll let you know if its a palindrome or not: ' palindrome = raw_input().lower() p_check(palindrome) def p_check(string): is_palindrome = False if string == string[::-1]: is_palindrome = True else: pass if is_palindrome == True: print 'Yes, %s is a Palindro...
00a525e7214c4f0dddf9f1fd007b68a504c5574f
pandolf99/Juego
/Juego - Con interfaz.py
3,994
3.546875
4
import random from tkinter import * from tkinter import messagebox options = ['1', '2', '3'] play=True #------------------------------------ Interfaz raíz y ventana para introducir el nombre ------------------------------------------- raiz=Tk() raiz.title("Juego") raiz.config(bg="lightblue") raiz.geometry("220x80") ...
a09ce5b389c4cd73367201da02fa6aa91fee050e
praveen151040/dsp
/mat.py
696
4.1875
4
r1=input("enter no of rows for mat1") c1=input("enter no of columns for mat1") r2=input("enter no of rows for mat2") c2=input("enter no of columns for mat2") if(r1==c2): print"matrix multiplication is possible" print"give input for mat1" i=0 a={} while(i<r1): j=0 while(j<c1): j=j+1 k=input("enter mat1 eleme...
4e288cd443d6da7618c2cff610e4639ac8074415
maknetaRo/everyday_python
/alarmClock/alarm_clock.py
1,539
3.640625
4
""" Make a program that accepts command line arguments for what time to go off, and when it does it should launch a Youtube video in your browser that will start playing. The program should read in a text file that contains URLs to different Youtube videos and will randomly choose one and launch it. My command line ar...
9343abce23f2e960318f0b30ee755c60f7d357e8
allenwoods/graph_centrality
/src/find_paths.py
1,286
3.625
4
# -*- coding: utf-8 -*- #+Author:Allen Woods import copy def find_all_paths(edges, start, end, path=[]): path = path + [start] if start == end: return [path] if start not in edges: return [] paths = [] for node in edges[start]: if node not in...
9486fc66b2d9e5d431a1971738ed5b3a59065aa5
KPetsas/IoTHome
/backend/api/devices/cache.py
3,401
3.5
4
class DevicesCache(): """ The Cache is a JSON object with three elements: 1. Primary key: pk. 2. user_id to primary key, octal converted to avoid user_id overlap. 3. Octal converted value to list of user devices. Example of cache: {'pk': 2, '1': '0o1', '0o1': [{'name': 'Smart Socket', 'swi...
0ecde25ec680ed5b068356f59d9072dd62b1c2ce
ChanchalKumarMaji/LintCode
/551. Nested List Weight Sum/main.py
1,398
4.03125
4
""" This is the interface that allows for creating nested lists. You should not implement it, or speculate about its implementation class NestedInteger(object): def isInteger(self): # @return {boolean} True if this NestedInteger holds a single integer, # rather than a nested list. def getInteg...
ec6f01987bc2423289a479fff42aaafb4dfc2e26
ChanchalKumarMaji/LintCode
/924. Shortest Word Distance/main.py
584
3.84375
4
class Solution: """ @param words: a list of words @param word1: a string @param word2: a string @return: the shortest distance between word1 and word2 in the list """ def shortestDistance(self, words, word1, word2): # Write your code here p1, p2 = -1, -1 res = 2**31 ...
5cdfb8876c0d535a0c02413c741f812e73c5be45
chadhac/210CTProgramming-AlgorithmsAndDatasStructures
/Week 5 Coursework Task Question 10.py
598
4.28125
4
#Week 5 #Question 10 class extractingNumbers(): """Function to extract numbers from a sequence in ascending order""" #Input: [5,10,15,20,25,30,35,40,45,50,55,60] #Output: [5,10,15,20,25,30] numbers = ["5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60"] #list numbers.remov...
1283f03d94eedd130c2cdd80151d5c61d5c4cdee
chadhac/210CTProgramming-AlgorithmsAndDatasStructures
/Week 6 Coursework Task Question 12.py
624
4.15625
4
#Week 6 #Question 12 #Tree sort algorithm #Pre order #In order #Post order class treeSort(): """Function to implement tree sort algorithm""" def preOrder(): if self.left_child: self.left_child.preorder() if self.right_child: self.right_child.preorder() def inOrder():...
3b5a2d2fa1341e3d8ec456b21159a85e4931b92b
qkuenlin/DataViz
/csv2db-movie.py
3,710
3.625
4
import csv import sqlite3 #TODO mettre le budget if __name__ == '__main__': # connection à la db conn = sqlite3.connect('db.sqlite') with open("Data/genre.csv", "r", encoding="utf-8") as csvfile: genre_dico = csv.DictReader(csvfile, delimiter=",", quotechar='"') genre_dico = {int(l["id"]):...
837a9000953ba81ae8120360d06c4e18bde28286
jschluger/demos
/python/Crime.py
1,374
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sun Nov 12 17:21:02 2017 @author: Frank-Mia """ import matplotlib.pyplot as plt import pandas as pd def plot_crime(df): fig, ax = plt.subplots() labels = [] for key, grp in df.groupby(['County']): grp = grp.sort_values(by = ["Year"]) grp...
ae99f498f4b74fea0a05c3bae1e891cf512b5011
cuthai/ML_Assignment2
/utils/args.py
1,658
3.53125
4
import argparse def args(): """ Function to create command line arguments Arguments: -dn <str> (data_name) name of the data to import form the data folder they are: breast-cancer, glass, iris, soybean, vote -rs <int> (random_seed) seed used for data split. Defaults to 1. All s...
dc3f5a174c4ff8d719adfad3623ca7e73be8df9e
chroto/AES_practice
/AES/ctr_util.py
492
3.65625
4
import struct from .util import xor def encrypt_block(msg_block, cipher, iv, count): """ Takes a block and XORs it with a block cipher based on its order in the message indicated by count. """ counter = iv[8:] # last 8 are counter iv = bytes(iv[:8]) counter = struct.unpack('>Q', counter)[...
31b6f2360a75458f82e1a8a27d817faaa00d236d
mirzafahad/weekend_python_projects
/guess_the_number.py
2,006
4.1875
4
import random NUM_DIGITS = 3 MAX_GUESSES = 10 def main(): print(f''' Guess the number! by Fahad Mirza I am thinking of a {NUM_DIGITS}-digit number with no repeated digits. Try to guess what it is. Here are some clues: When I say: That means: pico One digit is correct...
a921ce618371a57012f618f58bc65b71a440641b
KennyDove/python-challenge-
/PyBank/main.py
2,764
4.03125
4
#Financial record analaysis #Pull the file into the document import os #what will be analyzed import csv #create a path to the document which will be used to run the code csvpath = os.path.join("..", "PyBank","budget_data.csv") #I need to declare variables and leave openings for calculations totmonths = 0 period_growth...
683f9d3dd1ca00e52ba20941f968be691107ae1c
gregparkes/PythonTeaching
/02-Simulation/solutions/04_solutions_1.py
1,359
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 29 16:53:19 2019 @author: gparkes """ import numpy as np import matplotlib.pyplot as plt # task 1 def monte_carlo_integrate(f, dx, dy, N): area = (dx[1] - dx[0])*(dy[1] - dy[0]) # generate random numbers in 2-d pairs = np.random.rand(N,...
49f87df0dbaefb6a606ff15d9945322ccc076e0d
gregparkes/PythonTeaching
/05-Learning/classes/bayes_lr.py
3,494
3.828125
4
"""Bayesian linear regression.""" import math import numpy as np from scipy import stats class BayesLR: """This Bayesian Linear Regression class handles the case where both sigma-sq and theta are unknown.""" def __init__(self, p, a0=2., b0=1., add_intercept=False): """Creates a Bayesian Linear Regression frame...
6d2c7f593158505e7fc975cc0533b073a1100e92
lwoodyiii/Calculator
/Calculator.py
568
4.03125
4
def calculate(): num1 = int(input('Enter your first number: ')) num2 = int(input('Enter your second number: ')) print('{} + {} = '.format(num1, num2)) print(add(num1, num2)) print('{} - {} = '.format(num1, num2)) print(subtract(num1, num2)) print('{} * {} = '.format(num1, num2)) print...
4129158a48b8e11ba1369634b4e0cfa1ddbb1c0a
antgilles/aoc2018
/day5.py
344
3.5625
4
#!/usr/bin/python from aocd import get_data d = get_data() #d = 'dabAcCaCBAcCcaDA' i = 0 while i + 1 < len(d): if (d[i].lower() == d[i+1].lower() and ((d[i].isupper() and d[i+1].islower()) or (d[i].islower() and d[i+1].isupper()))): tmp = d[:i] + d[i+2:] d = tmp i -= 1 else: ...
26c83828d6c7deede9fde8bc0dd98ce2deefa5a2
Rjsetter/LearningPython
/OOP/HouseApp/home.py
5,916
3.515625
4
#_*_ encoding:utf-8 _*_ def get_valid_input(input_string, valid_options): """验证输入是否正确""" input_string += "({})".format(",".join(valid_options)) response = input(input_string) while response.lower() not in valid_options: response = input(input_string) return response class Property(object): """基类,其他子类继承于此""" ...
0b3aca40ffe9adf35572d72aedd0352ea8702bff
Rjsetter/LearningPython
/Think_Python/06recurse.py
100
3.609375
4
def recurse(n,s): if n == 0: print(s) else: recurse(n-1, n+s) print("test-",s) recurse(3,0)
2e2d7a21799350681a87e1ca40b9a1a9e9940d1f
Rjsetter/LearningPython
/Think_Python/time/time.py
1,128
4.21875
4
#_*_ encoding:utf-8_*_ class Time(object): """定义一天的时间""" def __init__(self,hour=0,minute=0,second=0): self.hour = hour self.minute = minute self.second = second def time2int(time): """时间转换为秒""" minutes = time.hour * 60 +time.minute seconds = minutes * 60 +time.second return seconds def int2time(seconds): ...
8007f4c22dac323a2df19294b37fec77a620d819
Rjsetter/LearningPython
/Think_Python/08-is_palindrome.py
198
4.1875
4
#_*_ encoding:utf-8_*_ def is_palindrome(st): if st == st[::-1]: print("It's a palindrome!") else: print("It's not a plindrome!") sta=input("Please input the string:") is_palindrome('sta')
e9df44ee78ba6655c0397c60a6554dca9ad5d0d9
Mastercliff/uri-desafios
/iniciante/python3/distance.py
70
3.609375
4
X = int(input()) result = int(X*2) print("{} minutos".format(result))
851ca73ab94e3ade1a0134522fc03903eed7f239
khuyentran1401/Python-data-science-code-snippet
/code_snippets/python/list_extend.py
158
4.125
4
# Add a list to a list a = [1, 2, 3, 4] a.append([5, 6]) print(a) # [1, 2, 3, 4, [5, 6]] a = [1, 2, 3, 4] a.extend([5, 6]) print(a) # [1, 2, 3, 4, 5, 6]
5e1717aba274327b74da867e8a3e160eab9a2a66
khuyentran1401/Python-data-science-code-snippet
/code_snippets/python/args_example.py
412
3.84375
4
sample_range = (2, 5) sample_range2 = (3, 7) # With * print(list(range(*sample_range))) print(list(range(*sample_range2))) """ [2, 3, 4] [3, 4, 5, 6] """ # Without * print(list(range(sample_range))) """ Traceback (most recent call last): File "code_snippets/python/args_example.py", line 9, in <module> print(lis...
3053a62cfd2be67859475b51e29e8a60ca9b2204
khuyentran1401/Python-data-science-code-snippet
/code_snippets/python/heapq_example.py
723
3.578125
4
import heapq import random from timeit import timeit random.seed(0) l = random.sample(range(0, 10000), 10000) def get_n_max_sorting(l: list, n: int): l = sorted(l, reverse=True) return l[:n] def get_n_max_heapq(l: list, n: int): return heapq.nlargest(n, l) expSize = 1000 n = 100 time_sorting = timeit("g...
1a9c32ccba507e426c6f18e21fd4acfd9504dc51
khuyentran1401/Python-data-science-code-snippet
/code_snippets/pandas/select_dtypes.py
739
3.8125
4
import pandas as pd df = pd.DataFrame({'col1': ['a', 'b', 'c'], 'col2': [1, 2, 3], 'col3': [0.1, 0.2, 0.3]}) print(df.info()) """ <class 'pandas.core.frame.DataFrame'> RangeIndex: 3 entries, 0 to 2 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ...
2e808a28fe07f0e2261f674db37ebfbeeb257021
khuyentran1401/Python-data-science-code-snippet
/code_snippets/cool_tools/decorator_module.py
697
3.8125
4
from decorator import decorator from time import time, sleep def time_func(func): def wrapper(*args, **kwargs): start_time = time() func(*args, **kwargs) end_time = time() print( f"""It takes {round(end_time - start_time, 3)} seconds to execute the function""" ) ...
79f85dd35e666c912c3efda83a6cdd4b0bef53e0
leonjia0112/EC602_2017_FALL
/Assignment2/overflow.py
102
3.515625
4
f = 1 while f > 0: f = f/2 print(f) g, f = 0, 1.0 while g < f: print(f) g, f = f, f*2
8dfb622d9d51b397013985db855f66125866ffcd
leonjia0112/EC602_2017_FALL
/Assignment5/testpoly.py
4,409
3.65625
4
# AUTHOR Brian Appleton appleton@bu.edu # AUTHOR Alex Bennett gottbenn@bu.edu # AUTHOR Cathryn Callahan cathcal@bu.edu import unittest import sys authors = ['appleton@bu.edu', 'gottbenn@bu.edu', 'cathcal@bu.edu'] class PolynomialTestCase(unittest.TestCase): """unit testing for polynomials""" def setUp(self): ...
b8fc895ff2462eb14955263cbe219d4bbb062d52
mariusvniekerk/filesystem_spec
/fsspec/mapping.py
2,982
3.5625
4
from collections import MutableMapping class FSMap(MutableMapping): """Wrap a FileSystem instance as a mutable wrapping. The keys of the mapping become files under the given root, and the values (which must be bytes) the contents of those files. Parameters ---------- root : string p...
eab6d8fbb5b8fc32ff4305e0c5c71ae6621c4e76
JudithBabbel/Data_Driven_Astronomy
/Week2/Assignment1/angular_distance.py
1,281
3.96875
4
"""angular_dist that calculates the angular distance between any two points on the celestial sphere given their right ascension and declination. Angular distances have the same units as angles (degrees).""" #b = np.cos(d1)*np.cos(d2)*np.sin(np.abs(r1 - r2)/2)**2 #d = 2*np.arcsin(np.sqrt(a + b)) import numpy as np d...
a7e38d52fd02b4ddf7c0aa9aa8d6be8d33f4eb0f
JudithBabbel/Data_Driven_Astronomy
/Week5/Assignment 1 - Building a regression classifier/color-color_redshift_plot.py
817
3.59375
4
import numpy as np from matplotlib import pyplot as plt # Complete the following to make the plot if __name__ == "__main__": data = np.load('sdss_galaxy_colors.npy') # Get a colour map cmap = plt.get_cmap('YlOrRd') # Define our colour indexes u-g and r-i x = data['u'] - data['g'] y = data['r']...