blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
86dc3ac8a4043b92be47954fb561d0da0efbed0d
mchalela/lensing
/gentools/distance.py
7,248
3.609375
4
import os import numpy as np import scipy.sparse from astropy.cosmology import FLRW def sphere_angular_separation(lon1, lat1, lon2, lat2): ''' Angular separation between two points on a sphere Parameters ---------- lon1, lat1, lon2, lat2 : Angle, Quantity or float Longitude and latitude of...
5b6c10ced0e43f45bfb4ec8734dead06be7de988
Pallav277/Python_Turtle_Graphics
/Smiley.py
834
3.703125
4
# importing turtle module import turtle turtle.bgcolor('black') smiley = turtle.Turtle() # function for creation of eye def eye(col, rad): smiley.down() smiley.fillcolor(col) smiley.begin_fill() smiley.circle(rad) smiley.end_fill() smiley.up() # draw face smiley.width(4) smiley.fillcolor('yel...
ef13c2bfcd1fa62ff80fdea426b2b7573fbf2190
jigglypuff27/MSI
/Python/Dictionary.py
506
4.1875
4
#Dictionary x= {'morning':'wake','evening':'snack','noon':'lunch','night':'dinner'} print(x) #O/P{'morning': 'wake', 'evening': 'snack', 'noon': 'lunch', 'night': 'dinner'} for k,v in x.items(): print(f'{k}:{v}') # morning:wake # evening:snack # noon:lunch # night:dinner for k in x.keys(): ...
be5eb2aad7659740cd0225d8537f6093906e4118
jasmineve/lpthw
/ex6.py
757
4.625
5
# This assigns a string with formatted variables to the variable x x = "There are %d types of people." % 10 # This assigns a string to variable called 'binary' binary = "binary" # This assigns a string to the variable 'do_not' do_not = "don't" # The right side is a string with two formatters, the left side is variable ...
37880f32e0d26b6337a564558d074e0544734080
geekcoderr/python_algorithms
/algo_armstrong_number.py
494
4.3125
4
#Take input from user.. >> tke=(input("Enter the number to check whether it's an Armstrong number or not :: ")) sumof=0 temp=tke leng=len(tke) tke=list(tke) #Loop will start to compute power of number with length.. >> for i in range(0,leng): tke[i]=int(tke[i]) sumof+=tke[i]**leng #Print answer to user if number...
56f9b67fb814e65f3573000a1c6ee8c05606c49f
ewdurbin/opstacle
/opstacle/util.py
842
3.5
4
import datetime import collections import threading class ExpireCounter: """Tracks how many events were added in the preceding time period """ def __init__(self, timeout=1): self.lock=threading.Lock() self.timeout = timeout self.events = collections.deque() def add(sel...
0944aea35f32894abe6ed80d2d26881a3758aa5f
tfinlay/pywinterm
/pywinterm/display/util.py
2,935
3.53125
4
""" Display utilities """ import os def clear_window(): """ Clears the screen :return: None """ os.system("cls") def render_chars(arr): """ Prints every character to the terminal window :param arr: iter<String>, each String is a line in the terminal :return: None """ for ...
36dfa78a6e2f12784c58248a08897d9dec865e2a
SergioHerreroSanz/dam2d17
/Sistemas_de_Gestión_Empresarial/P3_Python/PythonApplication6/Ej09_POO.py
3,051
3.921875
4
# -*- coding: utf-8 -*- ''' 8 PDO ''' class Mueble: # el primer registro siempre self en todos def __init__(self, tipo): # constructor self.tipo = tipo # Propiedad publica def getTipo(self): # Metodo getter return self.tipo def setTipo(self, tipo): self.tipo = tipo # Llamam...
5809cde51f5b406f4e674e3546879573bf8953f2
Anekjain/Programming-Solution
/misc/Hartals.py
696
3.796875
4
#!/usr/bin/env python def hartalCount(p,d): hartal_days = [] for j in p: for i in range(d): i += 1 if(i % j == 0 ): hartal_days.append(i) if(i%7 == 6 or i%7 == 0): #REMOVING HARTALS ON SATURDAY AND SUNDAY hartal_days.pop() ...
b424e6dc098239cfd125327cf5776df789820264
Priyadharshinii/begginnerr
/armstrong.py
209
3.640625
4
r1=input("enter lower range") r2=input("enter higher range") for num in range(r1,r2+1): sum=0 temp=num o=len(str(num)) while temp>0: r=temp%10 sum+=r**o temp//=10 if num==sum: print(num)
ed5f150b6847a6214535b561c83ae4b973499ec3
DT211C-2019/programming
/Year 2/Paul Geoghegan/S1/Labs/Lab7/l7q3.py
335
4.3125
4
#Assignes value for string str = "Monty Python" #Sets value for length length = 0 #Prints first character print("The first character is", str[0]) #Prints last character print("The last character is", str[11]) #Prints the last character using len print("The last character using len() is", str[len(str)-1]) #Prints ...
5fbdc1a74e32256094162a91bd4c9bc92e9d1cbc
Rajahx366/Codewars_challenges
/5kyu_Josephus_Permutation.py
1,996
3.75
4
""" This problem takes its name by arguably the most important event in the life of the ancient historian Josephus: according to his tale, he and his 40 soldiers were trapped in a cave by the Romans during a siege. Refusing to surrender to the enemy, they instead opted for mass suicide, with a twist: they formed a cir...
a7cb3d4381202069ba4a304887e7df5e955d44c1
Folkert94/Advent_of_Code_2020
/day_3/day_3.py
668
3.65625
4
def get_numbers(input_file): numbers = [] with open(input_file, 'r') as input: for line in input: temp = line.strip() numbers.append(temp) return numbers field = get_numbers("input.txt") def count_trees(slope): p, q = slope i = 0 j = 0 count = 0 while i ...
d8c2dd8ba2fbbc26f3010fbae473b9512decfd55
benpry/resource-rational-goal-pursuit
/code/main/linear_quadratic_regulator.py
13,353
3.671875
4
""" Code for the optimal (LQR) model and the sparse attention (sparse LQR) model. """ import torch import numpy as np from Microworld_experiment import Microworld class OptimalAgent: """ An agent that uses a linear quadratic regulator to pursue a goal A: endogenous transition matrix B: exogenous inpu...
057aa0c021e5b31f5ecdf694f54f53c371a8cbc1
IPFactory/WelcomeCTF2021
/ppc/revival/solve.py
357
3.8125
4
def Fib(n, memo): if n == 1: return 0 elif n == 2: return 1 elif n in memo: return memo[n] else: memo[n] = Fib(n-1, memo) + Fib(n-2, memo) return memo[n] N = 3 memo = {} while True: if Fib(N,memo) >= 31271819149290786098591076778525667781144930000000: ...
1a94816747a23effd6e3cc120ad9b62db4113e4d
flothesof/advent_of_code2019
/puzzle05.py
4,448
3.53125
4
def run(program, input_value): index = 0 prints = [] while True: instruction = program[index] op_str = f"{instruction:05}" # pad with zeros if necessary op = op_str[-2:] A, B, C = op_str[0], op_str[1], op_str[2] jump = False # add if op == '01': ...
5b6f08f5b5f374057e9389ebf4d7b8f8eb40e672
breastroke423/python_challenge
/charenge4.py
4,029
3.578125
4
from bs4 import BeautifulSoup import requests import pandas as pd import openpyxl ''' # ↓用意されたHTML html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their name...
b3eb8c6e7a01e8343bd62a14f141ec93ea0b6e20
ShivaliBandi/Automation_scripts_using_python
/WebLauncher.py
1,107
3.609375
4
#Web Launcher import webbrowser import urllib.request #This method is for checking internet connection def Connection_Established(): try: urllib.request.urlopen('http://216.58.192.142',timeout = 5) #print(url) #If we connect with specified url,then return True otherwise throw Exception. return Tr...
bfc5c6bd95f4667a156d61eb892d5521b68a0af8
emblaoye/python-semesteroppgaver
/sem1.py
3,764
3.546875
4
def stigend_eller_synkende(tall1, tall2, tall3): print('Tall nr 1:', tall1) print('Tall nr 2:', tall2) print('Tall nr 3:', tall3) if tall1 < tall2 < tall3: print('Disse talle er stigende') elif tall1 > tall2 > tall3: print('Disse tallene er synkende') else: print('Disse ...
8036bfe766b2b30f54a9e50e37928d85b5484049
rkoblents/python-text-adventure-api
/textprint/section.py
8,475
3.78125
4
from typing import Optional, TYPE_CHECKING, Tuple from textprint.line import Line if TYPE_CHECKING: from textprint.textprinter import TextPrinter class Section: OLD_LINES_AMOUNT = 100 """The amount of lines to keep and possibly render if they fit on screen""" OLD_LINES_REMOVE_AT_TIME = 10 """The...
4a959a722cdd7714bc6dc2d456374880e748a4d3
QiuFeng54321/python_playground
/loop_structure/edited_Q1.py
153
3.953125
4
# Quest: 1. Input two integers x, y, print the larger integer print("The sum is", int(input("First integer: ")) + int(input("Second integer: ")))
5da0ead112ac8814419d50d2825c9272976bf91b
paepcke/discrete_differentiator
/src/discrete_differentiator/discrete_differentiator.py
7,441
3.890625
4
#!/usr/bin/env python ''' Created on Jan 27, 2015 @author: paepcke Takes a sequence of numbers, and returns a sequence of numbers that are the derivative of the given sample. Takes the sequence either as a Python array, or in a CSV file. Differentiation is done as follows: For first data point uses: f'(x) =...
da513825966939e95d5c400bd1bc63e83ed67646
it3r4-gonzales/PythonCourse101
/PythonforBeginners/Data types, Input and Output/expenses.py
566
3.96875
4
##sum of expenses # expenses = [10.5,8,5,15,20,5,3] # sum = 0 # for value in expenses: # sum = sum + value # print("You spent $", sum, " on lunch this week.", sep='') #sum function expenses = [10.5,8,5,15,20,5,3] total = sum(expenses) print("You spent $", total, " on lunch this week.", sep='') #Adding Input T...
430dcfc88f30ff21456e192d1ce5754f14300a5c
123tharindudarshana/testproject
/linklist/LinkedList.py
1,517
3.734375
4
from Node import Node class linkedist: def __init__(self): self.head=Node() def listlenth(self): current=self.head count=0 while current is not None: count=count+1 #print(current. getData()) current =current.getNext() return count ...
0c32e313f9d3beb1af51d0b9a50225eef27163ec
CrackedCode7/Udemy-Learning
/basics/hello.py
247
3.90625
4
print('Python is easy') #The print function prints a message enclosed in double quotes to the console # can be used for single line comments '''can be used to have multiple line comments''' """alternatively you can use triple double quotes"""
d3317d61affebfb1c3658c1d6f37842eed6a02cf
a1723/django_brain_games
/project/brain_games/brain_even_helpers.py
138
3.59375
4
def get_even_correct_answer(num1): # проверяем число на чётность return "yes" if (num1 % 2 == 0) else "no"
8113a240b09da5e3a6c07c6808a6e2b1377cbe6d
wellington16/BSI-UFRPE
/2016.1/Exércicio LAB DE PROGRAMAÇÃO/Períodos anteriores/exercicio5/12.py
356
3.8125
4
rota=None def F(n): if n == 1: return 1 elif (n % 2) == 0: rota='Passou aqui' return F(n/2) elif (n % 2) != 0 and (n > 1): rota='Aqui tambem' return F(3*n+1) print(F(1)) print(rota) print(F(2)) print(rota) print(F(3)) print(rota) print(F(5)) print(rota) print(F(8)) p...
8e51cf4b49e4de3ad99b643043012b7dc9bec34c
spoorthichintala/Selenium_Demo_Python
/Python_Demo/Reand_and_Write_JSON_File_Data.py
513
3.5625
4
import json # function to add to JSON def write_json(new_data, filename='TestData.json'): with open(filename, 'w') as file: json.dump(file_data, file, indent=4) with open("TestData.json") as json_file: # First we load existing data into a dict. file_data = json.load(json_file) # Join new_dat3a...
542bceff437ee51af01f6292ee5d8528427eb418
Nishnha/advent-of-code
/2020/day2/part2.py
523
3.578125
4
num_valid = 0 with open("input.txt", "r") as input: for line in input: valid = False x = line.split(" ") p = x[0].split("-") pos1 = int(p[0]) - 1 pos2 = int(p[1]) - 1 letter = x[1].strip(":") password = x[2] print(pos1, pos2, letter, passwo...
4b33c4b3fee0e230ad67fd0e7a7f0b5d37fe6439
widelec9/codewars
/kata/python/6kyu/nut_farm.py
434
3.53125
4
def shake_tree(tree): nuts = [1 if c == 'o' else 0 for c in tree.pop(0)] while len(tree) > 0: for i, c in enumerate(tree[0]): if nuts[i] > 0 and c in ['\\', '/', '_']: if c == '\\' and i < len(nuts) - 1: nuts[i+1] += nuts[i] elif c == '/' a...
c4cd55ec702dd4ef95293ed2133367df8053ab1f
glissader/Python
/ДЗ Урок 8/main2.py
1,121
3.65625
4
# Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль. # Проверьте его работу на данных, вводимых пользователем. # При вводе пользователем нуля в качестве делителя программа должна корректно обработать эту ситуацию и не завершиться с ошибкой. class CustomZeroDivisionError(Exception): def...
1e25e0c7710e2d9ed059fae795dc8ccca46c42ea
dpoulomi/PythonPractice
/python_practice/largest_number_from_array.py
1,688
3.984375
4
import random def quick_sort(input_array, start_index, end_index): if start_index < end_index: partition_index = partition(input_array, start_index, end_index) quick_sort(input_array, start_index, partition_index -1) quick_sort(input_array, partition_index + 1, end_index) def partition...
c917449ef1d6686212e19722ba183bd782e3ed3f
ciberciv/pepi_challenge
/classes/TripGraph.py
4,317
3.65625
4
from classes.CitiesGraph import CitiesGraph from collections import defaultdict import functools import operator import queue class TripGraph(CitiesGraph): def __init__(self, cities, connections, maxDays): assert 2 <= maxDays <= 7, "Trip has to be between 2 and 7 days long" CitiesGraph.__init__(se...
c1bf8475323437fd8f9f9f43316824522fcf8b26
psarkozy/HWTester
/MIHF/FlappyQ/py_files/flappy_env_server.py
5,683
3.53125
4
#!/usr/bin/env python import random from math import sqrt random_seed = random.randint(0, 200) class Vector(object): def __init__(self, x, y): super(Vector, self).__init__() self.x, self.y = x, y def __add__(self, vector): if isinstance(vector, self.__class__): return se...
795578e5fce1469a121521e936f971910b095f97
zzz0072/Python_Exercises
/07_RSI/ch01/Fraction.py
3,591
3.921875
4
#!/usr/bin/env python3 def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, num, den): if type(num) != int or type(den) != int: raise TypeError if num == 0 or den == 0: ...
9b449116d0c8259cbd6c70b0a2b16026d2c55c69
frankieliu/problems
/leetcode/python/6/zigzag-conversion.py
2,089
4.3125
4
"""6. ZigZag Conversion Medium 834 2589 Favorite Share The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Wr...
d0bede460d9b28f5bdf847db3746340c506c5397
Frootloop11/lectures
/week 10/find_in_files.py
995
3.96875
4
import os def find_in_files(search_string, file_extension, files_found): """Find files of type file_extension that contain search_string.""" count = 0 for directory_name, directories, filenames in os.walk("."): for filename in filenames: if os.path.splitext(filename)[1] == file_extensi...
d390591611153ca80aa1dc292908f504a08f997f
yuhanlyu/arrivability
/files/random_generate.py
633
4.03125
4
import random def random_generate(row, column, number): print row, column print number for i in xrange(number): print 4 x, y = random.randrange(3, row - 3, 5), random.randrange(3, column-3, 5) (w, h) = 1, 5 if random.randint(1, 2) == 1: (w, h) = (h, w) pr...
380348fcb5ee2da37e1701f1260a04aa34a22444
vofchik/python_learning
/exercise_06/task_06.py
499
4.125
4
#!/usr/bin/python3 # Упражнение 6 # Задание 6 # Заполнить список из шести элементов квадратными корнями произвольных # целочисленных значений. Вывести список на экран через запятую. import random roots = [random.randint(0,10000) ** 0.5 for i in range(6)] def float_as_str(x): return '{:.2f}'.format(x) print('Когни...
6f349a56391da322714d84f95ab688b41fe62b26
chmjorn/MastersProject
/mSketch.py
897
3.578125
4
import random import numpy #must be odd numbers width=7 height=7 maze = numpy.chararray((width, height)) for x in range(height): #create map for y in range(width): if (x%2==0): if(y%2==0): maze[x][y]='*' else: maze[x][y]='-' else: if(y%2==0): maze[x][y]='|' else: maze[x][y]='X...
e38ae5e0e0b907f21f3d577b9fef5ead54e4812f
kiefersutherland/pythonLearning
/learn/mpl.py
822
3.53125
4
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt from walk import Radomwalk ''' input_value=list(range(1,1001)) squares=[x**3 for x in input_value] plt.plot(input_value,squares,linewidth=5) ''' while True: rw=Radomwalk(5000) rw.fill_walk() plt.title('我是标题,do u know') pointNumbers=list(range(rw.nu...
a0f48be79a42a74013168a426378a45d229257dc
carloseduardo1987/Python
/ex14_lista1.py
686
4.09375
4
#Questão 14. Sabendo que a relação entre vértices, arestas e faces de um objeto geométrico é dada pela fórmula: # vértices + faces = arestas + 2. # Elabore um programa que calcule o número de vértices de um objeto geométrico genérico. # A entrada será o número de faces e arestas (dadas por um número inteiro e pos...
94d4bd48f272fb1369efbbc1da2acc9174b38ffe
devroopb/number_guesser
/number_guesser.py
1,155
4.21875
4
# Made by Devroop Banerjee # Generate a random number between a range chosen by user # Tell user whether they need to go higher or lower # Return the number of attempts it took import random print("Please input the range of values from which a random number will be generated. You will have to have to guess this numbe...
5bd7abd88df49bfd2e3f5478d8f2927c53d89a78
murilo-muzzi/Desafio-Murano
/Questão 7.py
1,758
3.75
4
# Desafio PS Murano Investimentos # Candidato: Murilo Marinho Muzzi Ribeiro # e-mail: murilomarinhomuzzi@gmail.com # Questões de computação e programação # Feito em Python # 7) continuar = 'sim' while continuar == 'sim': dados = dict() dados['dre'] = int(input('Digite o DRE: ')) dados['curso'] = input(...
b40e520d3c3d671a43b43ad17f8048d264e4c5c0
cafaray/atco.de-fights
/digitsProduct.py
814
3.796875
4
def digitsProduct(product): if product == 0: return 10 if product < 10: return product number = list() while product > 1: for divisor in range(9, 1, -1): print('evaluating:',product, divisor) if product % divisor == 0: number.append(divisor) ...
c4ec6f2c3d3ee2be8872c209290543dadc1e758f
jcutsavage/OOD-Project
/prime.py
553
4.15625
4
#!/usr/bin/env python #author John Cutsavage #cool code -Victor M import math #this code was taken from stackoverflow.com/questions/18833759/python-prime-number-checker def is_prime(n): if n < 2: #0 and 1 aren't prime; assume only positive integers return False if n % 2 == 0 and n > 2: return False for i in ran...
f24d63ac6af2db6ff4fc068505cdb80503784277
ojohnso8/python-challenge
/PyBank/Main.py
2,867
3.96875
4
#import import os import csv #create csv path budget_csv = os.path.join(".", "budget_data.csv") #Create empty lists for months and revenue months = [] revenue = [] #open csv with open(budget_csv, newline = "") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = next(csvreader) #append ...
07dc52f1c26dbbcb7abf233196ff3aeb9a2a402a
x64511/SIC-Assembler
/AssemblerFinal.py
5,720
3.5
4
from collections import OrderedDict def a24to6(Bits): #Function to convert 24 bit binary to hexadecimal res="" arr=['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'] for i in range(6): s=Bits[i*4:(i*4)+4] x=int(s,2) res+=arr[x] return res def a16to6(Bits): #Function to convert 16 bit binar...
b6635fc1af31a8138fd5efb61bcd59c9f296f63d
RileyWaugh/ProjectEuler
/Problem2.py
863
4.0625
4
#Problem: find sum of all even fibonacci numbers under 4,000,000 (sum of 0,2,8,34, etc #The key thing to realize is that even fibonacci numbers occur every three terms: (0),1,1,(2),3,5,(8),13,21,(34), #this makes sense: even, odd, (even+odd)=odd, (odd+odd)=even, (odd+even)=odd, (even+odd)=odd, (odd+odd)=even, etc d...
dad724d67b93789b50dcb655dd0d614ca5613f17
gabriellaec/desoft-analise-exercicios
/backup/user_313/ch39_2020_04_12_17_28_14_008686.py
663
3.5
4
termos = [] for n in range(1,999): conta = 0 lista = [0] lista[0] = n while True: if n % 2 == 0: n = n/2 lista.append(n) if n == 1: break else: n = n*3+1 lista.append(n) if n == 1: ...
5654e8ef93926784e98a2b9b542c18cfa5dab642
theparadoxer02/Data-Structure-and-Algo
/spoj/basics/longest_substring.py
361
3.84375
4
def lstr(string): substring = string[0] oldsubstring = '' for i, char in enumerate(string[1:]): if ord(char) >= ord(string[i]): substring += char else: if len(substring) > len(oldsubstring): oldsubstring = substring substring = char pri...
1a379787c65172d8edd5d9a24f47b6f9b7bce25e
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/word-count/1da3f93df4ad4c9dafc527057396bd95.py
466
3.6875
4
def word_count(input): input = input.split() words = [] count = [] for item in input: index=0 newWord=True for word in words: if item == word: count[index]+=1 newWord=False index+=1 if newWord: ...
782af31d67c20f4b3b7d03b4ad283df4baa296fb
hoklavat/beginner-python
/08_Tuple.py
344
4.125
4
#08- Tuple tuple1 = () print(type(tuple1)) tuple1 = (9) print(type(tuple1)) tuple1 = (1, 2, 3, 4, 5) print(type(tuple1)) print(tuple1[1]) #tuple1[1] = 0 Error: unmutable elements (a, b, c, d, e) = tuple1 print(a) print(len(tuple1)) print(max(tuple1)) print(min(tuple1)) print(tuple1 + (1 ,2 ,3)) print(tuple1 * 2) print...
70e5f42d8e5d2fdcab28947613853517795c2ad7
tahmid-tanzim/problem-solving
/Intervals/meeting-rooms.py
1,331
3.8125
4
#!/usr/bin/python3 # https://leetcode.com/problems/meeting-rooms/ # https://www.lintcode.com/problem/920/ from typing import List """ Description Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings. """ class Sol...
7fb413b55914552cce54e476d433158373619966
Imperial-visualizations/Legacy_server
/visuals_T/examples/plotly.js/translator_examples/anim_3d.py
1,411
3.640625
4
""" Example to create moving 3D sine and cosine spiral. """ from translator.statics import Scatter3D, Document from translator.interaction import Animate import numpy as np # Creating some pretty spirals x = [] y = [] z = [] a = [] b = [] c = [] for t in range(0, 314): x.append(list(np.linspace(-np.pi, np.pi, 50)...
310e48c031cc16c034510d47b599b09a97043056
Isterikus/neural_network_lol
/src/neural_network/test2.py
2,133
3.8125
4
from keras.models import Model, Sequential from keras.layers import Input, Dense, Activation from keras.utils import np_utils # utilities for one-hot encoding of ground truth values import numpy batch_size = 50 # in each iteration, we consider 128 training examples at once num_epochs = 20 # we iterate twenty times ove...
75e180ffc3dea615ae4fd56d16a09656df1ce1f8
dks1018/CoffeeShopCoding
/2021/Code/Python/WebSiteGrab/old/chris_learning.py
338
3.84375
4
Darius = 24 Chris = 23 while Chris <= 26: if Darius > Chris: print("Your a toddler!") elif Chris > Darius: print("Life is out of balance!") else: print("Everyone on the Earth is now on Mars") print("Darius is",Darius,"Years old!") print("Chris is",Chris,"Years old!\n") ...
17026073234b9a0c795d2eb3d71dafc24f58064a
Souzanderson/Python_codes
/CADASTRO DE CURRICULO/criabanco.py
449
3.765625
4
import sqlite3 conn = sqlite3.connect('curriculo.db') cursor=conn.cursor() cursor.execute(""" CREATE TABLE pessoa( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome TEXT NOT NULL, ec TEXT, idade TEXT, ender TEXT, city TEXT, fone TE...
13869bccdfbc0ffe34cf15fef0595917b2cdad1a
andonyan/Python-Fundamentals
/functions more exercises/tribonacci 2.py
458
4.21875
4
def tribonacci(num): first = 1 second = 1 third = 2 print('1', end=' ') if num == 2: print('1', end=' ') elif num == 3: print('1 2', end=' ') elif num > 3: print('1 2', end=' ') for i in range(3, num): current = first + second + third f...
4f0e8cfe6c4c90bb1386237fca9c13b79790e2fa
ValyNaranjo/A1_Naranjo_Valery_MetodosNumericos
/Pregunta6.py
610
3.890625
4
import math print("Programa que encuentra el sen(pi/3) y trunca en 50 \n") #Código en grados, en este caso se utilizará el 60 x_deg = float(input("Ingrese el número que desee resolver en grados ")) print("\n") #Código para cambiar el valor a radianes x = math.radians(x_deg) n = int(input("Ingrese el número en el qu...
10783a6e8a9330f6c9d9a9f3204707db62a98d51
eugenechernykh/coursera_python
/week8_null_or_not.py
671
4.03125
4
''' https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/9uqay/nol-ili-nie-nol Проверьте, есть ли среди данных N чисел нули. Формат ввода Вводится число N, а затем N чисел. Формат вывода Выведите True, если среди введенных чисел есть хотя бы один нуль, или False в противном случае. ''' print( ...
b5fbfb62253bd8f6a027476acb1d1a3cc3d4a0ba
fransikaz/PIE_ASSIGNMENTS
/homework6.py
1,653
4.25
4
''' HOMEWORK # 6: Advance Loops Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board with he same number of rows and columns as specified ''' def drawPlayBoard(row, col): if row != col: # Forcing the number...
7148f060b1d6688dd8348aec7156d2738794333f
liuluyang/openstack_mogan_study
/myweb/test/checkio/home/Non-unique-Elements-2-Elementary.py
671
3.71875
4
#coding:utf8 ''' 你将得到一个含有整数(X)的非空列表。在这个任务里, 你应该返回在此列表中的非唯一元素的列表。要做到这一点, 你需要删除所有独特的元素(这是包含在一个给定的列表只有一次的元素)。 解决这个任务时,不能改变列表的顺序。例如:[1,2,3,1,3] 1和3是非唯一元素, 结果将是 [1, 3, 1, 3]。 ''' def checkio(data): for i in set(data): if data.count(i)==1: data.remove(i) return data print checkio([1,3,2,3,5])...
1a70465ba5e8038fc659edf0f0ef92a10c60d5b4
aobo-y/leetcode
/19.remove-nth-node-from-end-of-list.py
1,434
3.59375
4
# # @lc app=leetcode id=19 lang=python3 # # [19] Remove Nth Node From End of List # # @lc code=start # 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:...
cc83801559532757ed190be62da0abb379475532
Rconte/Small-Projects-and-Courses
/Data Camp Course/Cleaning Data/27_drop_duplicates.py
840
4.1875
4
#Dropping duplicate data #Duplicate data causes a variety of problems. From the point of view of performance, they use up unnecessary amounts of memory and cause unneeded calculations to be performed when processing data. In addition, they can also bias any analysis results. #A dataset consisting of the performance...
b5aa936e7b7c8ce9ab3c979ef42ac451251ef798
anderd11/CSCI-1100
/Lab1/check1.3.py
313
3.796875
4
base10size = int(input('Disk size in GB => ')) print(base10size) base2size = int((base10size * 10**9)/(2**30)) lost_size = base10size - base2size print(base10size, "in base 10 is actually",base2size,"in base 2,",lost_size,"GB less than advertised.") print("Input: ",base10size) print("Actual: ",base2size)
cd29abaaf25b79cffdd7ba391ae5827216337409
YerardinPerlaza/holbertonschool-higher_level_programming
/0x0B-python-input_output/6-load_from_json_file.py
243
3.71875
4
#!/usr/bin/python3 """create and object from a json file""" import json def load_from_json_file(filename): """create from json""" with open(filename, encoding="utf-8") as myfile: my_obj = json.load(myfile) return my_obj
8894c8e146c2713616b46e9bf16d6fa8fc05e782
head-256/MNA
/lab6/quadratic_spline.py
1,761
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def quadratic_spline(data): np1 = len(data) n = np1 - 1 X, Y = zip(*data) X = [float(x) for x in X] Y = [float(y) for y in Y] a = [0.0] * n b = [0.0] * n c = [0.0] * n for i in range...
6920d8ab1cae282bb11740e0ce3c1802c7ba7c99
iceycc/daydayup
/python/BaseLessnon/timegeekbang.com/func_test3.py
308
3.8125
4
# a * x + b = y def a_line(a,b): def arg_y(x): return a*x+b return arg_y def a_line(a,b): return lambda x: a*x+b return arg_y # a=3 b=5 # x=10 y=? # x=20 y =? # a=5 b=10 line1 = a_line(3, 5) line2 = a_line(5,10) print (line1(10)) print (line1(20)) #def func1( a,b, x)
22c40deb27c75f1bbb0dc7c3bb947e66ba17e23c
addovej-suff/python_alg_gb
/lesson_5/task_1.py
1,919
3.859375
4
# Пользователь вводит данные о количестве предприятий, # их наименования и прибыль за 4 квартал (т.е. 4 числа) # для каждого предприятия. Программа должна определить # среднюю прибыль (за год для всех предприятий) и отдельно # вывести наименования предприятий, чья прибыль выше среднего и ниже среднего. from collection...
a91c3b2a0bbcfffb418187d8042760fab4592198
porollansantiago/um-programacion-i-2020
/57031-porollan-santiago/tp1/copia_nueva/ej14/ej14.py
1,155
3.890625
4
import re class Words(): def __init__(self): self.get_words() def get_words(self): texto = """ """ for line in open("texto"): texto += line + " " words = {} for word in re.split(" |, |\n", texto): if word not in words and len(word) > 3: ...
9b54f61bdb8e7da6163c5cdf9425540676a48164
UO250711/Classroom
/PitoneSChool/ex_len4y6.py
265
4.09375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- b=int(input("Introduce un numero: ")) num_len = len(str(abs(b))) if num_len>=4 and num_len<=6: print "Tu numero tiene entre 4 y 6 cifras" else: print "Tu numero NO tiene entre 4 y 6 cifras, tiene: " , num_len
b239ecd6ec8942eab599dc56b9b79eb41416aad0
kapitsa2811/leetcode-algos-python
/sort/SelectionSort.py
654
4
4
# Selection Sort - similar to bubble sort but only makes a single exchange per pass through # O(n^2) def SelectionSort(arr): size = len(arr) if size <= 1: return arr #Loop through arr from end to front for i in range(size-1,0,-1): # default high pos as 0 high = 0 ...
d5c8b082ed261c2e01b595bbe3eb2eb6b4366300
LinLeng/xiaoxiyouran_all
/python2/20180718零基础学习python/Python-From-Zero-to-One/unmd/课时038 类和对象 继承/review002.py
599
4.15625
4
# Summary:定义一个点(Point)类和直线(Line)类,使用getLen方法可以获得直线的长度 # Author: Fangjie Chen # Date: 2017-11-15 import math class Point: def __init__(self, x=0, y=0): self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y class Line(Point): def __init__(s...
6e6923df7c1e5b4dde2232d2f1596016da9f2caa
ienoob/python-with-algorithm
/sort/heap_sort.py
983
4.0625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- """ 堆排序, 选择排序的一种方法 """ def heap_basic_sort(data): """ :param data: List<Int> :return: """ result = [] build_heap(data) while len(data): d = data[0] result.append(d) dl = data.pop() if len(data): d...
088371a751103cf2848cc2cd5ab9ffcd7fa0f04f
epenelope/python-playground
/find-slice-string.py
214
3.859375
4
#slices the number part of the string and converts it to a float before printing the output. text = 'X-DSPAM-Confidence: 0.8475' sp = text.find('0') end = text.find('5') num = text[sp:end+1] print(float(num))
91869f710517ebc2f5db3df6977ec366b2c3eda1
rdghenrique94/Estudos_Python
/Curso_Python/Modulo1/Modulos/ex020.py
411
3.8125
4
#import random from random import shuffle def main(): n1 = str(input("Primeiro Aluno: ")) n2 = str(input("Segundo Aluno: ")) n3 = str(input("Terceiro Aluno: ")) n4 = str(input("Quarto Aluno:")) #names = ("rodrigo", "danilo", "renato", "carlos") lista = [n1, n2, n3, n4] #random.shuffle(lista...
7a1b87216d114f4a5ba979081d7760be04af08e9
alexparunov/leetcode_solutions
/src/900-1000/_922_sort-array-by-parity-ii.py
482
3.5
4
""" https://leetcode.com/problems/sort-array-by-parity-ii/ """ from typing import List class Solution: def sortArrayByParityII(self, A: List[int]) -> List[int]: N = len(A) ans = [-1] * N t = 0 for i, n in enumerate(A): if n % 2 == 0: ans[t] = n ...
4aac2bca78613a443c06f497d96e4a16b78d31d1
TheFuzzStone/hello_python_world
/chapter_6/6_10.py
694
4.15625
4
### 6-10. Favorite Numbers: Modify your program from # Exercise 6-2 (page 102) so each person can have more # than one favorite number. Then print each person’s # name along with their favorite numbers. names_and_numbers = { 'alice': [8, 22, 43, 24,], 'bob': [2, 13, 46, 77,], 'carl': [3, 11,], 'dave':...
5bf7c152d3d76667ca5345091998bd291ecef983
MiltonPlebeu/Python-curso
/Mundo 2/exercícios/desafio39_HoraDoAlistamentoMilitar.py
1,042
3.984375
4
#Faça um programa que leia o ano de nascimento de um jovem e informe, #de acordo com sua idade: # - Se ele ainda vai se alistar ao serviço militar. # - Se é a hora de se alistar # - Se já passou do tempo do alistamento. #Seu programa também deverá mostrar o tempo que falta ou que passou do prazo from datetime import d...
09b9da8cc6b45e9ec2674d6b27502edc37f1ffff
AtIasz/ccOW1
/WeekNo1/apple.py
182
4
4
how_much_a_kg=int(input("How much is a kg apple ?")) how_much_apple=int(input("How much kg would you like?")) price=how_much_a_kg*how_much_apple print ("You will pay: " +str(price))
e2efe29f655bdc9ea99ac9e01e81b6955561fc39
gschen/sctu-ds-2020
/1906101032-邹婷/test03.py
807
3.859375
4
# num = int(input("请输入一个数字:")) # if num % 2 == 0: # if num % 3 == 0: # print("这个数字既能被2也能被3整除") # else: # print("这个数字能被2整除,不能被3整除") # else: # if num % 3 == 0: # print("这个数字能被3整除,不能被2整除") # else: # print(这个数字不能被3整除,不能被2整除) # sum = 0 # a = 1 # while(a <= 100): # sum = s...
aa7158b2f5880d0951776dcdff6232c61075e214
garvsac/Matchstick-problem-AI
/driver.py
1,127
3.609375
4
#Garv Sachdeva #2015B4A70551P #Driver file import math from function2 import * from generate2 import * from GUI2 import * import turtle size=4 #% of squares randomly generated percentage = 70 #no of Squares in final state final = 6 #arr = [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1,...
8076aafbb59addbd02c8c6b79418c05f7b5d5e7d
Lucar-Yulasise/Python-Studen
/Python学习/运算符与表达式.py
1,829
4.1875
4
# 什么是表达式? # 由变量、常量和运算符组成的式子,称为表达式 # 一条语句:见到一个分号代表一条语句的结束,如果一条语句只占一行,分号可以省略。 # 如果一行上面有多条语句,每条用分号隔开。 # 一行语句 a = 100;b = 200;print(a);print(b) print(a) #运算符 # 数学运算符: #功能:进行数学运算 # + 两数相加 # - 两数相减 # * 两数相乘 # / 两数相除 # ** 求幂 # // 取证 # % 取余(取模) print(13%4) print(-13%(-4)) print(-13 % 4) # 赋值运算符 # ...
2e9fe0c371423d78eafa89bea01f4b9fa0eac038
llm123456/weiruan
/TwoStack.py
558
4
4
#双头栈 class TwoStack(): def __init__(self,arr=None): if not arr: self.arr = [] else: self.arr = arr def l_push(self,value): self.arr.insert(0,value) def l_pop(self): if len(self.arr) > 0: del self.arr[0] def r_push(self,value): self.arr.append(value) def r_pop(self): if len(self.arr) > 0: ...
da82ed136ec38909750831ace0cbbf35d81ae116
baton10/lesson_002
/Lesson_in_class_002/010_lines.py
1,248
4.15625
4
# Вывести последнюю букву в слове word = 'Архангельск' print(word[-1]) # Вывести количество букв а в слове word = 'Архангельск' print(len(word)) # Вывести количество гласных букв в слове vowels = 'аеёиоуыэюя' # предлагают решать через vowels = u'аеёиоуыэюя'. u - unicode. Преобразование строки в u word = 'Архан...
52e9776b437b99e7db698c7fe4bf0e5dd5471347
KojiNagahara/Python
/TextExercise/13-2/test.py
2,391
3.5625
4
"""動的計画法の実装をテストするモジュール。""" import random import time from item import Item from rootedBinaryTree import max_value, max_value_fast def build_items(): names = ['時計', '絵画', 'ラジオ', '花瓶', '本', 'PC'] values = [175, 90, 20, 50, 10, 200] weights = [10, 9, 4, 2, 1, 20] items = [] for i in range(len(values)): item...
bf78f6e2d06c69a2508fe63e4dd19735654e26c1
malikxomer/static
/8.Boolean Algebra/2.Logical operators.py
367
3.65625
4
#AND operator 5 and 5 #True True and True #True True and False #False johnny_homework=True throw_out_garbage=True if johnny_homework and throw_out_garbage: #Returns true print('hello') #OR operator poison = False pizza = True pizza or poison #True #NOT operator not False #True not T...
28472086d17d0b134ee9934d5af5d26d267ea7ae
roshanpiu/PythonOOP
/19_Method_Overloading.py
1,537
3.96875
4
'''Method Overloading''' #inherit : use parent class definition classmethod #overide/overload: provide child's own version of a method #extend: do work in addtion to that in parent's method #provide: implement abstract method that parent requires import abc class GetSetParent(object): '''GetSetParent''' __me...
7577e3a943e4c952e224ca348705fe280800add9
eriksylvan/PythonChallange
/10/10.py
783
3.5625
4
# http://www.pythonchallenge.com/pc/return/bull.html # a = [1, 11, 21, 1211, 111221] def nextInSequence(numstr): next = [] # print("Sekvens: ",numstr) # print(len(numstr)) pos = 0 ch = numstr[pos] count = 0 for j in numstr: if j == ch: count = count + 1 els...
3aae620ec0ca2a0e42813ec9447e0cbf6fc48a02
Dale90r/cnpython
/checkpinandbalance.py
432
3.75
4
def dispense_cash(entered_pin, requested_amount, balance): pin = 1234 balance = 300 if entered_pin == pin and requested_amount < balance: print('Pin is correct, requested amount {} balance is {}'.format(requested_amount, balance)) else: requeste...
46637a1c9fcb73b17a1be05f43f68c81c024a362
lucasayres/python-tools
/tools/sha256_file.py
397
3.78125
4
# -*- coding: utf-8 -*- import hashlib def sha256_file(file): """Calculate SHA256 Hash of a file. Args: file (str): Input file. Retruns: str: Return the SHA256 Hash of a file. """ sha256 = hashlib.sha256() with open(file, 'rb') as f: for block in iter(lambda: f.read(...
e60e3e99a1b9e5a7bcc14959bb1c957464bc2a0c
ManibalaSinha/Python
/4.7.2argument.py
597
3.9375
4
# *name: receives a tuple.(consists number of values) # when a final parameter of the form **name is present, it receives a dictionary. # *name must occur before **name def cheeseshop(name, *arguments, **keywords): print("Do you have any ", name, "?") print("I'm sorry, we're all out of", name) for arg in ar...
9ea6eb07f066bed0b90f7d193d2430b5f94bd844
Liu-Rundi-SDUWH/Applied-Time-Series-Analysis-in-Python
/作业二/pythonCode/3-Optimization.py
4,688
3.6875
4
''' Optimization with Python ''' import numpy as np import matplotlib.pylab as plt from scipy.optimize import minimize np.random.seed(1) n = 100 x = 1+7*np.random.rand(n) y = 1*np.random.randn(n) + 0.8 * x plt.plot(x,y,'o') plt.show() from scipy.optimize import minimize def myfu(args): x , y...
42291f05be5e674c88275383214f4e18ffd65ec4
joseph-leo/Python-Repositories
/Real-Python/invest.py
382
3.734375
4
def invest(amount, rate, time): print('principal amount:', '$' + str(amount)) print('annual rate of return:', str(rate)) float(amount) float(rate) for i in range(1, time + 1): amount = amount + (amount * rate) yearCount = i print('year', str(yearCount) + ':', '$...
11ae02c8c254786e81d7b85e0f8779ec53f94e64
sadOskar/courses
/lesson_10/math_funcs.py
202
3.859375
4
def sum_numbers(numbers): total = 0 for num in numbers: total += num return total def len_numbers(nums): total = 0 for num in nums: total += 1 return total
d0bd653d6f58f146af2b37be406b1a37e4613b60
aboyd20/python-exercises
/loop_vs_recursion.py
2,536
3.984375
4
def sumEvenLoop( n ): ''' return sum of even numbers from 0 to n; return 0 for n < 1 ''' total = 0 # identity for addition for i in range( 0, n+1, 2 ): total += i return total def sumEvenRecursive( n ): ''' return sum of even numbers from 0 to n; ...
d1a33cf87444dcf13122ffadc9d29173c8d387aa
smallgreycreatures/kth-programming1labs
/Lab3/lab3-3.py
1,622
3.71875
4
def is_prime(tal): # Funktionen returnerar True respektive False beroende på om "tal" är ett primtal primlist = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97) new_prime = [101] if tal == 2: return True # Sortera ut tal som är delbara ...
56bdba404879c12714710415d2cd999239ad1ae1
ralsouza/python_object_oriented_programming
/t05_dunder_methods.py
1,317
4.4375
4
class Employee: """My employee class.""" # Instance variable. raise_amt = 1.04 # This is the constructor. def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + "." + last + "@company.com" def full_name(sel...
e5c3f873b8516359b51e7f5cb688645258668ed5
villancikos/realpython-book2
/sql/insert_cars.py
298
3.609375
4
import sqlite3 with sqlite3.connect('cars.db') as connection: c = connection.cursor() cars = [('Ford', 'Malibu', 2010), ('Ford', 'Mustang' , 2015), ('Ford', 'GT', 2020), ('Honda', 'Civic', 2010), ('Honda', 'Accord', 2010)] c.executemany("INSERT INTO inventory VALUES(?,?,?)",cars)