blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
ab013dc6733098ae51cf35365dd05d4ac8f91947
HenriqueCostaSI/Python
/docstring.py
497
3.8125
4
""" Documento funções com Docstring """ # Exemplosc def diz_oi(): """Uma função simples que retorna a string 'oi'""" return 'Oi!' print(diz_oi.__doc__) def exponencial(numero, potencia=2): """ Função que retorna por padrão o quadrado de 'numero' ou 'numero' à 'pontencia' :param numero: Número q...
676105f223f87a5f485e414bd743a6bf700da0eb
cobymotion/PythonCourse
/001_Introduccion/010_nominas.py
556
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 28 02:24:47 2019 @author: coby_ Practica 10: uso de librerias """ import datetime hoy = datetime.date.today(); mes = hoy.month year = hoy.year if hoy.day>15: if mes==12: mes = 1; year+=1 else: mes+=1 quincena = datetime.date(y...
6723a4837f896e60dd3e2532b1aa57c40e711151
cobymotion/PythonCourse
/001_Introduccion/modulotec.py
701
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 10:46:05 2019 @author: DevTequilaUser """ import datetime def calculonomina(fecha): mes = fecha.month year = fecha.year if fecha.day>15: if mes==12: mes = 1; year+=1 else: mes+=1 quincena = ...
d03b8f341d0833bb88fb67c39ff8e13b47eee2a4
cobymotion/PythonCourse
/001_Introduccion/002_enteros.py
506
3.609375
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 23 14:42:29 2019 @author: Luis Cobian Practica 1: Numericos """ x = 52 print(type(x)) # Da como resultado int x = 0o52 print (x) #considera su entrada como octal y lo muestra en decimal print(type(x)) # Da como resultado int x=0xA0F print (x) #considera su entrada c...
5cd0f9526a8ec3172b1f76b62fb3e25c50926208
MegaIng/simple-language-example
/step2/simple_ast.py
1,629
3.734375
4
from __future__ import annotations import operator from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Dict, Callable class AST(ABC): """The base class of all AST-Nodes. Will contain abstract methods.""" @abstractmethod def calculate(self) -> float: """Calcul...
b8e5075db58c27aa23c039769b1dbbb325a72a98
nkechiiregbulem/Animations
/Rotating Sphere.py
445
3.65625
4
#Please install Processing, then run code to get a rotating sphere from math import pi from random import randint def setup(): global sphere_size size(400, 400, P3D) sphere_size = randint(100, 200) def draw(): global sphere_size background(1) translate(width / 2, height / 2, 0) rotat...
17e2874cf224c030648fcedb6d5c9e263e75cc86
renero/seqfinder
/descriptive/seq_numusers.py
2,349
3.546875
4
"""count_users Given a file with patterns found (results) and a sequence file, returns the number of users matching each pattern. """ __version__ = '0.2' __author__ = 'J.Renero' import csv import sys import getopt import regex as re def checkargs(args): """ Check the command line arguments and return a dic...
7cc1365642108e0cb35f4219997ff51a1c47a180
Haestad/datatek
/oving5/led_board.py
2,589
3.578125
4
""" This module contains the class for the LED board """ from time import time, sleep from GPIOSimulator_v5 import GPIOSimulator, charlieplexing_pins class LEDBoard: """ This class contains the LED Board. """ GPIO = GPIOSimulator() # (high, low) LED_MAP = [(0, 1), (1, 0), (1, 2), (2, 1), (0, 2), (2, 0...
c9dffd73d61c4efdc1f599c1506811708c904708
danialaswad/ncb
/src/eip/dynamic_router/DynamicRouter.py
239
3.5625
4
class DynamicRouter(object): def __init__(self, plumber, params): self.plumber = plumber self.params = params def route(self, exchange): raise NotImplementedError("Subclass must implement the route method")
aa388535cc492bcd76caa2b637e9823d9c138fba
mpyrozhok/coding-challenges
/projecteuler/python/001.py
230
3.96875
4
def IsMultiple(number, base): if number%base == 0: return True else: return False summary = 0 for num in range(1, 1000): if IsMultiple(num, 3): summary += num elif IsMultiple(num, 5): summary += num print summary
c06c9a20e768312aa1c922df7ff0afdc8d34bb2a
mpyrozhok/coding-challenges
/codeeval/python/hard/spiral.py
608
3.640625
4
import itertools def transform_to_spiral(n, m, matrix): l = [] for i in xrange(m): row_length = m - i column_start = m - i - 1 l.extend(matrix[:row_length]) del matrix[:row_length] l.extend(matrix[column_start::row_length]) del matrix[column_start::row_length]...
7e2a0672c9a13e6de54ab1d41dfcaa97713d4eb5
alastra32/DS-Unit-3-Sprint-1-Software-Engineering
/second_attempt_sc/acme_test.py
823
3.5625
4
#!/usr/bin/env python import unittest from acme import Product class AcmeProductTests(unittest.TestCase): """Making sure Acme products are the tops!""" def setUp(self): """setup for default values""" self.prod = Product('Test Product') def test_default_product_price(self)...
720e19447e1cf3af160f59c807704f471753759b
zzzzzshPig/upgrade
/Python/base/comprehension.py
791
4.09375
4
list1 = ['lisa', 'pinzi', 'front', 'a', 'b', 'c'] list2 = [1, 2, 3] # list 过滤掉长度小于或等于3的字符串列表,并将剩下的转换成大写字母: print([r.upper() for r in list1 if len(r) > 3]) # list 计算 30 以内可以被 3 整除的整数: print([r for r in range(30) if r % 3 == 0]) # tuple 生成一个包含数字 1~9 的元组 print((r for r in range(1, 10))) # set 计算数字 1,2,3 的平方数: print({r...
d5519a856e796a8925f85db56ce6dfb583b41ab1
RodiMd/Python
/CaloriesCount.py
679
4.09375
4
#Calories from fat and carbohydrates #calories from fat = fat grams x 9 #calories from carbs = carb grams x 4 def fatNcarbCalories(): fatGrams = input('Enter grams of fat consumed per day ') carbGrams = input('Enter grams of carb consumed per day ') caloriesFromFat = float(fatGrams) * 9.0 ...
b148ce412d17e42ce3efbb822dc3b48bd99bfd22
RodiMd/Python
/Insure.py
322
4.0625
4
#How Much Insurance #should ensure your property for atleast 80 percent of the cost #to replace it costToReplace = input('Enter the amount it would cost to replace it ') def minInsurance(): amountToInsure = 0.8 * float(costToReplace) print ('amount to insure is %.2f' %amountToInsure) minInsurance()...
5cdfa102cff1c3210258e57c45eb8ba103e90481
RodiMd/Python
/RomanNumeralsRange.py
1,937
4.125
4
#Roman Numerals #prompt user to enter a value between 1 and 10. number = input('Enter a number between 1 and 10 ') number = float(number) def main(): if number == 1: print('The value entered ', number, 'has a roman equivalent of I') else: if number == 2: print('The val...
9bc3f4e6f2f9827ab3c5b96680d902468d4dbbcf
RodiMd/Python
/NumberAnalysisProgram.py
1,003
4.0625
4
#Number Analysis Program #Enter a set of numbers and save it to a list then get max and min, average and total def main(): try: numberList = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] numberListCpy = numberList index = 0 sumNumbers = 0 average = 0 ...
184286b4b369017ab8adfb871f4eb593fd5ea168
RodiMd/Python
/MathQuiz.py
792
4.09375
4
#Math Quiz #two random numbers to be added and the student should #be allowed to respond, if correct then congrats #if answer is incorrect - learn some math import random #if want to use random number generation def main(): ranNum1 = random.randint(1,1000) ranNum2 = random.randint(1,1000) prin...
9edb72ec105c350557d29d802059cddc379602d5
RodiMd/Python
/TestAverage&Grade.py
3,400
4.15625
4
#Test Average & Grade #user enter five test scores #display the letter grade for each score & then average all # have to think about this program using loops #this code works ##score1 = int(0) ##score2 = 0 ##score3 = 0 ##score4 = 0 ##score5 = 0 ##sc1 = int(0) ##sc2 = int(0) ##sc3 = int(0) ##sc4 = int(0) ...
cc0955631b2f2a028bea0541f573b80ed56fe527
RodiMd/Python
/PerformCalcs.py
300
3.796875
4
#Perform operations, #variables a, b, c a = 10 b = a + 2 print (b) a = b * 4 print (a) b = a/3.14 print ('%.2f' %b) #reduces final value to two decimal places a = b - 8 print ('%12.2f' %a) #makes final value to equal to two dec places and inserts it in a 12 character wide space
151c03c498a2cf012dfafd027a248d2adc760645
RodiMd/Python
/Driver'sLicenseExam.py
2,687
3.9375
4
#Driver's License Exam #20 multiple choice questions #correct answers:a,c,a,a,d,b,c,a,c,b,a,d,c,a,d,c,b,b,d,a #store correct answers in a list, read student's answer and store #the answers in a another list, create text file to test app #message (pass or fail), correctly answer 15/20, then display the #correct an...
19d948529b4da0ca728c55653e413629487b606f
RodiMd/Python
/MonthlyCarCost.py
690
4.1875
4
#Automobile Costs #ask user to input automobile costs including: loan payment #insurance, gas, oil, tires, maintenance. loanPayment = input('Enter auto monthly payment ') insurance = input('Enter insurance cost ') gas = input('Enter monthly gas cost ') oil = input('Enter monthly oil cost ') tires = input('Ente...
1aae2e1953e77f361f01f4907675b0b2a0b9255f
RodiMd/Python
/TotalSales.py
1,162
3.59375
4
#Total Sales Week = ['Monday', 'Tuesday', 'Wednsday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] def main(): dailySales = open('dailySales.txt', 'w') for day in Week: print(day) sales = input('Enter sales for each day of the week ') dailySales.write(sales + '\n') ...
19be8d9e73b668b2039865214c3bb7b1937c1924
RodiMd/Python
/convertKmToMiles.py
383
4.4375
4
#Kilometer Converter #write a program that converts km to mi #ask the user to enter a distance in km distanceKilometers = input('Enter a distance in km ') distanceKilometers = float(distanceKilometers) def conversionTokilometers(): miles = distanceKilometers * 0.6214 print ('The distance entered in kil...
54598c277ca109f2d6f2a41323ec59a2f12229d7
suhwanoh/Source_By_Jason
/Python/PyCharm/thenewboston_practice/classes and objects.py
391
3.765625
4
class Enemy: life = 3 def attack(self): print("ouch!") self.life -= 1 def check_life(self): if self.life <= 0: print("I'm dead!") else: print("Oops! I'm still Alive. " + str(self.life) + " life left.") enemy1 = Enemy() enemy1.attack() enemy...
20a73064501f1b7567dd927559602d7999eef10a
itspedruu/bruteforce
/main.py
2,237
3.921875
4
import sys # Constant Variables (can be changed manually before startup) CARAC = '1234567890' MIN_CARAC = 1 MAX_CARAC = 6 FILENAME = 'wordlist.txt' password = [0 for x in range(0, MIN_CARAC)] file = open(FILENAME, 'w') current_password_count = 0 max_possibilities = sum([len(CARAC) ** current_carac for current_carac i...
e216735ba7223147981fe1113a298737664dba15
sheng-jie/Learning.Python
/douban_spider/doubanspider/book_wall.py
1,374
3.5625
4
# encoding:utf-8 """豆瓣图书9分绑定图片墙""" import os import math from PIL import Image def generate_books_wall(): """ 生成图书墙 """ curr_path = os.path.dirname(__file__) # 当前文件文件夹所在目录 parent_path = os.path.dirname(curr_path) # 上层目录 image_path = os.path.join(parent_path, 'books', 'full') images = o...
404d95fa9c248dc9abb1ea6c03a1d44d87fac1c5
pkjayk/hydropathy-scores
/autocorrelation.py
531
3.640625
4
#import numpy import numpy as np #method usage: #method works by using the call acf(list) to return a list of acf scores #e.g. ACF_scores = acf(list_of_values) def acf(series): n = len(series) data = np.asarray(series) mean = np.mean(data) c0 = np.sum((data - mean) ** 2) / float(n) def r(h): ...
0c9dbcb25ef7b122b5ceaa0e7fa72a06687b8fbf
matt-bowen/montecarlo
/q2.py
858
3.5625
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 8 13:47:12 2017 @author: Matthew """ import random as rand import numpy as np import matplotlib.pyplot as plt def func(y): return np.power(np.sin(1/y), 2) def integrate(samples, upper): n = 0 xmax = upper ymax = 1 for i in ran...
196325aa1fc60de988b039b7a5d0207de2886bf7
dannybrowne86/Tic-Tac-Toe
/ttt/ttt/computer_logic.py
7,668
3.984375
4
import numpy def next_move(ttt): """"This is the primary logic for the unbeatable computer. a simple strategy has been implemented that results in the computer, at worst, losing to the oponent, regardless of whether the computer makes the first mark or not. """ # get board in 2D array ...
a34024a9b81221d0c4702985d74e45be47ef0aea
chengxq129/selenium7th
/day5/csvFileManager4.py
2,522
3.59375
4
#1.导包 import csv import os class CsvFileManager4: def read(self,filename): list = [] #声明一个空列表 #2.指定csv文件的路径 #path = r'C:\Users\51Testing\PycharmProjects\selenium7th\data\test_data.csv' #这样生成的path路径有一个缺点,可移植性比较差 #在公司中,一个项目往往是多人协作完成的,有人可能将项目放在自己的C盘,有人放在D盘 #项目换了不同的路径,...
e9a08730b666c00a18af2703c773490112769cc7
ashidagithub/ASD_WinForms
/try_controls_1/try5_radio_check_btn/try_radio_btn1.py
1,517
3.515625
4
# -*- coding: UTF-8 -*- # ------------------------(max to 80 columns)----------------------------------- # author by : (学员ID) # created: 2019.11 # Description: # 初步学习 WinForm 编程 ( Radio Button ) # ------------------------(max to 80 columns)----------------------------------- import tkinter as tk from tkinter impo...
180f7f0ade9770c6669680bd13ac8f2fd55cc8c7
devprofe/python
/guia2_whiFunEjercicio2.py
273
3.953125
4
def raizCubica(numero): r = pow(numero,(1/3)) return r numeros = [] raices = [] for x in range(5): numeros.insert(x, float(input("Ingrese Numero: "))) raices.insert(x, round(raizCubica(numeros[x]),3)) print("Numeros: ", numeros) print("Raices: ", raices)
012f04a108ad5bb0d1d6a2a939389d9ed6ba9736
devprofe/python
/ej1_clases2406.py
433
4.125
4
#DECLARAR UNA LISTA VACIA numeros = [] #COMO LLENAR UNA LISTA SOLO CON APPEND #numeros.append(35) #numeros.append(28) #numeros.append(12) #INGRESAR NUMEROS EN UNA LISTA MEDIANTE INSERT Y FOR. #for i in range(5): #numeros.insert(i, float(input("ingrese numero:"))) #INGRESAR NUMEROS EN UNA LISTA MEDIANTE APPEND Y ...
65d47333837656a9b720b5947769619f1363f867
zakolm/software_engineering
/lab_00/iarray.py
320
3.515625
4
# Кол-во максимальных элементов в массиве. def GetMaxCount(Arr, N): Max = Arr[0] Count = 1 I = 1 while (I < N): if (Arr[I] > Max): Max = Arr[I] Count = 1 else: if (Max == Arr[I]): Count += 1; I += 1 return Count
16245246fbf58dc6eeaa1ab339953637f2aa22fa
CoffeeCreamer435/PythonGraafschap
/Arrays/opdracht1.py
201
3.515625
4
import random items = ['fiets','kroeg','kreng','school','python','grens','friet'] item_to_show = random.choice(items) print('op positie', items.index(item_to_show), 'staat het woord' , item_to_show)
c97caee3094698057b030db0a3c1db20e389a349
Luiznfe/Novo-TCC
/funcs2.py
4,345
3.796875
4
from population import Population import random from plot import Plot # local search # 1 - recebe como entrada uma solução # 2 - recupera as rotas (sem o deposito) # 3 - realiza as operações (simultaneamente) # 4 - compara a nova distancia com a anterior # fontes http://www.decom.ufop.br/marcone/Publicacoes/PRVCES-ANP...
880712ee73fee3dff18203c11f8cef4722b883e5
tarunjohnmathew/test
/Data Structs.py
214
3.609375
4
# Student = ["Grade","Student ID","Credits"] # Class = {"Jeff": Student, "Bob": Student} # print(Class) Student = {"grade" : 90, "name" : "jeff"} print(Student["grade"]) # Class = [Student, Student] # print(Class)
66079189a84d8cd1c08a3b9eee964f6a116395d4
h8rsha/tip-calculator
/main.py
441
4.125
4
if __name__ == '__main__': print("Welcome to the tip calculator.") total_bill = input("What was the total bill? ") tip_percentage = input("What percentage tip would you like to give? 10, 12 or 15? ") people_count = input("How many people to split the bill? ") total_amount = (float(total_bill) / int(...
f03e23dbdadb6efeb9b42f30dcd02c8907a31ffc
sumrdev/Code-Portfolio
/OBJECTORIENTED/Geometry/line2D.py
1,409
3.546875
4
import math from dot2D import Dot2D class Line2D: def __init__(self,dot1,dot2): self.dot1 = dot1 self.dot2 = dot2 self.length = self.calcLength() def printLine(self): print((self.dot1.x,self.dot1.y),(self.dot2.x,self.dot2.y),self.length) def editDot(self,newDot1,newDot2): ...
b97a5731f3f30d6ba293eeb3c9d5f8d6385299c9
sanssssd/Permanent-Calendar---Python-tkinter
/calendar.py
3,109
3.875
4
import tkinter # 平瑞年 def leap_year(year): if year % 4 == 0 and year % 100 != 0 or year % 400 == 0: return True else: return False # 月份的天数 def getMonthDays(year, month): days = 31 if month == 2: # 确定2月天数 if leap_year(year): days = 29 else:...
c615290bd8143a156a1c6f903abe6d55638dc416
shelltitan/PHYS20161
/assigment_final.py
15,549
4.1875
4
#Write a Python program that reads in the data from the file GBplaces.csv (see last week's practice) and presents it visually using #the matplotlib module in whatever amazing way you can dream up! I encourage you to be as creative as possible and marks will be #awarded for this. If you just plot an x-y graph of e.g. ...
b5e6f4348b9445639f2696caac83c9a761200cc0
zchiam002/vecmc_codes_zhonglin
/nsga_ii/nsga_ii_para_imple_evaluate_objective.py
2,310
4.15625
4
##Function to evaluate the objective functions for the given input vector x. x is an array of decision variables ##and f(1), f(2), etc are the objective functions. The algorithm always minimizes the objective function hence if ##you would like to maximize the function then multiply the function by negative one. def ...
5e4e2fdc4c1037667821e5f23ad88ccc62f7de18
Salcazul/ComputerElective
/Quiz2.py
622
4.21875
4
#Name name = raw_input("What is your name?") #Last Name last = raw_input("What is your last name?") #Class classname = raw_input("What class are you in?") #Year of birth year = input("What is your year of birth?") #Calculate current age age = 2015 - year print "You are", age, "years of age." #Computer grade 1S s1 =...
47236d90ef3f0ac50a020f1f65e6826bdd7c4ebb
Salcazul/ComputerElective
/HelloWorld.py
318
3.96875
4
print "Hello World" print "My name is Salvador. \nThis is Python" print 2015 #Printing an integer print "2015" #Printing a string print 3.1416 #Printing a floating point number print 2+2 print 2-2 print 2*2 print 3/2 print 3%2 #Modulus is the remainder of a division print 10%3 print 3.1416 * 2.8 print 3.1416 * 2
494c80b2fd387a6fa5d7d8a15461116026489a06
jfthuong/tech-notes
/docs/post/Python/Modules/ArgParse/test.py
1,244
4.0625
4
from argparse import ArgumentParser, SUPPRESS def do_something(options): '''A function that does something''' print(str(options)) if __name__ == '__main__': prog = "test_ArgParse" help_string = """\ Purpose: Check how to use ArgParse """ parser = ArgumentParser ( description=hel...
bee6ce35e4fd805d24605cbc281ecad0dba07498
saroarjahan/askfm-crawler
/askfmcrawler-0.1.5/askfmcrawler-0.1.5/askfmcrawler/entities.py
834
3.734375
4
class User: def __init__(self, _id, name): self.id = _id self.name = name def __repr__(self): return f'User({self.name})' def __str__(self): return self.__repr__() def __eq__(self, other): return self.id == other.id and self.name == other.name class Article:...
8a66633f1c65017095de383388de87af5dc3e914
MFarooq786/Python_Matplotlib
/simpleplot.py
520
3.953125
4
#load library import matplotlib.pyplot as plt#for plots import numpy as np #for arrays and lists import math#needed for pi #We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library. x=np.arange(0,math.pi*2,0.05)#values for x-axis y=np.sin(x)#values for y-axis ...
88dd7e5b517f6d65fe63c0f239bc0b1a4d91d347
txxxxc/python-sample-files
/try_except_name.py
310
3.53125
4
sum = 7600 while True: num = input('How many people') if num == 'q': print('exit') break try: price = round(sum / int(num)) except Exception as error : print('error') print(error) else : if price < 0 : continue print(price)
5689b4f689a3e64dc4d5960a24fdcca105fc0d8e
txxxxc/python-sample-files
/try_except.py
201
3.78125
4
while True: num = input('How many') if num == 'q' : print('exit') break try: price = 120 * int(num) print('total', price) except: print('error')
570f728565301a3cef87b11dc054d24670a49816
yennanliu/udacity-nanodegree-data-analyst
/Machine-Learning/datasets_questions/explore_enron_data.py
2,629
3.75
4
#!/usr/bin/python """ starter code for exploring the Enron dataset (emails + finances) loads up the dataset (pickled dict of dicts) the dataset has the form enron_data["LASTNAME FIRSTNAME MIDDLEINITIAL"] = { features_dict } {features_dict} is a dictionary of features associated with that person...
bb1a0cf9bfac0df9f564a285309cc90ee2f22ba0
saikalyan552/CSEE5590-490-Python-and-Deep-Learning-Programming
/icp-2/icp-2(2).py
415
3.8125
4
from collections import deque str1 = input("enter the string") li = list(str1.split(' ')) stack = li queue = deque(li) #stack stack.append("Ram") stack.append("Iqbal") print(stack) print(stack.pop()) print(stack) print(stack.pop()) print(stack) print(stack[-1]) #queue print(queue) queue.append("Akbar") print(queue)...
08b584400a3cfb14ca9f228b103ea95b5ef4268d
analuisadev/Campinas-Tech-Exercises
/ex12.py
141
3.734375
4
print ('{:=^40}'.format(' SEJA BEM VINDO(A) ')) name = str(input('Informe o seu nome: ')) print (f'Olá {name}, o seu nome é muito bonito!')
aaca96577191f204f3fd9d25a26fef7a7078c0cf
wsy858/python-demo
/python2-grammar/model1/TestList.py
2,114
4
4
# -*- encoding=utf-8 -*- """ Created on 2016年9月30日 列表 @author: evan """ # 1、使用下标索引来访问列表中的值 list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1] print "list2[-1]: ", list2[-1], list2[-3] # 2、使用append()方法来添加列表项 list2.append(8) print list...
5e84425db688196c62f455b7e656ecca4e74199f
wsy858/python-demo
/python2-grammar/model4/json/TestJson.py
551
3.953125
4
# -*- coding: utf-8 -*- import json # 将已编码的JSON字符串解码为Python对象 def decode_json(): str = '["foo", {"bar":["baz", null, 1.0, 2]}]' print type(str) print str obj = json.loads(str) print obj print type(obj) # 将Python对象编码成JSON字符串 def encode_json(): obj = ["foo", {"bar": ["baz", None, 1.0, 2]}...
6615541379ff77286757052c8bcf5ab8253cc605
wsy858/python-demo
/python2-grammar/model4/Test_datetime.py
376
3.84375
4
# -*- coding: UTF-8 -*- import datetime # 显示当天 today = datetime.date.today() print today # 时间差值 timedelta = datetime.timedelta(days=1) yesterday = today - timedelta # 显示昨天 print yesterday cur = datetime.datetime.today() # 显示最近5个小时的日期 for i in range(5): timedelta = datetime.timedelta(hours=(i + 1)) print cur ...
ed218f5025544474394bed9e161c987edd884a3e
yk2684/Codewars
/7kyu/Highest-and-Lowest.py
410
4.125
4
#In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number. #Example: #high_and_low("1 2 3 4 5") # return "5 1" #high_and_low("1 2 -3 4 5") # return "5 -3" #high_and_low("1 9 3 4 -5") # return "9 -5" def high_and_low(numbers): num_list = sorted(...
89074f4afad000944e11ed9fcc508ecc69e42233
yk2684/Codewars
/8kyu/Return-negative.py
435
4.65625
5
#In this simple assignment you are given a number and have to make it negative. But maybe the number is already negative? #Example: #make_negative(1); # return -1 #make_negative(-5); # return -5 #make_negative(0); # return 0 #Notes: #The number can be negative already, in which case no change is required. #Zero (0)...
42879bb5f155aca7652dd4ceda8008621b8a7882
Pawan142001/Calculatiion-of-area-of-a-circle
/radius.py
132
4.34375
4
PI = 3.14 R= float(input("Enter the radius of the circle : ")) area = PI*R*R print("%2f" %area ) Enter the radius of circle as 1.1
4a7c8ff3d94cb6cc354d1f0fec370d83c855fe81
sukiyy/18.1_python_intro
/loop.py
76
3.6875
4
num = 0 while num <= 100: print (num) num= num+10 print("all done")
60df423972c1f49a383df35a13141c02dc66e2b1
RingOV/gis-weather
/utils/diff_versions.py
561
3.5625
4
#!/usr/bin/env python3 def diff(cur_ver, new_ver): cur_ver = fix_length(cur_ver) cur_ver = fix_digits(cur_ver) new_ver = fix_length(new_ver) new_ver = fix_digits(new_ver) if int(''.join(new_ver)) > int(''.join(cur_ver)): return True else: return False def fix_length(ver): w...
f4980eb15419d97417ee72e8697d669068171ca1
takumi-kawaguchi/python_lesson
/src/chap2/compare.py
313
4.0625
4
x, y, z = 1, 2, 3 if x < y < z: print('true') if x < z > y: print('true2') a = 'book' if a is not None: print('object exists') items = ['book', 'note'] if 'book' in items: print('there is a book') count = {'book': 1, 'note': 2} if 'note' in count: print('there is a note')
c1e96ca1166fecb2eba621c1c27b5e59e27da0e1
KristianHolme/theHardWay
/ex43.py
10,073
3.625
4
from sys import exit from random import randint from textwrap import dedent from os import system loop = True class entity(object): def __init__(self, weapon, skill): self.weapon = weapon self.skill = skill class Scene(object): def enter(self): print("This scene is not yet configure...
1bb34f3c3e1ad26f0edbc573836f177039502c22
mur78/PythonPY100
/Занятие4/Лабораторные_задания/task2_5/main.py
280
4
4
def poliand(): n = int(input("Введите число: ")) s = str(n) reverse_s = ''.join(s[::-1]) if s == reverse_s: print("Палиндром") else: print("Нет") if __name__ == "__main__": # Write your solution here poliand()
aa728e9d908799a73950d45e7ff22611f08d98e3
mur78/PythonPY100
/Занятие1/Лабораторные задания/task1_3/main.py
129
3.671875
4
# Напишите ваше решение q = float(input('Ввод а: ')) v = float(input('Ввод n: ')) c = q ** v print(c)
3c05ebeb6520dd08e06f6536d42a3b0f272e5396
mur78/PythonPY100
/Занятие1/Домашнее_задание/task3/main.py
184
3.71875
4
# Напишите ваше решение a = int(input("Число 1 :")) b = int(input("Число 2 :")) c = int(input("Число 3 :")) list_n = [a, b, c] print (min(list_n))
e5d81164a8c9c1af1429820ad8b9b695ba2a3a09
mur78/PythonPY100
/Занятие2/Лабораторные_задания/task1_2/main.py
196
3.875
4
# TODO A = int(input("Введите чило А: ")) B = int(input("Введите чило B: ")) result = A % 2 == 1 and B % 2 == 1 if result: print("Числа A и B нечетные")
12deb91945b7856aa818ec40b2bef8f007445389
mur78/PythonPY100
/Занятие5/Практические_задания/task1/main.py
509
3.75
4
if __name__ == "__main__": matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] for row in range(len(matrix)): for col in range(len(matrix[0])): print(matrix[row][col], end=" ") print() table = [ [i*j for j in range(1,10)] for i in range(1,10) ] fo...
803e6d84560ca207aa809bce383ad7d618c396c0
hwngenius/leetcode
/learning/In_place_Reversal_of_LL/61.py
1,324
3.59375
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head is None or k==0: return head count=0 h=head while h.next and count!=k: h=h.next ...
4b0d971941ee826e1d57f8306de6b1bf6ca16363
hwngenius/leetcode
/learning/Sliding_Windows/904.py
951
3.53125
4
from typing import List from collections import defaultdict class Solution: def totalFruit(self, tree: List[int]) -> int: ans, current_sum = 0, 0 left, right = 0, 0 count = 0 data = defaultdict(int) while right < len(tree): while count < 3 and right < len(tree):...
77f6771e24a55d522cc67125c24b28efae1d803d
hwngenius/leetcode
/learning/Dynamic Programming/5_dp.py
633
3.515625
4
class Solution: def longestPalindrome(self, s: str) -> str: n=len(s) ans="" dp=[[False for _ in range(n)]for _ in range(n)] for l in range(n): for i in range(n): j=i+l if j>=n: break if l==0: ...
d5bc562ad6fe6e0585b67a74445e93dd30686e54
hwngenius/leetcode
/learning/fast&slow_poionters/143.py
1,137
3.671875
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reorderList(self, head: ListNode): if head: slow, fast = head, head.next while fast and fast.next: slow, fast = slow.next, fast.next.next ...
ca3af03a0096f2e3dc27ffb46fcfb1106008ef14
hwngenius/leetcode
/learning/fast&slow_poionters/234.py
1,212
3.625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def isPalindrome(self, head: ListNode) -> bool: if not (head and head.next): return True def reserve(head: ListNode) -> ListNode: if head: head_next = h...
3fd36283fd6dbfb49ba52280d6aae5cf397d97dc
hwngenius/leetcode
/course/19.py
453
3.71875
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: a,b=head,head while n>0: b=b.next n-=1 if b is None: ...
189a9d0cd82d8055502afd18cd57df75ac8479b7
hwngenius/leetcode
/learning/fast&slow_poionters/203.py
562
3.5
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: h = l = ListNode(0) while head: if head.val != val: l.next = head l = l.next ...
46ae499f948b6fa698ca30c3604c32d65efc33fb
hwngenius/leetcode
/course/35.py
438
3.953125
4
from typing import List class Solution: def searchInsert(self, nums: List[int], target: int) -> int: left,right=0,len(nums)-1 if nums[right]<target:return len(nums) while left<right: mid=(left+right)//2 if nums[mid]<target: left=mid+1 els...
869803fba5c703f11e32087c86a085d51c7d9bfb
hwngenius/leetcode
/hot_100/94_stack.py
623
3.796875
4
from typing import List class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: stack=[] ans=[] while root or len(stack)>0: ...
12f2d2bcf07d5f466c709c2ba6e3569c08f1dbf2
hwngenius/leetcode
/hot_100/146.py
1,692
3.703125
4
class Node: def __init__(self,key,val): self.key=key self.val=val self.next=None self.pre=None class LRUCache: def __init__(self, capacity: int): self.capacity=capacity self.cache={} self.head=Node(0,0) self.head.next=self.head self.head.p...
2da3a655d46ab775cfe31fc6ed92e033295ee418
hwngenius/leetcode
/learning/In_place_Reversal_of_LL/206.py
510
3.90625
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def reverseList(self, head: ListNode) -> ListNode: if not (head and head.next): return head ans=self.reverseList(head.next) head.next.next=head head.next=None ...
b1b970347dc59bb9cb78db573dc8e44a440a7001
hwngenius/leetcode
/hot_100/102.py
841
3.75
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root:return [] ans=[] level=[] level.append(root) ...
fff444b74d82d9e45255483a17b549f8e029687a
hwngenius/leetcode
/course/110.py
705
3.828125
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def height(self,root:TreeNode)->(int,bool): if root is None: return (0,True) left_height,left_balance=self.height(root....
4331b7249e9e7c4fc5f2562e26eea745e503c41a
hwngenius/leetcode
/hot_100/240.py
938
3.625
4
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: if not matrix:return False row,col=len(matrix),len(matrix[0]) r=c=0 while r<row and c <col: if target==matrix[r][c]: return True if target<matrix[r][c]: ...
04ba9eaf9e9f5ce1aea1ccc47ac7dc7238bc628b
hwngenius/leetcode
/每日一题/509.py
339
3.546875
4
class Solution: def fib(self, n: int) -> int: if n==0:return 0 a,b=0,1 for i in range(1,n): a,b=b,a+b return b # 执行用时: # 40 ms # , 在所有 Python3 提交中击败了 # 63.74% # 的用户 # 内存消耗: # 14.6 MB # , 在所有 Python3 提交中击败了 # 15.74% # 的用户
a8e8fffb25c7d02fbc053e513337ba9823b1aa88
Renegate/object-detection
/src/utils/argparser.py
519
3.625
4
from constants import Constants import argparse import sys class ArgParser(object): """ Parse args in main """ parser = argparse.ArgumentParser( description='A python program trains or serves object recognition models.') parser.add_argument(Constants.MODE, help='Running mode', choices=Cons...
5bfa598c566aa73ca2a56e42fc06666225e6571c
billsu2013/pyschool
/09-08.py
431
3.5625
4
# -*- coding: utf-8 -*- """ Created on Tue Apr 24 22:27:07 2018 @author: dell """ def shiftByTwo(*args) : sh=[] if len(args)==1: sh.append(args[1]) if len(args)>=2: sh.append(args[-2]) sh.append(args[-1]) for i in range(len(args)-2): sh.append(...
1fd31276c363b1ddf3884f26e7a941ad24e08381
billsu2013/pyschool
/06-23.py
504
3.59375
4
# -*- coding: utf-8 -*- """ Created on Sat Apr 21 23:24:48 2018 @author: dell """ #def getNumbers(num): # Ge=[] # for i in range(num,0,-2): # a=i*i # Ge.append(a) # for j in range(0,num+2,2): # a=j*j # Ge.append(a) # return Ge # #b=getN...
da62206ded7d47b21731a015e7c07e4716ac150c
billsu2013/pyschool
/06-24.py
306
3.671875
4
# -*- coding: utf-8 -*- """ Created on Sun Apr 22 10:50:01 2018 @author: dell """ def getSumOfFirstDigit(num): a=0 b=[] for i in range(len(num)): b=int(str(num[i])[0]) a=a+b return a num=[12, 23, 34, 45, 56] c=getSumOfFirstDigit(num) print (c)
c9ee7bbaacb5943af53f69123580cb97f627fd8d
billsu2013/pyschool
/06-12.py
419
3.796875
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 20 17:10:10 2018 @author: dell """ def matrixDimensions(m): c=len(m[0]) r=len(m) for i in range(len(m)): if len(m[i])!=c: return 'This is not a valid matrix.' break return 'This is a '+ '%d'%c +'x' +'...
8af763799fd311e20b514e3d7e227c48f79f5ff4
billsu2013/pyschool
/06-16.py
348
3.609375
4
# -*- coding: utf-8 -*- """ Created on Fri Apr 20 23:34:23 2018 @author: dell """ la =range(10, 2, -2) lb= range(1, 10, 3) print (la) print (lb) a=[] lenght1=len(la) length2=len(lb) for i in range(lenght1): a.append(la[i]) for j in range(length2): a.append(lb[j]) b=sorted(a,reverse...
dde7dfce0d10f336e130f0b61ed9f9785abcefdd
billsu2013/pyschool
/04-03.py
406
3.90625
4
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 12:33:01 2018 @author: dell """ def generateNumber(start,end,step): gen=[] if step<0: for i in range(start,end-1,step): gen.append(i) return gen if step>0: for i in range(start,end+1,step): ...
5c50e3387dd4db9bce58b4abad63d142d4bcb79c
bonuz/other
/automatetheboringstuff/removeLists.py
169
3.65625
4
spam = ["hello", "hi", "howdy", "heyas"] spam.remove("hi") print(spam) spam.append("hello") print(spam) # will remove the first "hello" spam.remove("hello") print(spam)
bd74c00fab6c856858920398200d0f5b42f26792
bonuz/other
/automatetheboringstuff/sortLists.py
539
3.9375
4
spam = [2, 5, 3.4, 1, -7] spam.sort() print(spam) spam = ["ants", "cats", "dogs", "badgers", "elephants"] spam.sort() print(spam) spam.sort(reverse=True) print(spam) # sort modifies the list, dont assing like this spam = spam.sort() # cant sort a list that has both number and string values # sort orders by ASCCIbetical...
4fc50d95cf6394eb37388ab03e73a4f209a5dfdc
Abdulkadir78/Python-basics
/q39.py
306
4.09375
4
''' Write a program to guess a number that is randomly selected between 1 and 100 ''' import random random_number = random.randint(1, 100) guess = int(input('\nEnter a number: ')) if guess == random_number: print('Correct answer!\n') else: print(f'Wrong answer, the number was {random_number}')
4639fada97674fcece2a42bebec800450916d083
Abdulkadir78/Python-basics
/q42.py
1,292
3.8125
4
''' Given a sorted list with duplicates and a target number 'n',find the range in which the number exists(represented as a tuple(low, high),both inclusive.If the number does not exist in the list, return (-1, -1)) Example: Input: [1, 2, 3, 4, 5, 3, 6] n = 3 Output: (2, 5) ''' l = [1, 2, 3, 4, 5, 3, 6] def find_num(l...
c4d957205efb049acc46b4cc892ef0fb32b8607f
Abdulkadir78/Python-basics
/q16.py
690
4.34375
4
''' Use a list comprehension to square each odd number in a list. The list is input by a sequence of comma-separated numbers. Suppose the following input is supplied to the program: 1, 2, 3, 4, 5, 6, 7, 8, 9 Then, the output should be: 1, 9, 25, 49, 81 ''' numbers = input('Enter comma separated sequence of numbers: '...
278c75115f7d16cbb3b881b0ea0ec90d22eca62a
Abdulkadir78/Python-basics
/q7.py
565
4.21875
4
''' Write a program which takes 2 digits, X, Y as input and generates a 2-dimensional array. The element value in the i-th row and j-th column of the array should be i*j. Example Suppose the following inputs are given to the program: 3, 5 Then, the output of the program should be: [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0,...
f28b75916667124438f2c9e661078cf25ac70277
Abdulkadir78/Python-basics
/q35.py
663
4.15625
4
''' Please write a program which counts and prints the numbers of each character in a string input by console. Example: If the following string is given as input to the program: abcdefgabc Then, the output of the program should be: a, 2 b, 2 c, 2 d, 1 e, 1 f, 1 g, 1 ''' string = input('Enter a string: ') l = [] for c...
6c00c83aa92613f1b01f0b7e381ec08109d6da7e
ostanleigh/winter
/tryingPy.py
467
3.8125
4
print("hello world") print("this is from November 23rd") def Test(a): if a == 1: return a, else: print(a) count = Test (a-1) return count print(count) Test(32) def gcdIter1(a, b): for x in range(a, -1, -1): if a % x == 0 and b % x == 0: print ("...
fa07223afda6315ad1e260abea3f4691f7b919b6
maax23/hangman
/hangman.py
1,861
3.84375
4
import random ,words ,os,time max = print("coded by max23 \nenjoy it =)\nsubscribe philolearn") time.sleep(1) random.seed() health = 6 choosedword=[] guessedword = [] def play(): def sendresult(): for x in range(len(choosedword)): print(f"{choosedword[x]}",end="") pr...
ad5ab43a406038a63ce69b62c7df061daa6ceb14
FintelmannLabDevelopmentTeam/pygmh
/pygmh/dataset/image_set.py
2,076
3.515625
4
"""Model for a set of images.""" from typing import Set, Iterable from pygmh.model import Image class ImageSet(Set[Image]): """Represents a set of images.""" def __init__(self, images: Iterable = None): super().__init__() if images is not None: for image in images: ...