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
523a9daac912b78cde2c9f61bfbf024fb932bb08
sudheendra02/competetive_programming
/exam2/queue.py
605
3.734375
4
def method(listt): listt.sort() listt=listt[::-1] # print(listt) for i in range(len(listt)-1): if(listt[i][0]==listt[i+1][0]) and (listt[i][1] > listt[i+1][1]): temp = listt[i+1] listt[i+1]=listt[i] listt[i]=temp out = [] for i in listt: out.insert(i[1], i) return print(out) # Input: method([...
2505cc4b428d7c616160d837eb7708b8607a9446
sudheendra02/competetive_programming
/week1/day5/rotation.py
1,427
3.921875
4
import unittest def rotate(words,l,h): mid = int((l+h)/2) # print(mid) # if(words[l][0]>words[h][0]): if((words[mid])>(words[h])): # print("hii") return rotate(words,mid+1,h) elif((words[mid])<(words[h])): # print("bye") return rotate(words,l,mid) elif(words[mid]...
b3cdf85262cd51763c0935e96eeb3f1844077d71
sudheendra02/competetive_programming
/week1/day2/temp.py
630
3.59375
4
global a,minimum,maximum,mean,count minimum,maximum,mean=-99999,-9999,0.0 count=0 a = {} def insert(temp): global a,minimum,maximum,mean,count if temp not in a: a[temp]= 1 else: a[temp]=a[temp]+1 if (temp<minimum): minimum=temp elif (temp>maximum): maximum=temp mean = mean+temp count=count+1 def max1()...
86a15c8b5cb5f008855ea98e325cacde875239d9
gajendra394394/python
/rectabglemn.py
190
4.125
4
def rectangle(m,n): for i in range(m): for j in range(n): print('*', end=' ') print() x=int(input("enter value of m")); y=int(input("enter value of n")); rectangle(x,y);
93499a2e7b83799bfacf10c91477ecf03da60cb8
gajendra394394/python
/counting chart.py
125
3.671875
4
s=input("enter string:"); for i in range (len(s)): if s.count(s[i])>1: print(s.find(s[i]),end=" ");
57b07d75c2d81356bab342880380353f6debbc25
meginks/data-structure-notes
/Queues/queues.py
2,152
4.15625
4
class ListQueue: def __init__(self): self.items = [] self.size = 0 def enqueue(self, data): """add items to the queue. Note that this is not efficient for large lists.""" self.items.insert(0, data) #note that we could also use .shift() here -- the point is to add the new t...
134217b6176f66d81e3c9818f3ebb69261c4a627
MichalMichniak/405676_lab_1_metody_numeryczne
/main.py
2,656
3.53125
4
import math import numpy as np import numpy.linalg as linalg #checking if obj can be represented as float: def is_number(s): try: float(s) return True except ValueError: return False def cylinder_area(r:float,h:float): """Obliczenie pola powierzchni walca. Szczegółow...
0ad7c909077ed319f59c62fdd552ee11728aef7d
JonathanBrunssen/python-beginner
/day-4/multi-color-spiral.py
347
4.03125
4
import turtle t = turtle.Pen() turtle.bgcolor("black") colors = [] addColor = input("type in a basic color. ") while addColor != "": colors.append(addColor) addColor = input("Type a basic color or press enter to see a spiral") for x in range(1000): t.pencolor(colors[x%len(colors)]) t.forward(x...
e93fb3209cf6af3ec35022b182bcbcabda79ce04
myoniles/minimax
/src_old/board.py
3,108
3.984375
4
class Board: # __won = False def __init__(self): self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] # used to change the state of the board def changeState(self, xpos, ypos, char): if (self.board[xpos][ypos] != ' '): return False else: ...
706346e2d20d4421def932264a6e34f7b86f3347
onp/ProjectEuler-py
/Problem002.py
524
3.765625
4
# Project Euler Problem #2 # Even Fibonacci Numbers ''' Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not...
56607d7bd78682dfc28621cd0208648775107d65
onp/ProjectEuler-py
/Problem023.py
2,046
3.859375
4
# Project Euler Problem #23 # Non-abundant sums ''' A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called def...
efce0e6324ad35c87816f876331e447682fdad43
onp/ProjectEuler-py
/Problem020.py
377
3.75
4
# Project Euler Problem #20 # Factorial digit sum ''' n! means n x (n - 1) x ... x 3 x 2 x 1 For example, 10! = 10 x 9 x ... x 3 x 2 x 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! ''' import math as mt Answer= sum([int(x) f...
4a8ba7c09505557f054ceb6e685b4ba77c27c393
onp/ProjectEuler-py
/Problem034.py
626
3.703125
4
# Project Euler Problem #34 # Digital factorials ''' 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. Find the sum of all numbers which are equal to the sum of the factorial of their digits. Note: as 1! = 1 and 2! = 2 are not sums they are not included. ''' from math import factorial digitFactorials =...
57dac925187ac9730ecaf6a1d33a19e2189bcac5
agomez1953/Taller_semana_santa
/suma_Vectores.py
5,415
3.890625
4
from producto_escalar import * import math vectores = {} def ingresar_vector(): """ Permite leer un vector del usuario :return: list of num el vector ingresado por el usuario """ vector = [input('¿Cual es el nombre de su vector? ')] while True: num = input('Ingrese su escal...
e286b58153f3aca5b588ec2c1b9fb13bcda2d3da
Prestonhall31/python_projects
/toPrime.py
787
3.875
4
''' Task : Given a List [] of n integers , find minimum mumber to be inserted in a list, so that sum of all elements of list should equal the closest prime number . Notes List size is at least 2 . List's numbers will only positives (n > 0) . Repeatition of numbers in the list could occur . The newer list's sum sho...
281080ba1252de2b4fe3768de6c7a3ebe4d2ee94
rschled/yahtzee
/Yahtzee.py
1,868
3.703125
4
import random x_axis = """+-------+""" two_in = """| o o |""" one_in = """| o |""" nan_in = """| |""" threet = """| o |""" threeb = """| o |""" def print_dice(arr: [int]): #top for i in range(len(arr)): print(x_axis, end=' ') print() #top row for i in ran...
0cd98f21d56a0a60f102d880dea4a88759a2bbca
hyperion-mk2/git
/flipAndInvertImage.py
602
3.578125
4
class Solution: def flipAndInvertImage(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ for index in range(len(A)): datalen = len(A[index]) for index2 in range(len(A[index])//2): A[index][index2],A[index][datalen-1-ind...
1eff6b6c415b0a0046679f73f2aabd6ace3609e1
hyperion-mk2/git
/Unique Paths.py
498
3.8125
4
class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ if(m==1 and n==1): return 1 elif(m==1): return self.uniquePaths(self,m, n-1 ) elif(n==1): return self.uniquePaths(self,m - 1,...
3dde3c6f74b194239bbde9667ecda89e13339450
hyperion-mk2/git
/Remove Duplicates from Sorted Array.py
489
3.765625
4
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ deletenum = 0 index = 0 while index < len(nums) - 1: if(nums[index] == nums[index+1]): nums.pop(index) deletenum += 1 ...
dc373529186bcb94aeb9c5452fa5d3ec53fbf326
sabakethar/Python-Learning
/assignments/unique.py
566
3.703125
4
#! /usr/bin/python import os, time name=None names=[] ncount={} while name!="": os.system("clear") name=input("Enter name:") if name!="": names.append(name) ncount[name]=names.count(name) print(("Name "+name+" entered "+str(ncount[name])+" time(s)").rjust(20)) time...
18a6d309e1055cf8a6e19a4a160e985c9deb6388
sabakethar/Python-Learning
/tmp/ex4.py
796
3.5625
4
#! /usr/bin/python class Communicate: def __init__(self): self.msg_list={} self.prompt_count=0 def get_message(self, prompt): self.prompt_count+=1 prompt=prompt+" "+str(self.prompt_count)+":" self.msg_list[prompt]=input(prompt) return self.msg_list[prompt...
d511cdde3c540cbb77f4fb574a686deac1a4acfa
sabakethar/Python-Learning
/functions/x.py
289
3.84375
4
#! /usr/bin/python def func1(a, b): x=[1,2,3] def func2(a, b): nonlocal x x.append(1) for i in x: yield i for i in x: print(i, end='') print() return func2 x=func1(1,2) for i in x(1,2): print(i)
9c0f2d1643920790b747a2607a8a7c1a665c82c3
sabakethar/Python-Learning
/functions/f2.py
233
4
4
#! /usr/bin/python def func(a): return lambda v: print(a, v) x=func(10) x(10) #--------------------------------------# def func1(): y=10 func1.x+=10 print(func1.x, y) func1.x=0 for i in range(10): func1()
c88276db924e9955da9d2fb3265085e48911c4ea
bhoj001/python_network_programming
/demo2_server.py
906
3.984375
4
# demo2_server.py # purpose: simple server program in python to know network programming # date : august 21st /2018 # the client for this is demo1_client import socket import sys # create TCP/IP socket sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # define host host = 'localhost' # define communication...
d50303e4f133f70dbcca339854be988cc3ba482a
ravisousag/ravisousag
/python-fundamentos/jokenpo.py
1,757
3.65625
4
from random import randint from time import sleep itens = ('Pedra', 'Papel', 'Tesoura') computador = randint(0,2) print('O computador escolheu {}'.format(itens[computador])) print(''' Suas opções: 0 - Pedra 1 - Papel 2 - Tesoura ''') jogador = int(input('Insira sua jogada: ')) print ('JO') sleep(1) print('KEN') slee...
ba2464a63611c012c5d046da23bdb86ef2f91e83
ravisousag/ravisousag
/python-fundamentos/builtins.py
339
3.828125
4
#builtins #print("Jamilton") #print( type("Jamilton") ) #print( dir() ) """ Conversão de tipos Tipos:str,int, float, list """ #print( type([10,5,9,7]) ) #print( 1 + int('2') ) #print( 1 + float('2.5') ) #numero = 9 #print( str(numero) + '50' ) """ Conversão automática """ #print( type(10 / 2) ) print( 2 + False )#Tru...
8b0866ebca3b4f84f8d2462ff17431b3aea6ec0e
Anupam1234567/siet-code
/program 05.py
263
3.765625
4
# Program no. 05 # Python Program to Solve Quadratic Equation import cmath a,b,c=map(int,input().split()) distance = (b**2) - (4 * a*c) a1 = (-b-cmath.sqrt(distance))/(2 * a) a2 = (-b + cmath.sqrt(distance))/(2 * a) print(' Quadratic Equation\n',a1,a2)
6ae5ce690efe8a56361b60ee09fb5de1af50c842
nyamzy/Password_Manager
/password_manager_test.py
4,835
3.859375
4
import unittest from password_manager import User, Credentials class TestUser(unittest.TestCase): ''' Subclass for testing the cases for the user class behaviours ''' def setUp(self): ''' Set up method that runs before each test case ''' self.new_user = User("John", "Nyamweya", "nyamzy", "johnn...
c97c3a6f79d14e479b4c7780b9a873919f7dddcb
mtils/ems
/ems/singletonmixin.py
18,977
4.09375
4
""" A Python Singleton mixin class that makes use of some of the ideas found at http://c2.com/cgi/wiki?PythonSingleton. Just inherit from it and you have a singleton. No code is required in subclasses to create singleton behavior -- inheritance from Singleton is all that is needed. Singleton creation is threadsafe. ...
62137569ff281fdec07eda9b02a8e5c80ad2df6d
mtils/ems
/ems/notification/abstract.py
887
3.5
4
from abc import ABCMeta, abstractmethod class FormNotifier(object): """ A FormNotifier displays messages in a form. If this leads to write the messages into a session (http), to the view (templates) or a widget (pyqt) """ __metaclass__ = ABCMeta @abstractmethod def showMessage(self, ke...
6e112b1a49de50d9fc8ce8e577e40210f1a98239
Kyle-ai/P4E
/Ex6/Ex6.5.py
314
3.59375
4
#Take the python code in str = 'X-DSPAM-Confidence:0.8475' #use find and string slicing to extract the portion of the string after the #colon charecter. Then use float() to convert the string to a flaoting point. str = 'X-DSPAM-Confidence:0.8475' apos = str.find(':') newpos = float(str[apos +1:]) print(newpos)
33a8eac1ee8f41cff48e7f55b6c500a3b493a4b3
Kyle-ai/P4E
/Ex9/Ex9.3.py
644
3.859375
4
# Write a program to read through a mail log, build a histogram using a #dictionary to count how many messages have come from each email adress, #and print the dictionary. fname = input('Enter file name: ') emails = dict() try: fhandle = open(fname) for line in fhandle: if line.startswith('From '): ...
d3db7c1c92ad7ea0f4267981c089717a1b0954c0
Kyle-ai/P4E
/Ex5/Ex5.1.py
609
4.0625
4
#Exercise 1: Write a program which repeatedly reads numbers until the user #enters “done”. Once “done” is entered, print out the total, count, and average #of the numbers. If the user enters anything other than a number, detect their #mistake using try and except and print an error message and skip to the next #number...
0928a181c9940bc2dc5bbdbd616c49c5cdc29db6
Kyle-ai/P4E
/Ex6/Ex6.2.py
198
3.9375
4
# Given that fruit is a string, what does fruit[:] mean? fruit ='banana' newfruit = fruit[:] print(newfruit) #The out come is 'bananas'. So the whole string is copied to the new variable #newfruit.
7edcbedba8d62b6cd9ff9c9ac1acd14f4a80edbe
Kyle-ai/P4E
/Ex12/Ex12.4.py
715
3.5625
4
#Change the urllinks.py program to extract and count paragraph (p) tags from the #retrieved HTML document and display the count of the paragraph as the output #of your program. Do not display the paragraph text, only count them. Test your #program on several small web pages as well as some larger pages. import urllib....
18626a0e6de0cf2ed1678820949c3a21c143d369
MasterNobikan/First_Python_Scripts
/deck.py
1,786
3.65625
4
from random import * class Card: def __init__(self, suit, rank): # constructor self.suit = suit self.rank = rank def getSuit(self): return self.suit def getRank(self): return self.rank def blackJackValue(self): # specific to blackjack if self.rank in ['J...
2f280877ac163808625670d16e765e2c021d30e6
MasterNobikan/First_Python_Scripts
/easter.py
781
3.96875
4
"""Program from class computes the date of Easter years 1954, 1981, 2049, 2076 are adjusted """ def compute_easter(year): # compute needed values a = (year % 19) b = (year % 4) c = (year % 7) d = ((19*a + 24) % 30) e = ((2*b + 4*c + 6*d + 5) % 7) day = 22 + d + e # check choice is a...
ec434c5a13ddbd2a68973c3143d422f6c1fa0ba2
MasterNobikan/First_Python_Scripts
/Entry.py
136
3.890625
4
name = input("What is your name: ") print("Hello ", name) answer = input("Do you want me to open the door (y/n)?") print("ok then...")
2ba25c690771ad43b5b0fa4256aea0b6cef4a8ad
MasterNobikan/First_Python_Scripts
/trianglestars.py
127
3.9375
4
x = '*' for i in range(0, 5): print(x) x = x + '*' print('MY NAME IS JT') for i in range(5, 0, -1): print(x[0:i])
4f9d5a1df660012b4d362e7ea51b0156508180a9
MasterNobikan/First_Python_Scripts
/year.py
184
3.921875
4
import time # this program prints the current year def year(): return int(time.time() / 60 / 60 / 24 / 365 + 1970) def main(): print('the current year is', year()) main()
f1e0c02aefb4abe372e1dcd4e098e9bc1f941323
asAshura/OpsModules
/IP_20171103.py
5,741
3.6875
4
''' 1. get Windows local IP address - method 1 2. get Windows local IP address - method 2 3. get Linux local IP address 4. get Linux MAC address 5. IP address format check 6. Convert Interger to IP with socket 7. Convert Interger to IP without socket 8. Convert IP to Interger without socket 9. IP translation w...
319d2d9261047ba9218b7b696fb33ad7fc1895a3
neelindresh/try
/VerificationFunctions.py
2,729
4.1875
4
import numpy as np import pandas as pd import operator def check_column(df, ops, first_mul, col_name, oper, value): ''' This function will return the list of valid and invalid rows list after performing the operation first_mul * df[col_name] oper value ex: [ 1*df['age'] >= 25 ]. ''' valid_...
f05e5ae4f5835a34854719c7389617a8c2060ddd
realivanivani/python_visualization
/intro_dataviz_seaborn.py
4,587
4.15625
4
# Statistical ploting using Seaborn # # Import plotting modules import matplotlib.pyplot as plt import seaborn as sns # Plot a linear regression between 'weight' and 'hp' from dataframe 'auto' sns.lmplot(x='weight', y='hp', data=auto) # Display the plot plt.show() # Generate a green residual plot of the regression...
1ab9c7b7e17ae75d46b56abb4ab4796c03a7c222
rhuselid/CS_123_project
/code/time_series.py
22,531
3.796875
4
from datetime import date, datetime, timedelta, timezone import json import numpy as np ## Final: Start / End date for data in dd-mm-yyyy format START_DATE = "01-10-2018" END_DATE = "01-11-2018" def find_date_range(tweet_file): ''' Purpose: We had problems with our dataset. At some point we realized ...
6b2e8aae81d548698267f1dd479e67940eac09bd
songwenju/BeautyDeepLearning
/chapter5/5.10_getNeighbors.py
816
3.5625
4
import operator import math def EuclidDist(instance1, instance2, length): distance = 0 for x in range(length): distance += pow((instance1[x] - instance2[x]), 2) return math.sqrt(distance) def getNeighbors(trainSet, testInstance, k): distance = [] length = len(testInstance) - 1 for x ...
f508e76f8235ec2b49323b33835801453ecd3164
MonikerTechnology/ledwall
/ledwall/animation/a_start_up.py
1,153
3.875
4
def start_up(t, coord, ii, n_pixels, value): """Compute the color of a given pixel. t: time in seconds since the program started. ii: which pixel this is, starting at 0 coord: the (x, y, z) position of the pixel as a tuple n_pixels: the total number of pixels Returns an (r, g, b) tuple in the ra...
e32456af48a5f5cbbdd51455ffc7c02bb4588d77
andre15ap/ordenacao
/merge_sort.py
2,472
3.53125
4
import csv , io import time import gerar_lista def merge(llist, rlist): """ Merge two lists into an ordered list. """ final = [] while llist or rlist: # This verification is necessary for not try to compare # a NoneType with a valid type. ...
223ecec7152526553cfa0f9d1292c9e0f8fe9c12
aledomesalazar/Producto-de-Unidad---Tercer-Parcial
/Código Fuente/Programa 4.py
1,892
3.75
4
#Programa 3 # Para leer los datos while True: # Defino variables estado = 'S' # El estado se inicia en S cont = 0 # Número de dígitos de la entrada salida = 0 # Inicializa la salida con 0 # Para ingresar los datos entrada = int(input("Ingrese la entrada: ...
285b71d438117ccab5653952da70112c9646ea45
rguezgiova/imw
/ut2/a2/program4.py
632
3.921875
4
import sys import math from math import pi r = float(sys.argv[1]) print ('(1) Calcular el diámetro de la circunferencia') print ('(2) Calcular el perímetro de la circunferencia') print ('(3) Calcular el área del círculo') print ('(4) Salir') menu = int(input('Introduzca un valor: 1 - 4: ')) if menu < 1 or menu > 4:...
d8d791d01895b3a173b4d8003b2e2b648905b3da
AlirezaTeimoori/Unit_1-04
/radius_calculator.py
480
4.125
4
#Created by: Alireza Teimoori #Created on: 25 Sep 2017 #Created for: ICS3UR-1 #Lesson: Unit 1-04 #This program gets a radius and calculates circumference import ui def calculate_circumferenece(sender): #calculate circumference #input radius = int(view['radius_text_field'].text) #process ...
b33054f31a3bf6cbd51940a7fc0a570f032c06b7
liberty1997/myPythonchengxu
/python_practices/newTonfa/newTonfa.py
556
3.703125
4
#!/bin/python3 # -*- coding: UTF-8 -*- def fangcheng(x): F = x**3 + 4*(x**2) -10 return F def yidao(x): F = 3*(x**2) + 8*x return F def Newton(x,n): n = n + 1 print("n=", n,end=' --- ') print("x(n)=", x,end=' --- ') x1 = x - fangcheng(x) / yidao(x) print("x(n+1)=", x1) # 符合精度,...
aaf4f66532587ab4040df06cbc149df662cb1360
Szabo1/BootCamp19
/Temp_converter TDD.py
581
3.90625
4
import unittest from temp_convertor import convert_celcius_to_farenheit class TempConvertortest(unittest.TestCase): #given in celcius = correct in F #data type for input #it it thorws an exception when data type is incorrect #check for null values -> throw an error def test_celcius_is_converted_to_farenh...
56757181ef64ab77261b3887452862008fff673e
gakkistyle/comp9444
/exam_scripts/perceptron.py
1,162
3.5
4
w0 = 0.5 w1 = 1 w2 = -2 lr = 1 targets = [-1,-1,1] data = [[-1,-1],[2,1],[-2,2]] count = 0 def check_convergence(w0,w1,w2,lr,count): for i in range(3): temp = w1* data[i][0] + w2 * data[i][1] + w0 print("temp is", temp,"target is ",targets[i]) if (temp * targets[i]<0): ...
0b8bd96e4f49be321f7391a47a213a10f1a1eed5
ponnuru171/aws
/PythonProject/sai_pandas/csv files.py
184
3.5
4
import csv with open('test1.csv')as csvfile: line=csvfile.readlines() print(len(line)) readcsv=csv.reader(csvfile,delimiter=',') for row in readcsv: print(row)
7a8df806bbb6774ee9f9c3c56c82bf90d34f37ae
johnjosephhorton/stv
/stv_results.py
6,684
3.546875
4
#!/usr/bin/env python import csv import re import copy import random import os import sys from contextlib import contextmanager def OrderChoices(ordering, names): "Creates a list for each respondent, with choices ordered 1 = most-preferred" choices = [] for order, name in zip(ordering, names): c...
02082cb9cea92fcb4a5ebf7318aa1e13422db679
Equinox21040/Processing-Projects
/Binary_Stars/Binary_Stars.pyde
1,095
3.625
4
m1 = float(3) m2 = float(1) a = 400 t = 0 canvas = None def setup(): global canvas size(800,800) canvas = createGraphics(1000,1000) canvas.beginDraw() canvas.background(0) canvas.endDraw() frameRate(120) def draw(): global t , canvas image(canvas,0,0) ...
04ced06172158dfb99885f66351f725877b04d60
gaofeil/Algorithm-code-python
/剑指offer/20包含min函数的栈.py
1,163
3.75
4
# -*- coding: utf-8 -*- # @Time : 2019/5/7 20:10 # @Author : gaofeil ''' 题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 ''' ''' 最佳思路:利用一个辅助栈来存放最小值 栈 3-4-2-5-1 辅助栈 3-3-2-2-1 每入栈一次,就与辅助栈顶比较大小,如果小就入栈,如果大就入栈当前的辅助栈顶 当出栈时,辅助栈也要出栈 也就是两个都出,可以保证辅助栈顶一定都当前栈的最小值 ''' # -*- coding:utf-8 -*- class Solution: def __init__(s...
e51153d9d6e302546d152c14ef9fc132cc052394
flex94/Python
/utils/dates.py
443
3.546875
4
from datetime import date as dt from calendar import monthrange from pandas.tseries.offsets import BDay def is_bday(date): # move to date utils return (date + BDay(0)).date() == date def month_ends_range(start, end): # move to date lib months_ends = [ dt(y, m, monthrange(y, m)[1]) for y in ...
140e00af694b93ab6de0b6eb2310f0a38c5db83b
catmyc/FEPParser
/src/vector.py
1,906
3.984375
4
__Author__ = ''' Yuncheng Mao ''' __Email__ = ''' catmyc@gmail.com maoyuncheng@mail.nankai.edu.cn ''' import math def vecadd(vec1, vec2): if len(vec1) == len(vec2): return [a + b for (a, b) in zip(vec1, vec2)] else: print("ERROR: Two ...
d413b355db70f40497339c1ce624c8f24d8ef99c
juan-domenech/say-it-louder
/ranking.py
865
3.546875
4
def basic_ranking(movies): movies_new = [] # We are interested only in movies and tv series titles for movie in movies: if movie['kind'] == 'movie' or movie['kind'] == 'tv series': movies_new.append(movie) # Discard year = 0 or 2155 (Movie in development) movies_temp = [] ...
0256d5c7f79e3b116520cf7bd33ed99dfd376194
C109156117/MIDTERM
/04_2D座標判斷及計算離原點距離.py
856
3.890625
4
x=int(input("請輸入X值:")) y=int(input("請輸入Y值:")) d=(x**2)+(y**2) if x >0 and y>0: print("該點位於第一象限,離原點距離為根號"+str(d)) elif x<0 and y>0: print("該點位於第二象限,離原點距離為根號"+str(d)) elif x<0 and y<0: print("該點位於第三象限,離原點距離為根號"+str(d)) elif x>0 and y<0: print("該點位於第四象限,離原點距離為根號"+str(d)) elif x==0 and y==0: print("該點位於...
b0f9d63c2e9b33ce237d01972225bccba86cde4f
C109156117/MIDTERM
/58_判斷串謝數字大小.py
320
3.5625
4
a=[] ma=[] mi=[] c=0 for i in range(10): c=c+1 u=int(input("請輸入第"+str(c)+"個數字:")) a.append(u) ma=sorted(a,reverse=True) mi=sorted(a,reverse=False) print("最大的3個數字為:"+str(ma[0])+",",str(ma[1])+","+str(ma[2])) print("最小的3個數字為:"+str(mi[2])+","+str(mi[1])+","+str(mi[0]))
f3d6c170b9c699457ea0fa3834d7207637c0291a
C109156117/MIDTERM
/30_販賣機.py
207
3.578125
4
M=int(input("小明身上有幾元(<=100):")) N=int(input("販賣機有幾種飲料(<=30):")) a=0 for i in range(0,N): d=int(input("")) if M>=d: a=a+1 print("小明可買",str(a),"種飲料")
d3343a8fc5228c73e26ba5c01bd51b354a953ab5
C109156117/MIDTERM
/05_階乘判斷.py
185
3.71875
4
m=int(input("請輸入階乘值M:")) total=1 n=1 while total <m: total=total*n if total>m: break n=n+1 print("超過M值為"+str(m)+"的最小階乘N值為:"+str(n))
a06ef912a2f2ffaa962b974f273f8d465d3dfe7f
daikiante/python_Udemy
/python_basic/lesson_002.py
620
4.25
4
# helpコマンド  関数、ライブラリの機能が表示される # import math # print(help(math)) # '' "" \n ==> 改行 print('say "I don\'t know"') print('hello \n how are you') # インデックスとスライス word = 'Python' print(word[0]) print(word[1]) print(word[-1]) print(word[0:2]) print(word[2:5]) print('----------------------------') ''' インデックスの...
56a5a5f85e781ce362438985965eb1f8f8b8fc2b
daikiante/python_Udemy
/def_practice.py
236
3.921875
4
def get_total(a,b,c): return a + b + c def get_average(a,b,c): return (a + b + c) / 3 a = int(input('a :')) b = int(input('b :')) c = int(input('c :')) print('合計:',get_total(a,b,c)) print('平均:',get_average(a,b,c))
71e8c1d879c0b68fbf00a79f495b399a8aaed662
daikiante/python_Udemy
/python_basic/lesson_001.py
276
3.671875
4
# 変数宣言   (1文字めは数字を使えない) num = 1 name = 'Mike' is_OK = True print(num,type(num)) print(name,type(name)) print(is_OK,type(is_OK)) # type(変数名)でデータタイプがわかる # ↓型変換が用意 num = name print(num,type(num))
900ec7398217c13d3751e5fe0873dcd3385c10ac
vamshi029/Assignment
/solution_3.py
635
3.90625
4
from collections import deque class Node: def __init__(self, key): self.key = key self.left = None self.right = None def bfs(root): if not root: return queue = deque([]) queue.append(root) while(queue): node = queue.popleft() print(node...
e2c0ea3f0638d3d181a0d291eb488839f1596001
Yasin-Yasin/Python-Tutorial
/005 Conditionals & Booleans.py
1,415
4.375
4
# Comparisons # Equal : == # Not Equal : != # Greater Than : > # Less Than : < # Greater or Equal : >= # Less or Equal : <= # Object Identity : is # if block will be executed only if condition is true.. if True: print("Conditinal was true") if False: prin...
f17feb86a3277de3c924bcecb2cc62dee8801e1b
Yasin-Yasin/Python-Tutorial
/014 Sorting.py
1,686
4.28125
4
# List li = [9,1,8,2,7,3,6,4,5] s_li = sorted(li) print("Sorted List\t", s_li) # This function doesn't change original list, It returns new sorted list print('Original List\t', li) li.sort() # sort method sort original list, doesn't return new list, this method is specific to List obj print('Original List, Now So...
b2223d50360a7f4a4b3e06bd3bf4a1d2e78dc8d6
tnakatani/python2_ccac
/wk_6/api_challenge/api.py
1,063
3.6875
4
# Challenge: Try converting the following code into an API class import json import requests # Set up the variables company = 'saturn' model = 'LS' year = 2000 # Set up the API call URL url = f'https://webapi.nhtsa.gov/api/Recalls/vehicle/modelyear/{year}/make/{company}/model/{model}?format=json' # Make the request...
d79633bbc84f88162c3a848d671f2e9ddd94e87c
DishantK1807/Leetcode-Practice
/83 - Remove Duplicates from Sorted List/PythonSolution.py
650
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if head == None or head.next == None: return head ret = head last = self....
20a37c14966562ebec88f783a3afb252054417bf
DishantK1807/Leetcode-Practice
/160 - Intersection of Two Linked Lists/PythonSolution1.py
491
3.578125
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: return None tempA = headA ...
b9809b83cf432b723bdd3c8306584773e6d96871
DishantK1807/Leetcode-Practice
/107 - Binary Tree Level Order Traversal II/PythonSolution2.py
943
3.78125
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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]: list_dict = dict() if root is None: return []...
0162302b638def1466a6225e775bd213a486944f
DishantK1807/Leetcode-Practice
/110 - Balanced Binary Tree/PythonSolution.py
875
3.8125
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 isBalanced(self, root: TreeNode) -> bool: flg = True if not root: return True elif not root.left...
6fe94a471801879a49c973c687c1e61b44d3e80a
tristan1994/python-challenge
/PyBank/main.py
2,604
3.96875
4
# Allow to create file paths across operating system import os # Module for reading csv file import csv #Input path csvpath = os.path.join('Resources', 'budget_data.csv') #Output path result = os.path.join('analysis', 'analysis.txt') #Setting variable and store it as list #Total number of months included...
37a05f22edc35b2389564e1a1a7e6e98e91c24e0
Arnaud31200/Projet5Openclassrooms
/program_mysql.py
3,999
3.8125
4
class Program_execute : """Set program execution""" def __init__(self, cursor) : self.cursor = cursor self.categories_list = [] self.foods_list = [] self.food_selected = [] self.food_substituted = [] def select_categories(self): """Set categories selection"""...
946c30523308a76ab76ace3f316f0f1d71de8521
ian-ludden/office-scheduler
/officeScheduler/Solver.py
1,032
3.6875
4
from abc import ABC, abstractmethod import enum class Solver(ABC): """Abstract superclass for solvers of the office scheduling problem.""" def __init__(self, people=[], set_constraints=[], time_limit=-1): self.people = people self.set_constraints = set_constraints self.time_limi...
426dc3d0853723330cb99f2d0f6571764e969267
tuxerrante/rot_cipher
/rot_cipher.py
2,704
3.609375
4
''' Use case example: INPUT bmhnYnpuZ3ZiYXZmbmpyZmJ6cg== KEY 13 DECODED nhgbzngvbavfnjrfbzr DECRYPTED automationisawesome ''' import string import base64 import argparse from argparse import RawTextHelpFormatter # === GLOBAL VARS === useless_bar = 50 * "=" # === FUNCTIONS DEFINITI...
074ac0d3a6836dbf02831280eb8cd55adb3a508d
ZHANGYUDAN1222/Assignment2
/place.py
1,282
4.3125
4
""" 1404 Assignment class for functions of each place """ # Create your Place class in this file class Place: """Represent a Place object""" def __init__(self, name='', country='', priority=0, v_status=''): """Initialise a place instance""" self.name = name self.country = country ...
d8bb309ef822eff21b590b65e0b3483f05513393
mahirdurmaz/ITF
/prime_numbers_2.py
266
3.953125
4
lower = 0 limit = int(input("Please enter a number: ")) print("Prime numbers from 0 to", limit) for num in range(lower, limit + 1): if num > 1: for i in range(2, num): if (num % i) == 0: break else: print(num)
cbc6893bd5bea9b8d41c539c400b038a1c37272b
jetcem/Coursera-Machine-Learning
/Python_Implementation/Machine Learning - Week 5/Neural_Network_Backpropagation.py
4,871
4.03125
4
""" Created on Sun Apr 26 03:01:15 2020 @author: Cem Dogan """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import io import functions #=========== Part 1: Loading and Visualizing Data ============= mat = io.loadmat('data\ex4data1.mat') #read the data from mat file data_X = mat[...
b116d468659dde81728a5006b7ad939d4ad12cd2
karpiyeniamv/PyFiles
/five_pal.py
975
3.671875
4
import math def prime(n): if (math.factorial(n-1) + 1) % n != 0: #print("Это составное число") return 0 else: #print("Это простое число") return 1 def is_palindrome(word): for i in range(len(word)//2): if word[i] != word[-1-i]: return False retur...
70b1b7530120895ff6440a7e6b8b9a26579eebbb
BrawlerPro/PyGame
/ArcadeGamesBook/1.py
3,503
3.609375
4
import pygame import random pygame.init() screen=pygame.display.set_mode((640,480),) # try out larger values and see what happens ! screenrect = screen.get_rect() # ------ constants ------------ clock = pygame.time.Clock() mainloop = True FPS = 30 # desired framerate in frames per second. playtime = 0 radius = 50 # for...
f0e1579f63904244defcfcc1e37b3c880d8c06cc
BrawlerPro/PyGame
/Snake/sprites/rabbit.py
2,608
3.5
4
from random import randint import pyanimation TILE = 50 RABBIT_TILE = 32 class Rabbit: def __init__(self, tiles_in_row, tiles_in_col): self.x = randint(0, tiles_in_row) self.y = randint(0, tiles_in_col) self.scr_x = (self.x * TILE) + (TILE - RABBIT_TILE) // 2 self.scr_y = (self.y ...
9a017ca9e9480b23e8d487cd88714e5952304892
hank6315/SwordOffer
/028-数组中出现次数超过一半的数字/main.py
712
3.703125
4
# -*- coding:utf-8 -*- class Solution: def MoreThanHalfNum_Solution(self, numbers): # write code here count = 0 length = len(numbers) target = numbers[0] for i in range(length): if count == 0 or target == numbers[i]: target = numbers[i] ...
3c1e06e474fd1efe589a430add9794610f3f2cda
hank6315/SwordOffer
/010-矩形覆盖/main.py
341
3.65625
4
# -*- coding:utf-8 -*- class Solution: def rectCover(self, number): # write code here if number == 0: return 0 f1 = 1 f2 = 2 if number == 1 : return f1 if number == 2 : return f2 for _ in range(number - 2): f2 , f1 = f1 + f2 , f2 ...
06117bbc714f6c434640f915ace717bf8257976b
hank6315/SwordOffer
/025-复杂链表的复制/main.py
533
3.703125
4
# -*- coding:utf-8 -*- # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # 返回 RandomListNode def Clone(self, head): # write code here dic = dict() m = n = head while m: d...
3eb188c75eec08248d61344b87c1ee684d87c4f7
Monduli/HashMap-MinHeap
/min_heap.py
6,055
3.78125
4
# Course: CS261 - Data Structures # Assignment: 5 # Student: Dan Glendon # Description: Portfolio minimum heap implementation # Import pre-written DynamicArray and LinkedList classes from a5_include import * class MinHeapException(Exception): """ Custom exception to be used by MinHeap class DO NOT CHANG...
f785bc811f5ca108755fd2783e9e5a96240c8b77
mikehancoski/ice-creams-homework
/week1/game_over.py
229
3.515625
4
# basic game over program Chapter 1 -Mike print("game over!") input("\n\n Press the enter key to move on.") #challenges chapter one print("pineapple") print("Leeeeeroy jenkinnssss!!!") input("\n\n press enter to exit")
79144ad6f7efd0fcdc7d3fe20e04a881cb1b544a
Diwyang/PhytonExamples
/demo_ref_list_sort3.py
1,206
4.40625
4
# A function that returns the length of the value: #list.sort(reverse=True|False, key=myFunc) #Sort the list descending cars = ['Ford', 'BMW', 'Volvo'] cars.sort(reverse=True) print(cars) #Sort the list by the length of the values: # A function that returns the length of the value: def myFunc(e): return len(e) ...
ba6e01baaa2b69497ede48f24737831c8d35fa68
Diwyang/PhytonExamples
/Example4.py
531
4.21875
4
# My Example 3 """There are three numeric types in Python: int - Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. float - Float, or "floating point number" is a number, positive or negative, containing one or more decimals. complex - Complex numbers are writt...
a08d8bcd77031a2157f8507a81a95e134ca45032
elamje/daily-py
/080619.py
687
3.9375
4
# monte carlo pi # generating only random data, and using knowledge about circles # approximate pi # x2 + y2 = r2 # area of circle = pi*r2 # unit circle area of square = 1, r = .5 # generate random x,y points # pi = area / .5^2 # n is the size of the random data set def monte_pi(n): unit_square = np.random.uniform...
670187ea7283d2c53dced065f078228aa6b2bcf9
loki999009/GB_Python
/lesson_2/hw02_hard.py
4,624
4.25
4
# Задание-1: уравнение прямой вида y = kx + b задано в виде строки. # Определить координату y точки с заданной координатой x. equation = 'y = -12x + 11111140.2121' x = 2.5 # вычислите и выведите y #разбиваем список методом split по пробелу name = equation.split(' ') #берем 2 значение полученного списка (-12x) и преоб...
4d61d4f6f2c3c1f47b5db3fdb75eb9350e4687cd
dcmswim/Python-Projects
/python_db_Assignment/python_db_assignment.py
871
4.09375
4
import sqlite3 conn = sqlite3.connect('db_python_assignment.db') with conn: cur = conn.cursor() #creates table cur.execute("CREATE TABLE IF NOT EXISTS tbl_files( \ file_ID INTEGER PRIMARY KEY AUTOINCREMENT, \ file_name TEXT)") conn.commit() #commits change to dB conn.close() #ends con...
972baa463680cfaddd85fc621e677a9bed5264ae
treatmesubj/Tips-Tricks
/Algos/binary_search.py
1,049
3.9375
4
import time # find a num in sorted ascending array of nums # binary search: look to mid; is num > mid or num < mid or num == mid? # log n def binary_search(sorted_array, target_val): low_index = 0 high_index = len(sorted_array) - 1 while low_index <= high_index: print("-" * 20) print(sort...
ecfeb861585690199ed6c375895cdfe0649bba5e
tarasrumezhak/Lab3
/json_copy.py
4,582
3.640625
4
import requests import json import sys from requests_oauthlib import OAuth1 def check_type(curr): ''' (dict/list) --> str Takse the data of some type and returns the string to represent the type ''' if isinstance(curr, dict): return "dictionary" elif isinstance(curr, list): ...
cbce8ce40e2c2fa60e666db94677a3ac2ff95069
clejacquet/algonum-p3
/src/imgutils.py
1,167
3.578125
4
# coding=utf8 import numpy as np def decomposition_couleurs(a): """ Prend une matrice de triplets RGB et la décompose en 3 matrices avec les valeurs correspondant aux 3 couleurs :param a: matrice de triplets :return: trois matrices contenant les éléments des triplets de a """ n = np.shape(a)[...
a6158f2bf6ce87e6213cb5de60d4b82d9cd5000c
guoguozy/Python
/answer/ps1/ps1b.py
648
4.21875
4
annual_salary = float(input('Enter your annual salary: ')) portion_saved = float( input('Enter the percent of your salary to save, as a decimal: ')) total_cost = float(input('Enter the cost of your dream home: ')) semi_annual_raise = float(input('Enter the semi­annual raise, as a decimal: ')) current_savings =...
6b4de4c7d0e7dc9306116497f2bd125ee81c09a6
gfannes/latijn
/afvragen.py
1,545
3.65625
4
import sys sys.path.append("gubg.io/src") import word import util book = word.Book.load("vestibulum.naft") print("Hallo Tibe, ben je er klaar voor?") six = util.input_int(f"Van waar wil je beginnen?", 1, len(book)) eix = util.input_int(f"Tot waar wil je gaan?", 1, len(book)) book.prune(six-1, eix) nr = util.input_...