blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
980704a325d7845138060370d2975c2ba5e42ea0
jdiaz-dev/practicing-python
/SECTION 13 modules and packets/65 dates modules.py
472
3.515625
4
#date modules #this module is in python by default import datetime #show today date print(datetime.date.today()) #to get complete date completeDate = datetime.datetime.now() print(completeDate) print(completeDate.year) #show year print(completeDate.month) #show month print(completeDate.day) #show day # to custo...
f20ac75fe9af810058223a9a2f534958f357ee8e
cehdeti/pyeti
/pyeti/utils.py
2,643
3.953125
4
import datetime import re def ignore_exception(*exception_classes): """ A function decorator to catch exceptions and pass. @ignore_exception(ValueError, ZeroDivisionError) def my_function(): ... Note that this functionality should only be used when you don't care about th...
e5b19a2665932c1af7bdaeaa738ad6008f2c7d22
KAPILJHADE/banking_system_python
/deposit.py
878
3.703125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 25 19:08:25 2017 @author: dell """ from database import accountlist as items def depositing(): amount=0 while 1: entry = int(input("Enter the account number (1 for entire list,0 to exit) : ")) if entry==0: break elif en...
e070f0feedb5b6c1efa3f08e80e98e2484ea7574
monikarychter/assigments
/rewrite_bigger.py
86
3.6875
4
def bigger(x,y): if x > y: print(x) else: print(y) bigger(1,8)
3a39966a47097e02b11823c38b11975df0e7feec
20191014/kit2020-myflask
/testdb.py
339
4.03125
4
import sqlite3 conn = sqlite3.connect('mydb.db') # Cursor 객체 생성 c = conn.cursor() # 데이터 불러 와서 출력 for row in c.execute('SELECT * FROM student'): print(row) # 접속한 db 닫기 conn.close() # CREATE TABLE "users" ( # "id" varchar(50), # "pw" varchar(50), # "name" varchar(50), # PRIMARY KEY("id") # );
1e3c93b94d57fbd151699296838a32dabb105ec0
satishsolanki1990/Leetcode
/643_MaxAvgSubarray.py
757
3.84375
4
''' Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. Example 1: Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 ''' class Solution:...
195315f70d1ea0565494a8ea958d5ad2e1675f44
rifatmondol/Python-Exercises
/008 - [Strings] Contagem de Vogais.py
640
4.03125
4
#008 - Conta espaços e vogais. Dado uma string com uma frase informada pelo usuário (incluindo espaços #em branco), conte: #a. quantos espaços em branco existem na frase. #b. quantas vezes aparecem as vogais a, e, i, o, u. frase = input('Digite uma frase: ') letraA = frase.count('a') letraE = frase.count('e') letra...
07ad2860872539501b7aa59dc6f42af8ed79166d
ramangerami/Home_Manager
/detached_home.py
3,161
3.65625
4
from abstract_home import AbstractHome from sqlalchemy import Column, String, Integer, Float, DateTime class DetachedHome(AbstractHome): """ Child class of AbstractHome that creates a DetachedHome object """ FLOORS_LABEL = "Number of Floors" HAS_SUITE_LABEL = "Has Suite" DETACHED_HOME_TYPE = 'detach...
a899c345580eac52adb3168290bbc50d2718bf34
CalamariDude/youtube
/Intro to Multiprocessing - Python/extras/example.py
710
3.5625
4
import multiprocessing from multiprocessing import Process import time class Chef(Process): def __init__(self): Process.__init__(self) def season_chicken(self): #Takes 3 seconds to season chicken time.sleep(1) def cook_chicken(self): #Takes 10 seconds to cook the chicken ...
58f29876890d89495e98614e63b8af38f89e6874
dx19910707/LeetCode
/637(二叉树的层平均值).py
1,060
3.78125
4
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode :rtype: List[float] """ l = [] ...
d2c9bcff5fad9e301e48c22bec8bba955e119564
BaijunY/smart_alarm
/playground/reading_brightness.py
1,635
3.75
4
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) def read_photocell(): """reads the surrounding brightness using the connected photocell and transforms the values to a scale of 0 - 15 in order to adjust the displays brightness""" photocell_input_pin = 20 upper_limit = 400 lower...
46192aac5064b59a2207cd98529b0f6219d83bc0
kanglicheng/CodeBreakersCode
/from Stephen/google list/1110. Delete Nodes And Return Forest (DFS, pass).py
1,167
3.640625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]: def dfs(curNode...
3c6e10b1105d65dac324d5ca57ce231fa85dfdd9
Iso-luo/python-assignment
/practice/Lab4/Task2.py
2,253
4.03125
4
# -*- coding: utf-8 -*- # !/usr/bin/env python # @Time: 2020-05-12 9:35 a.m. """ Task 2 """ """ A. count the total number of words in the book, and the number of times each word is used. """ import string # 获取文本words列表 def get_words_list(): with open("/Users/a123/Desktop/paragraph.txt", "r") as f1: f2 = f...
bcbc8a755eb3cb4a7347c5d990420a26ef59a5c0
teoranss/Projects
/modul3/modul3.py
3,003
4.125
4
#is statement def return_true(): return "" def return_false(): return "" if return_true(): print('True') if return_false(): print('False') else: print('else exec') if return_false(): pass elif return_true(): print('elif exec') else: print('else exec') # if assignment operator var...
209f2e02040d29971821a1187917e71f43a1feff
AlecLjpg/PythonSetlist1
/Setlist1/Q6.py
248
3.75
4
x = input("Enter a string to be maniuplated: ") y = list(x) i = 0 while i <len(y): print (y[i]) i += 1 print("Sliced string: " + x[0:len(x):2]) print(x*100) z = input("Enter a second string to be concatenated: ") print(x+" "+z)
67cc67ed7f25b4423d653b9cd6ca1371f29df029
spdjuanse2/curso
/curso python/sintaxis/Herencia.py
1,258
3.71875
4
class veiculos(): def __init__(self,Modelo,marca): self.marca=marca self.Modelo=Modelo self.arrancar=False self.frenar=False self.acelerar=False def enciende(self): self.arrancar=True def acelera(self): self.arrancar=True def fre...
af36cbc8610864d2cb89ff98d1b73e2e16dcdc06
chaudhary19/SDE-Interview-Problems
/G_SetMatZero.py
874
3.796875
4
class Solution(object): def setZeroes(self, matrix): col0 = 1 row, col = len(matrix), len(matrix[0]) for i in range(row): if matrix[i][0] == 0: col0 = 0 for j in range(1, col): if matrix[i][j] == 0: matrix[i][0] = ...
df968808d75e531a215675949ffbee6b4df422f8
StanLong/Python
/01基础/02函数/闭包和迭代器.py
1,468
3.734375
4
# 闭包就是内层函数对外层函数(非全局)的变量的引用叫闭包。变量写在全局使不安全的,所以使用闭包,防止其他程序改变变量 # 闭包可以让一个局部变量常驻内存 # def func(): # name="沈万三" # def inner(): # print(name) # 在内层函数调用了外层函数的变量(name),这个就叫闭包 # # print(inner.__closure__) 打印结果不为空说明inner是个闭包 # return inner # ret = func() # ret() # 迭代器:节省内存,惰性机制,不能反复只能向下执行 # 可迭代对象 str, li...
9bc5ca6f603d6109173ee6af95307b7b9b40c784
salmaShahid/PythonCourse
/lec4ExerciseQ4-Q7.py
2,438
4.125
4
#Q4-Ask the user to enter a list containing numbers between 1 and 12. Then replace all of the # entries in the list that are greater than 10 with 10. lis = [] for i in range(0,12): z = int(input("enter num ")) lis.append(z) #list comprehension method p = 10 if p >10: pass else: w = [10 if x>1...
31b11d92f79b639dccbf4992b7fb09d93351080d
CristofherAndres/Codigos_Python
/Clase 14/funcion1.py
363
3.765625
4
#función para calcular el area de un triangulo # Def <- Indica que es una función def AreaTriangulo(base, altura): area = (base*altura)/2 return area ########################################## baseEntrada = int(input("Ingresa la base: ")) alturaEntrada = int(input("Ingresa la altura: ")) area = AreaTriangul...
1f335d241b2a1f77bd24b92ff38f0877d4aee130
JohnHaan/cloudtechpython
/20170327/DONE/sjhan/deduplicate.py
1,016
3.84375
4
# -*- coding:utf-8 -*- def dedupe(targets): resList = [] for target in targets: if target not in resList: resList.append(target) return resList def dedupe_dict(targets): resList = [] for target in targets: same = False if len(resList) == 0: resList.a...
2219e82af03b455217ee688fb56672b3279c1f89
lordjuacs/ICC-Trabajos
/Ciclo 1/discretas/ej1.py
443
3.9375
4
import time n = int(input()) suma = 0 start_for = time.time() for i in range(1, n + 1): suma += ((3*i - 2)*(3 * i + 1))**-1 end_for = time.time() diferencia_for = end_for - start_for print("suma con ecuacion: ", suma) print("tiempo del for:", diferencia_for) start_ecu = time.time() efe = n / (3 *n +1) end_ecu = tim...
65befcf71f714eb7406e3506813f4390162a403c
Fan-Wang-nl/ML_Course
/1_Feature_Engeneering/TextFeatureExtract.py
2,133
3.53125
4
# coding=utf-8 from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer def demo_CountVec(): # 文本文档列表 text = ["The quick brown fox jumped over the lazy dog."] # 构造变换函数 vectorizer = CountVectorizer() # vector = vectorizer.fit_transform...
a806637c6209cab267749e2eba86a978dcea174d
nik24g/Python
/main.py
808
4.53125
5
def add(x, y): """This function is use to add two numbers""" return f"The sum of these numbers is: {x +y}" def subtract(x, y): """This function is use to subtract two numbers""" return f"The subtraction of these numbers is: {x -y}" def multiply(x, y): """This function is use to multiply two numb...
ad3da83207b21957251129245a09693057588d5b
Abiseban147/OpenCV_Sample_Codes
/14_image_thresholding.py
1,263
3.75
4
import cv2 import numpy as np import argparse ap = argparse.ArgumentParser() ap.add_argument('-i', required = True, help= 'Path for the image') args = vars(ap.parse_args()) image = cv2.imread(args['i']) """ image thresholding is a task that convert the values of pixels -less than the given value to 0 -greater tha...
227241fbbac65bb52a95a992165e47eae869c833
pieterdavid/adventofcode2020
/day23.py
5,323
3.9375
4
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.7.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # Advent of code 2020: day 23 # # Problem [here](http...
0a7b661a177032f2f1ab14d4e77c0589f1f446d8
fmojica30/leetcode_practice
/test.py
754
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def combine(self, n, k): """ :type n: int :type k: int :rtype: List[List[int]] """ temp = [] self.result = [] position = 1 self.helper(n, k, position, temp) ...
30e47fb337341a4ba755952b7250ca99d0f5a65e
daniel-reich/ubiquitous-fiesta
/RoEn338P4xAf7mNNg_14.py
298
3.53125
4
def shortest_path(lst): pnts = [] for y, row in enumerate(lst): for x, n in enumerate(row): if n != '0': pnts.append((int(n), x, y)) pnts.sort() return sum(abs(x2-x1)+abs(y2-y1) for (n1,x1,y1), (n2,x2,y2) in zip(pnts, pnts[1:]))
1d7202c139806aa1dbfd63df7f2d8b94624b6433
WirachaLooknoo/workshop2
/string/f-string.py
142
3.78125
4
name = "Looknoo" age = 21 result = f" My name is {name}, and I am {age}" print("result", result) # Output: "My name is Looknoo, and I am 20"
2cd9247ebaa2249fe1794834d38f71f96a946c99
Matheus872/Python
/Learning/teste.py
75
3.59375
4
resp = str(input('Digite uma letra: ')).strip().upper()[1] print(f'{resp}')
3e8f37b8df4bed2dc17ac5105e7de0b4031090bf
kyledavv/lpthw
/ex31_practice.py
4,024
4.28125
4
import random #Basic explanation of the rules print("Here is the sport of tennis explained in a game.") print("""First, you spin a racquet to see who serves first. The winner of the racquet spin gets to choose whether to serve or return, or which side of the court they would like to start on.""") print("Which type of r...
d1d5064157538280748b162be27037f851781c0d
debaratidas1994/Python-Lab
/4/2.py~
712
3.921875
4
''' Given an input file, do the following using regular expression and create an output file. a) Remove extra whitespaces between two words. b) Insert a white space after the end of a sentence (after . or ? or !). c) First letter of each sentence should be upper case d) Remove consecutive duplicate words. ''' f...
fafbf66d42f700027bc5ba65da0ab4f5e4f34ff7
codefire53/DDP1
/UTS2016/UTS2016_5.py
376
3.65625
4
def string_match(str1,str2): #Set counter ke 0 ans=0 #Looping dua lapis untuk mengecek substring str1 dengan str2 for i in range(len(str1)-1): for j in range(len(str2)-1): #Jika ada substring yang sama, counter bertambah if(str1[i:i+2]==str2[j:j+2]): ans+=1 #Mengembalikan nilai counter return an...
3d7c2f642268da88e38dbe5cbfb2baaaeb36529c
natiem/python-1
/01-flow-control/loop_for.py
1,130
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Przykład - pętla for na różne sposoby. CC-BY-NC-ND 2020 Sławomir Marczyński """ # Generowanie tabeli pseudolosowych liczb z zakresu od 0 do 9. W każdym wierszu # ma być 10 liczb, wierszy ma też być 10. Uwaga: parametr end=' ' powoduje że # print nie wypisuje końca w...
fca31d06337dd388d59f0be9043bcab57a34266a
christianwcweiss/Udacity-Datastructures-and-Algorithms
/Chapter 3/Exercise 7 - HTTPRouter using a Trie.py
5,082
3.53125
4
class RouteTrieNode: def __init__(self, path, handler): self.path = path self.handler = handler self.sub_path = {} class RouteTrie: def __init__(self, root_path, root_handler): self.root_node = RouteTrieNode(root_path, root_handler) def insert(self, path_list, h...
136efc26c0d215234813382bcf0fdede83f955d0
rajdipa/Sentiment-Analysis
/extras/deprecated_NB.py
1,449
3.65625
4
# naive bayes from https://opensourceforu.com/2016/12/analysing-sentiments-nltk/ import csv import re import nltk #nltk.download('punkt') from nltk.tokenize import word_tokenize def readcsv(): with open('train.csv', newline='') as csvfile: spamreader = csv.reader(csvfile, delimiter=',') cnt = 0 ...
fa8c90288b9a841d2cb50b9863c1f04544dfde62
shuxinzhang/nltk-learning
/exercises/Chapter 03/03-18.py
421
3.75
4
# -*- coding: utf-8 -*- import matplotlib matplotlib.use('TkAgg') import nltk ''' ◑ Read in some text from a corpus, tokenize it, and print the list of all wh-word types that occur. (wh-words in English are used in questions, relative clauses and exclamations: who, which, what, and so on.) Print them in order. Are a...
8ee37497a745bc0ab88832315d43eccf47d14637
mgracioli/conexaoSQLitePython
/usuario.py
1,040
3.859375
4
#cria um modelo de usuário class Usuario(object): #método construtor def __init__(self, nome, telefone, email, cpf): self.__nome = nome #o __ informa que essa variável é do tipo private. Em python não existe variável privada, então, isso é só uma convenção para dizer que essa variável deve ser...
b8b2eb89716b3c2b1b3e20b63080030b90b2e652
KierstenPage/Intro-to-Programming-and-Problem-Solving
/Homework/hw1/kep394_hw1_q6.py
594
3.640625
4
print("Please enter your amount in the format of dollars and cents in two seperate lines:") dollarValue = int(input()) centsValue = int(input()) dollarToCentsValue = int(dollarValue * 100) totalCents = int(dollarToCentsValue + centsValue) quarters = int(totalCents/25) dimes = int((totalCents - (quarters*25))/10) nickel...
27c67d3d438f5b0e6480774b987459b1a73ccff5
zatzk/INF032A
/Atividade lista 9 python/q2.py
312
3.90625
4
nums = [] i=0 while i < 8: nums.insert(i, input("Digite o numero: ")) i+=1 i=0 while i < len(nums): x = nums[i] y = 2 print("numero {}: {}".format(i, nums[i])) for y in range (20): if(int(x)) == 6*y: print("multiplo de 6") y+=1 i+=1
d416388f7f60370051933676ee6369ab7e9a93ef
huttonb/BBB
/languageMaker.py
1,162
3.703125
4
""" Language parser for the pseudo-language""" class LanParser(): def __init__(self, spell): sad = False # The lexer works by giving it a set of code, it can use regex to determine whether or not it's a key-word def lexer(self, lex): keyword = True; # if Keyword send it to the corre...
f345ba23214923d21839b5c9477bfa8b000a8f52
pololee/oj-leetcode
/companies/uber/692.top-freq-words.py
1,113
3.765625
4
import heapq class Wrapper: def __init__(self, freq, word): self.freq = freq self.word = word def __lt__(self, other): if self.freq == other.freq: return self.word > other.word else: return self.freq < other.freq class Solution: def topKFrequent(s...
75c1394e4ab6d415953bdaafa720f89eed67282b
Rhylan2333/Python35_work
/精品试卷 - 06/P301-2.py
816
3.703125
4
# 问题2模板: # P301-2.py # 请在.....处填写多行表达式或语句 # 可以修改其他代码 def display(): fi = open("address.txt", 'r') content = fi.read() print(content) fi.close() menu = ["1. 显示所有信息", "2. 追加信息", "3. 删除信息"] flag = True while flag: for element in menu: print(element) ch = '' # 为了使非int输入也能运行后续if语块 try...
ef50244f76b08ec1f6b7a95621badb904ab8f609
PrateekCoder/Introduction-to-Python-For-Data-Science
/06_Controlflow_and_pandas/Pandas/script05.py
759
3.953125
4
''' loc (2) 100xp loc also allows you to select both rows and columns from a DataFrame. To experiment, try out the following commands in the IPython Shell. cars.loc['IN', 'cars_per_cap'] cars.loc[['IN', 'RU'], 'cars_per_cap'] cars.loc[['IN', 'RU'], ['cars_per_cap', 'country']] Instructions Print out the drives_right v...
9c705473225e354dff912c9952ebafb0da2d16e6
techkuz/PythonDataStructures
/week7 - tuples/sort_by_keys.py
139
3.734375
4
#1 d = {'a' : 10, 'b' : 1, 'c' : 22} print (d.items()) t = sorted(d.items()) print (t) for k, v in sorted(d.items()): print (k, v)
50f22144414a2e145aaf64e1d396275f20b2a7b3
Danis98/AdventOfCode2018
/day11/part1.py
545
3.59375
4
serial = int(open("day11.input", "r").read().rstrip()) def get_val(x, y): rackID = x + 10 power = rackID * y power += serial power *= rackID power = (power/100)%10 power -= 5 return power def get_square(x, y): return sum([get_val(x+i, y+j) for i in range(3) for j in range(3)]) best = ...
0e34da0cbdd4333ecde35450ee99c2b50b4b1374
ArthurFSantos/CursoemVideoPython
/Exercicios/ex014.py
137
4.03125
4
c = float(input('Informe a temperatura em °C: ')) f = 9 * c / 5 + 32 print('A tempteratura de {}°C corresponte a {}°F!'.format(c, f))
60d6178b19bb3864c70eecf705cce860999f502e
mitja-mandic/grid-peeling
/razredi.py
2,145
3.84375
4
import math class Tocka: def __init__(self, x, y): self.x = x self.y = y def kot_med_dvema(self, other): """Kot med dvema točkama v radianih""" if self.x != other.x: return math.atan((self.y - other.y) / (self.x - other.x)) else: return m...
520304a278f36679c025faf57fe87bf8b6e72fab
sarthakydv/COL759---Cryptography
/Assn1/Functions.py
6,659
3.84375
4
# Functions # Part 1 - Kasiski Method def divisors(n): # Finds all divisors, except 1 divs = [] for i in range(2, n + 1): if n % i == 0: divs.append(i) return divs # Finds all repeating substrings, poplulates a list of all divisors of distances # and returns sorted list of number of o...
79258cf3229385b0c03dd8c4a4ef25a51764bd4a
C-CHS-TC1028-021-2113/FUNCIONES_PREDEFINAS
/assignments/17RazonAurea/src/exercise.py
281
3.75
4
# Coloca aquí la librería de matemáticas def main(): #escribe tu código abajo de esta línea #phi = () / 2 #f = ("Número: ") #k = int(("Decimales a mostrar: ")) #resultado = round( , ) #print("Razón áurea: ") if __name__ == '__main__': main()
6f77f5a73db723c1377eb8278e48ea23945eae03
nthakkar/logit_regression
/nigeria/code/load_data.py
2,489
3.6875
4
'''Functions and tools for loading and preprocessing the data. The functions take the data from the .csv file and manipulate it as a pandas dataframe and as a numpy array.''' from __future__ import print_function import numpy as np import pandas as pd def ReadHeader(fname='_data/headers.csv'): '''Read the header f...
d8bf8623f9e4a58288909e1f05a7e172aea6e5a3
iamserda/cuny-ttp-algo-summer2021
/roseWong/assignments/slidingwindow/lc53/lc53.py
2,017
4.03125
4
# Problem Statement # # Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’. # Personal note - "Diary" - I am able to understand and explain the code after # Melissa walked us through a solution. Here I "copy" the code by typing it in per class' #...
58400455a1d233e0e4e54f85b411fb88129e3563
sharmasourab93/PythonDesignPatterns
/design_patterns/behavioural_design_pattern/template/template_pattern_example.py
1,604
4.21875
4
""" Python Don't Repeat Yourself principle violated. """ class Bus(object): def __init__(self, destination): self._destination = destination def bus_trip(self): self.start_diesel() self.leave_terminal() self.drive_to_destination() self.arrive_at_destinatio...
937905ae16a62a384c7312c050e0a966509d913a
y56/proving-ground
/py-dict-learn/tmp00.py
411
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 15 03:43:16 2019 @author: y56 """ r1dict = {1:'I',10:'X',100:'D'} r5dict = {1:'V',10:'L',100:'M'} for d in [1,10,100]: # d is for decimal base r1 = r1dict[d] # roman digit 1 r5 = r5dict[d] # roman digit 5 myDict = {1*d:r1, 2*d:r1*2,3*...
3bc0312c42f36cbba156447fc4d7aaaa10cebdd1
pawelszablowski/Python
/EduInf_waw/2.Liczby_Podzielne.py
573
3.6875
4
#W przedziale <a, b> liczb całkowitych należy wyszukać wszystkie liczby # podzielne przez jedną z liczb z zadanego zbioru P. a = int(input("Podaj początek zakresu: ")) b = int(input("\nPodaj koniec zakresu: ")) n = int(input("\nPodaj liczbę podzielników: ")) i = 0 j = 1 p = [] while i <= n: p.append(i) print(...
dfbc7df85fae70721c6d1faff8a038814715f467
Kotaro-Sekine/hippocampus
/Fruits_and_vegetables.py
3,683
3.734375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np class hebb: memory = [] memory_size = 0 def __init__(self, size): self.memory_size = size self.memory = np.reshape([0]*size**2, (size, size)) def learn(self, activity): if self.memory_size != len(a...
9829a596af82c41ed457a59a4010953b64802cdc
kunalkumar37/allpython---Copy
/boolean.py
911
3.84375
4
#boolean represnet one of two values:: #true false print(bool("hello")) print(bool(14)) class myclass(): def __len__(self): return 0 myobj=myclass() print(bool(myobj)) def myfunction(): return True print(myfunction()) def myfunction(): return True if myfunction(): print("yes") else: pri...
d0e5e798674bb7395cb00caa997b548b1160f5cd
xwzl/python
/python/src/com/python/learn/container/SetOperate.py
6,744
3.828125
4
import time # Python set 集合最常用的操作是向集合中添加元素、删除元素,以及集合之间做交集,并集、差集等运算。 # # 向 set 集合中添加元素 # # set 集合中添加元素,可以使用 set 类型提供的 add() 方法实现,该方法的语法格式为: # # setName.add(element) # # 其中,setName 表示要添加元素的集合,element 表示要添加的元素内容。 # # 需要注意的是,使用 add() 方法添加的元素,只能是数字、字符串、元组或者布尔类型(True 和 False)值,不能添加列表、字典、集 # 合这类可变的数据,否则 Python 解释器会报 TypeEr...
bcc4db183fbcb4ac3f48f122f7e88e7bc4e28bf2
MateuszJarosinski/ListaZaliczeniowaDSWPodstawyProgramowania
/2.py
810
3.578125
4
""" ubezpieczenie emerytalne: 9,76% * kwota brutto składka rentowa: 6,5% * kwota brutto składka wypadkowa: 1,67 * kwota brutto fundusz pracy: 2,45% * kwota brutto skłądka na Fundusz Gwarantowanych Świadczeń Pracowniczych: 0.10% * kwota brutto + pensja praownika brutto """ def employerCosts(kwotaBrutto): ube...
7f454e4cbb12313ad62e26fe64a599b522367c50
carlosalf9/InvestigacionPatrones
/patron adapter python/main.py
416
3.984375
4
""" main method """ if name == "main": """list to store objects""" objects = [] motorCycle = MotorCycle() objects.append(Adapter(motorCycle, wheels = motorCycle.TwoWheeler)) truck = Truck() objects.append(Adapter(truck, wheels = truck.EightWheeler)) car = Car() objects.append(Adapter(car, wheels = car.FourWhe...
f9fe70e9a9bc55774c0413ce1887d45d677bfd4f
nishaagrawal16/Datastructure
/leetcode/medium/3_longest_substring_without_repeating_chars_solution_1_n^3.py
839
3.84375
4
""" https://leetcode.com/problems/longest-substring-without-repeating-characters/ Complexity ---------- O(n^3) """ class Solution: def lengthOfLongestSubstring(self, s): if len(s) == 1: return 1 nonRepeating = [] result = [] for i in range(len(s)): for j in range(i, len(s)): if s...
26d83ed4129b7e64dfa0cf5fbb84f4440c8ee177
Aiden1997/Tkinter
/checkbutton.py
784
3.5625
4
#!/usr/bin/python # -*- coding: UTF-8 -*- import tkinter as tk window = tk.Tk() window.title('Choice') window.geometry('1080x720') l = tk.Label(window,bg='yellow',width=20,text='empty') l.pack() def print_selection(): if(var1.get()==1)&(var2.get()==0): l.config(text='I love Python') elif(var1.get()==0)&(var2.ge...
6e0bba0728418408f211ed4ad20abb5a2c0899f5
Hgser/NURBS-Python
/geomdl/_tessellate.py
6,552
3.578125
4
""" .. module:: _tessellate :platform: Unix, Windows :synopsis: Helper functions and algorithms for tessellation operations .. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com> """ from . import elements from . import utilities from . import ray # Initialize an empty __all__ for controlling imports __al...
872173a798f0085282921907b91bad088ef29798
NadjB/Juice_SCM_GSE
/juice_scm_gse/analysis/fft.py
2,083
3.65625
4
import numpy as np def __fact(window): """Computes the amplitude conpensation factor to apply to a FFT for the given window. Just equivalent to 1/RMS(window). Args: window ( iterable object): The windows to analyse. Returns: float: The compensation factor. """ return 1./np.sq...
86e6b610c4c0013e13b21b1e8061de5cf846a5d9
MSaaad/Basic-python-programs
/Sum of natural numbers.py
539
4.3125
4
#python program to find sum of natural numbers num=1 while True: #As long as the condition is true num=int(input('Enter the number you want for the sum:')) if num<0: print('Negative numbers are not Natural numbers') break elif num==0: print('0 is not a natural number') ...
14686fb68d17cef8f860c2b533e940dfee4fe91a
us19861229c/Meu-aprendizado-Python
/CeV - Gustavo Guanabara/exerc030.py
211
4
4
#030: ler um numero e dizer se é par ou impar num = int(input("Escolha um numero: ")) if num % 2 == 0 : print("este numero é PAR") else: print("este numero é IMPAR") print("obrigada por participar!")
128886d186124f6fe81347a427b77b24c9c078ef
MrBoas/PLC
/SPLN/aulas_kiko/aula2/ex3.py
564
4.28125
4
#!/usr/bin/python3 #Função que recebe nome de ficheiro e imprime linhas em ordem inversa ## Normal def reversePrint (file): for line in reversed(open(file).readlines()): # print (line, end='') #termina com nada print (line.rstrip()) #remove \n a direita (e espaço vazio?) # print (line) #te...
1c2742943251d0467da95fac73f0b5a68691c180
megarazor/INIAD_3
/Exercise4B/Week123/sum_between.py
193
3.84375
4
def sum_between(x, y): if x > y: tmp= x x= y y= tmp sum= 0 for i in range(x, (y + 1)): sum+= i return sum print(sum_between(10, 12))
0a2aa7b199fae04a10ee91835cdba5e027d6eef2
jiluhu/dirtysalt.github.io
/codes/contest/leetcode/most-frequent-subtree-sum.py
1,008
3.703125
4
#!/usr/bin/env python # coding:utf-8 # Copyright (C) dirlt # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from collections import defaultdict class Solution: def findFrequentTreeSum(self, root): ...
59cde930fc9d4eaab3601eac9af6fd027822b26c
kallyrhodes/LIS4930
/Module #5.1.py
158
3.75
4
def insert_sting_middle(str, word): length=len(str)//2 s=str[:length] + word + str[length:] return s print(insert_sting_middle('[[]]', 'Python'))
d245de137f14278a6698ee9e6ea002d00388223c
sshekhar1094/python_automations
/wikipedia.py
1,269
3.875
4
#!usr/bin/python # Python script to take in query and read out summary of corresponding wikipedia article # Uses google search intead of wiki search as google gives the most relevant article # External modules: requests, bs4, gtts import os import sys import requests from bs4 import * #web scraping from...
807194153dec6564c674e511f2ce051ccd47159f
enmorse/PythonCrashCourse2ndEdition.4-6.OddNumbers.py
/Main.py
236
4.28125
4
# Use the third argument of the range() function to # make a list of the odd numbers from 1 to 20. Use a # for loo to print each number. odd_numbers = [] for value in range(1, 20, 2): odd_numbers.append(value) print(odd_numbers)
14b27cfc1baa0848ab1b293207520abb9ec0c24d
Madhivarman/DataStructures
/leetcodeProblems/minimumCostsPerTickets.py
1,269
3.875
4
""" In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365. Train tickets are sold in 3 different ways: a 1-day pass is sold for costs[0] dollars; a 7-day pas...
bb13cbc6977ff93b41d2d98c1466df29dc3e9f54
rifatmondol/Python-Exercises
/073 - [O.O] Índices.py
452
3.6875
4
#073 - Write a Python program to find a pair of elements (indices of the two numbers) from a given #array whose sum equals a specific target number. class Indice: def soma(self, nums, alvo): dicNum = {} for i, num in enumerate(nums): if alvo - num in dicNum: return (dic...
71ff0be003016cbc2b3377e5e84bbe3f37b6258b
drishtipatwa/guessgame
/guessinggame.py
1,817
3.859375
4
from tkinter import * import random as r win = Tk() f = ("Algerian",16) win.title("Guessing Game") num = StringVar() l1 = Label(win, font= f,text = 'Enter your guess:') en = Entry(win,font = f,width=4,textvariable=num) l1.grid(column=0,row=1) en.grid(column = 1, row = 1) l2 = Label(win, font = f,text = 'Won / Lose',fg ...
7a3164827afabe4c29af630777a7e665ef88f8a3
ryedunn/Password-Generator
/registration.py
5,390
3.515625
4
import tkinter as tk def main(parent): parent = tk.Frame(parent) Register(parent) parent.mainloop() return None class Register: def __init__(self, parent, *args, **kwargs): self.parent = parent self.parent = tk.Toplevel() self.parent.title("Registration Form") se...
b2c4bb3420c54e65d601c16f3bc3e130372ae0de
nfarnan/cs001X_examples
/functions/TH/04_main.py
655
4.15625
4
def main(): # get weight from the user weight = float(input("How heavy is the package to ship (lbs)? ")) if weight <= 0: print("Invalid weight (you jerk)") total = None elif weight <= 2: # flat rate of $5 total = 5 # between 2 and 6 lbs: elif weight <= 6: # $5 + $1.50 per lb over 2 total = 5 + 1.5 ...
2a0d1c7081a02071ee439ab64493cc4594bc4db3
Sonu-soni/Python-Tutorial
/Projectf/tut2.py
250
4.03125
4
#If else x=int(input('Enter a your Age\n')) if(x>18 and x<25): print("You are eligible") elif (x>18 and x<25): print("Adult") elif(x>18 and x<50): print("Gents") elif(x>18 and x<75): print("Citizen") else: print('Senior citizen')
8fc5099ea34c6585151bd65a7bc18f516c7107ff
mbadayil/Ilm
/rangeSumquery.py
193
3.5625
4
l1=[-2, 0, 3, -5, 2, -1] def sumRange(array1, i, j): """ :type i: int :type j: int :rtype: int """ return sum(array1[i:j+1]) print(sumRange(l1, 0, 5))
b2e85ec22e5c7f6b98a3cc521c85a3ec5dd0a9ea
ScienceOxford/pyconuk-2018
/kitty/CHASSIS_receiver.py
2,565
3.5
4
from microbit import * import radio # Please tag us if used! # We'd love to see what you make: # @ScienceOxford ''' A1A-B1B are the four pins of the motor driver. A1A/B are for one motor, B1A/B are for the other motor Define which motor driver pin is connected to which micro:bit pin ''' AIA = pin14 AIB = pin13 BIA = ...
3a3ef762fc6a5bc1a75da40ae7bd1148497e9a3a
boknowswiki/mytraning
/lintcode/python/1436_flipping_an_image.py
716
3.75
4
#!/usr/bin/python -t class Solution: """ @param A: a matrix @return: the resulting image """ def flipAndInvertImage(self, A): # Write your code here if not A or not A[0]: return A m = len(A) n = len(A[0]) for i in range(m): ...
6ce7e5288054f69ee88237a1813bcfe2ddaee375
irukae/minecraft_ai
/Code_001.py
2,566
3.546875
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 16 19:12:23 2020 @author: Guillaume """ import pyautogui import time import pydirectinput import os os.chdir('D:\Projets\Minecraft') #screenWidth, screenHeight = pyautogui.size() # Returns two integers, the width and height of the screen. (The primary mon...
84685d919840eb41efcafacbc1071cb36215fbd4
lillyluo1995/aoc2020
/aoc/d05/main.py
2,330
4.03125
4
from typing import IO import math def calc_num(code, low, high): '''given a binary seat code and a total number of seats, calc the correct seat for this''' # check that it corresponds....need to add 1 bc 0 index assert math.pow(2, len(code)) == (high-low+1) if len(code) == 1: if code in ...
6c1b92fd810bb846c9beec2abef5d337e83cfd75
iAbhishek91/algorithm
/basics/13_tuples.py
506
3.828125
4
# they are very similar to list # key differences or unique features of tuples are: # - they are immutable, (no addition, del or update of elements from tuples). # - Its mostly used to store fixed data that never gonna change. # they are another type of data structure available in Python # they are represented by fir...
721477843134986d4017d3dfb31bef34d54be979
dthinkcs/ps
/old/recDP/13-waterArea/sol.py
2,601
3.9375
4
Don't show this again. Questions List C++ Go Java Javascript Python Theme: algoexpert algoexpert blackboard cobalt lucario midnight night oceanic-next rubyblue white Keymaps: default default emacs vim 00:00 ×Don't forget to scroll to the bottom of the page for the video explanation! Question:_ No changes made. ...
f6c5e328e5b949ec7ffe1220fad91508bb59391a
mnauman-tamu/ENGR-102
/part1.py
2,098
4.09375
4
# Program for Plotting Functions # # Plots a given function, first and second derivatives, and min/maxes # # Alexander M Bogdan # Patrick Zhong # Muhammad Nauman # Daniel Huck # November 19, 2018 # ENGR 102-213 # # Lab 12 Activity 1 - Program for Plotting Functions from scipy.misc import * import numpy as np import m...
96d44108fdbf50e952d6d46b6d5c3761f28fb3e5
masaya1123/PublicRepository
/notbose10_final/app.py
28,195
3.53125
4
import sqlite3 # Flaskからimportしてflaskを使えるようにする from flask import Flask, session, render_template, request, redirect import datetime import json # appという名前でFlaskアプリを作っていく! app = Flask(__name__) # シークレットキーの設定 sessionを使えるようにする app.secret_key = "sunabaco" # ルートの挙動調べる @app.route("/") def top_html(): return render_...
9904272efe1e47d4332e94fbb952c2951e1ba73e
skeerth1/Python-basics
/Functions.py
376
3.921875
4
# functions - starts with def def print_max(a,b): if a>b: print('a is maximun') elif a==b: print('a is equal to b') else: print('b is maximum') # directly pass the literal values print_max(3,4) x = 5 y = 7 # pass variables as arguments print_max(x,y) def sayHello(...
84e879ee20d5eaad43c34e35dc9712c87173368c
sgichuki/TidyTuesday-Py
/2021-08-24/lemurs.py
1,046
3.546875
4
# -*- coding: utf-8 -*- """ Created on Fri Sep 17 13:21:42 2021 @author: warau """ import pandas as pd import matplotlib import matplotlib.pyplot as plt #load data lemurs = ( pd.read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-08-24/lemur_data.csv",encodi...
931c8c2b81f6fff19a9459d32f57529ea1c2e753
kidoyen/Repository
/Project2/Versions/Version0/accessories_final.py
18,464
3.796875
4
from math import e, pi, cos, sin, sqrt, atan from pygame import * FPS=40 # Frames per second game will run at screenwidth=500 screenheight=850 dt_strd=1/float(FPS) # time constant used in physics calculations halfsinkwidth=80 # spacing of gap at bottom of screen (hal...
4b78c16e930c1c1abaaca88ffbb76ecdcbc98454
andreioprisan/AI
/HW3/Problem 2/problem2_DecisionTree.py
1,781
3.671875
4
# Braden Katzman - bmk2137 # Columbia University # Artificial Intelligence Summer 2016 # HW3 - Question 2 # Description: # Decision Tree classifier with param option max_depth from sklearn import tree from sklearn.cross_validation import cross_val_score from sklearn.metrics import accuracy_score # Builds and returns ...
4e68bbd2abf13d31f8297d4899d3554a581c3d9d
Mirannam/while_for
/task7.py
302
3.875
4
names = ('Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',) names1 = [] for i in range(1,13,2): names1.append(names[i]) names1= set(names1) print(names1)
7de5f90f71e3925b6f031374ceade16dcab7aa98
zeel1234/mypython
/ma007/Practical 9/Personclass.py
2,580
3.75
4
class Person: def __init__(self,nm = "",gen = "",bdat = 1996): self.name = nm; self.bdate = bdat; self.gender = gen; def set(self,nm = "",gen = "",bdat = 1996): self.name = nm; self.bdate = bdat; self.gender = gen; def get(self): return (self...
85aefd0c245c502db7c5bf62bdfdb62084e84bd4
salemgyn/python-3montes
/3montes.py
5,774
3.59375
4
#coding: utf-8 #! /usr/bin/env python # #Autor: Melky-Salém <msalem@globo.com> #Descrição: 3 montes(ainda não descobri o nome) é um jogo de lógica # a regra é, voce deve escolher um monte e tirar quantas # peças quizer, desde 1 até todas, com isso em jogo até # dois montes vão sumir, quem pegar a ultima peça ganh...
d5202858c2b27c4e45c4066f373bd4c2dc65f04e
sabzi1984/Intro-to-Algorithms
/Dijkstra with heapq.py
1,579
3.5625
4
import heapq def val(pair): return pair[0] def id(pair): return pair[1] def dijkstra_heapq(G,v): heap = [ [0, v] ] dist_so_far = {v:[0, v]} final_dist = {} while len(final_dist) < len(G): while True: w = heapq.heappop(heap) node = id(w) dist = val(w) ...
a6d3d5804930d20e5a9688dc546a083bd10cb9f9
shenjinrong0901/python_work
/学习阶段历程/homework5.2.py
520
3.609375
4
car='subaru' print("Is car='subaru'? I predict Ture.") print(car=='subaru') print("Is car='audi'? I predict False.") print(car=="bmw") print("\n") name='harden' print("Is the most value player in NBA harden? I predict Ture.") print(name=='harden') print("Is the most value player in NBA james? I predict False.") print(n...
8aeb9bf06e38802a130c2c4b2b69a01e4e80adaa
Iiridayn/sample
/Coderbyte/42-NumberSearch.py
454
3.890625
4
# Challenge: sum single digit numbers in string / by # letters (not chars). 10 points, 8 mins # I didn't know about sum(array) yet def NumberSearch(str): nums = filter(lambda c: c.isdigit(), str) letters = filter(lambda c: c.isalpha(), str) sum = 0 for x in nums: sum += int(x) return int(round(float(sum)...
ec980ca61ac6441501bc3d4f1a4753313f758279
leeson9394/learngit
/Reverse_number_v2.py
320
3.609375
4
import sys input_num=input("Enter an integer N that 1 <= N <= 1000000000: ") if 1 <= input_num <= 1000000000 bin_input=[int(i) for i in str(bin(input_num))[2:]] bin_input.reverse() bin_output=int(''.join(map(str,bin_input)),2) print "Output integer: ",bin_output else: print "Input number not in range"
5335785ca1e92d1b5fdc31818659c42fc8223918
gaohaoning/leetcode_datastructure_algorithm
/LeetCode/Tree/98.py
4,494
4.15625
4
#!/usr/bin/env python # coding:utf-8 """ 98. 验证二叉搜索树 给定一个二叉树,判断其是否是一个有效的二叉搜索树。 假设一个二叉搜索树具有如下特征: 节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。 示例 1: 输入: 2 / \ 1 3 输出: true 示例 2: 输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4...
6b7d9a33a03f003c8d368cedafbc906efba81e6f
chacham/learn-algorithm
/acmicpc.net/10866/10866.py
2,287
3.65625
4
class deque: def __init__(self, size): self._start = 0 self._end = 0 self._size = 0 self._maxSize = size self._deque = [None] * size def push_front(self, item): if self._size >= self._maxSize: return self._deque[self._start] = item self...