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 |
|---|---|---|---|---|---|---|
fbbcfec4d5b94e5a30414e962b95ab506a60db77 | lelong03/python_algorithm | /array/calculate_sqrt.py | 295 | 3.640625 | 4 | def mysqrt(n):
start = 0
end = n
mid = float(end + start) / 2
while ( (mid*mid) != n ) and ( abs((mid * mid) - n) > 0.1 ):
if (mid*mid) > n:
end = mid
else:
start = mid
mid = float(end + start) / 2
return mid
print(mysqrt(3))
|
0847e2a138d297ceb53d34e5c15004424227907e | lelong03/python_algorithm | /array/next_permutation.py | 1,358 | 4.125 | 4 | # Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
# If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
# The replacement must be in-place, do not allocate extra memory.
# Here are so... |
90cc3867cb7a055bfea83ee921836bbb94ff915d | lelong03/python_algorithm | /recursion/list_sub_sets.py | 1,117 | 4.28125 | 4 | # Question: List all sub sets of one set
# Solutions:
# - with base case n = 0, there is one sub set {}
# - with n = 1, there are: {}, {a}
# - with n = 2, there are: {}, {a}, {b}, {a,b}
# - with n = 3, there are: {}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, {a,b,c}
# P(3) = P(2) + {c}
# Using Recursion
def list_sub_set(a_... |
14c124a1acc458c7a4864df345005edbbc5950af | lelong03/python_algorithm | /recursion/multiply.py | 637 | 4.03125 | 4 | # Question: multiply two positive numbers without using * operator
# Solutions: with a * b, we try to count how many squares in the rectangle grid when the length and width of grid are a and b
def multiply(a, b):
smaller = a if a < b else b
bigger = (a+b) - smaller
return multiply_helper(smaller, bigger)
... |
55efe1d1aa2f16790965b6389019c91b96066b90 | kevinpatell/Object-Oriented-Programming | /player/player.py | 1,497 | 3.609375 | 4 | class Player:
def __init__(self, gold_coins = 0, health_points = 10, lives = 5):
self.gold_coins = gold_coins
self.health_points = health_points
self.lives = lives
def __str__(self):
return (f"Your Score is\nGold treasure = {self.gold_coins}\nHealth = {self.health_points}\n... |
a064701eb3d31e6496bf0a19a05495dfba855ea3 | kapil1308/knn_classifier | /knn_classifier.py | 1,863 | 3.765625 | 4 | from sklearn.datasets import load_breast_cancer # Import the Breast Cancer Wisconsin (Diagnostic) Data Set
from sklearn.neighbors import KNeighborsClassifier # Importing the KNNClassifier algorithm to be used in the project
from sklearn.model_selection import train_test_split # Importing to divide the... |
32c49272ff07c0a0fe55537dac145d63093ff14b | canadiyaman/python-studies | /listsquare.py | 460 | 3.953125 | 4 | def square(the_list):
return [x*x for x in the_list]
def merge(x, y):
if len(x) == 0:
return y
elif len(y) == 0:
return x
elif x[-1] <= y[0]:
return [x[-1]] + merge(x[:-1], y)
else:
return [y[0]] + merge(x, y[1:])
the_list = [-8, -5, -3, -1, 4, 7, 12, 24]
half_the... |
f072351c49d70331e94af6c7557a3cf8e4423380 | kvn-lee/RecipeTransformer | /main.py | 2,176 | 3.640625 | 4 | import rparser
import recipetranslator
import copy
prompt = ("Please enter a number for how to change your recipe:"
"\n1: To vegetarian"
"\n2. From vegetarian"
"\n3: To healthy"
"\n4: From healthy"
"\n5: To Vegan"
"\n6: From Vegan"
"\n7: To Mexican"... |
429a91d928bbf33f9ddf0c5daea25a8777d65084 | anutha13/Python | /demo.py | 1,058 | 4.21875 | 4 | from time import sleep
from threading import Thread
class Hello(Thread):
def run(self):
for i in range(5):
print("hello")
sleep(1)
class Hi(Thread):
def run(self):
for i in range(5):
print("Hi")
t1=Hello()
t2=Hi()
t1.start() ... |
5a0140339b66c37c3d1f7056f8a2b8520630d39c | JasleenUT/Encryption | /ElGamal/ElGamal_Alice.py | 1,669 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 23 20:07:58 2018
@author: jasleenarora
"""
# Read the values from intermediate file
with open('intermediate.txt','r') as f:
content = f.readlines()
p = int(content[0])
g = int(content[1])
a = int(content[2])
c1 = int(content[3])
c2 = ... |
f321b8da5edff31f1c279f8cbde5e92bd78b77f1 | PranavTripathi101/AdventOfCode | /Advent of Code/Day3/day3.py | 2,073 | 3.9375 | 4 | def readData():
with open('input.txt') as f:
wire1 = f.readline().split(',')
wire2 = f.readline().split(',')
wire1[-1] = wire1[-1][:-1]
wire2[-1] = wire2[-1][:-1]
return wire1, wire2
def populatePath(wire):
start = [0,0]
stepsDict = dict()
steps = 1
for step in ... |
e79c965a46a710f49d4888c4113ea2fbbbedf9d8 | HasanKaval/Assignment_6_Python | /Prime_Numbers_2.py | 372 | 3.96875 | 4 | #Print the prime numbers which are between 1 to entered limit number (n).
n = int(input("Please enter a number : "))
numbers = list(range(1,n+1))
prime_list = []
for j in numbers :
count = 0
for i in range(1, n+1) :
if not (j % i) :
count += 1
if not((j == 0) or (j == 1) or (count >= 3... |
186a3995a21c3821bb3bfcb6598cc40f40283497 | divijwadhawan/DisasterResponsePipeline | /data/process_data.py | 3,779 | 3.8125 | 4 | import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
'''This function is used to load messages and categories files from their
filepath to dataframes'''
# load messages dataset
messages = pd.read_csv("disaster_messages.csv")
# ... |
f3057ca79beff59db0ce1a06a31d3627fe0e67ba | sagarnaikele/Python_HandsOn | /Basic/LogicalPrograms/ArmstrongOfAny.py | 633 | 4.03125 | 4 | def IsArmstrong(number):
#123 ---->
#1*1*1 + 2*2*2 + 3*3*3
cloneNumber=number
sum=0
power=findPower(cloneNumber)
while cloneNumber>0:
nextSingleDigit=int(cloneNumber%10)
tempAlloc=pow(nextSingleDigit,power)
sum=sum+tempAlloc
cloneNumber=int(cloneNumber/10)
re... |
f73ae633877ee78afdbfe8db012f451dfeb4059e | pk026/competative_pragramming | /find_missing_and_repeating.py | 348 | 3.96875 | 4 | def return_missing_and_repeating(array, size):
for i in range(size):
if array[abs(array[i])-1] > 0:
array[abs(array[i])-1] = -array[abs(array[i])-1]
else:
print "The repeating element is", abs(array[i])
for i in range(size):
if array[i] > 0:
print "and... |
2a0c0bb0c9f718791d2742a1e43bfd097c8c5196 | maiconarantes/Atividade2 | /questao2.py | 805 | 4.28125 | 4 | #_*_coding:latin1_*_
#Elaborar um programa que lê 3 valores a,b,c e verifica se eles formam
#ou não um triângulo. Supor que os valores lidos são inteiros e positivos. Caso
#os valores formem um triângulo, calcular e escrever a área deste triângulo. Se
#não formam triângulo escrever os valores lidos. (Se a > b + ... |
45760f48c550c564bcb6d242b2713c9e004490e1 | am282000/PythonTutorials | /main(0).py | 1,041 | 3.75 | 4 | #import cv2 #we can import it by cv2 name
# import math # inbuild module
print("Hello World\n")
print("5+8")
print(5+8)
# print (math.gcd(3,6))
# if(age<18):
# print("I am inside if ...")
# python main.py to runpython script in terminal
# install extension code runner for vs code
# Python is all ab... |
d96e0003f97a041987cb123654bbd02b12c62220 | ChristianChang97/Computational-Thinking | /ex1.py | 283 | 4.15625 | 4 | print("1TDS - FIAP - Primeiro Programa Python")
numero = int (input("Digite um número: "))
#campo para digitação do número
quadrado = numero*numero
#cálculo do quadrado do número
print("O quadrado do número {} é {}".format(numero, quadrado))
#impressão do resultado |
ca4309338b560bd5e438c35e18466993cff041e6 | DavidCouronne/LaTeXConvertHTML | /testregex.py | 2,850 | 4.03125 | 4 | """
Here is a simple python program showing how to use regular
expressions to write a paren-matching recursive parser.
This parser recognises items enclosed by parens, brackets,
braces and <> symbols, but is adaptable to any set of
open/close patterns. This is where the re package greatly
assists in parsing.
"""
im... |
31437cfb86cb0bdd9ce378ba6aacd44a48c1a3dd | opember44/Engineering_4_Notebook | /Python/calculator.py | 1,426 | 4.34375 | 4 | # Python Program 1 - Calculator
# Written by Olivia Pemberton
def doMath (num1, num2, operation):
# defines do math function
# program will need yo to enter 2 numbers to do operation
if operation == 1:
x = round((num1 + num2), 2)
return str(x)
if operation == 2:
x = round((num1 - num2), 2)
return str(x)
if... |
f147bf186c8219367f3824c65cbaefb0b7e0802b | PatelMohneesh/Deep-Learning-Excersise | /Excercise 1/ecbm/features/pca.py | 1,070 | 3.65625 | 4 | import time
import numpy as np
from numpy import linalg as la
def pca_naive(X, K):
"""
PCA -- naive version
Inputs:
- X: (float) A numpy array of shape (N, D) where N is the number of samples,
D is the number of features
- K: (int) indicates the number of features you are going to keep af... |
a1ce876079788f5c5a681731dc4025c87ba372a6 | jishnupramod/expert-python | /ep5_generators.py | 662 | 3.578125 | 4 | # class Generator:
# def __init__(self, n):
# self.n = n
# self.last = 0
#
# def __next__(self):
# return self.next()
#
# def next(self):
# if(self.last == self.n):
# raise StopIteration()
#
# rv = self.last ** 2
# self.last += 1
# return r... |
d2af0cb7f8c7fd64e827310cbf31216406f28efb | lmrz/py | /ex15.py | 399 | 3.953125 | 4 | #引入库
from sys import argv
#定义库
script, filename = argv
#将文件内容赋改txt对象
txt = open(filename)
#输出文件名/文件内容
print(f"Here's you file {filename}:")
print(txt.read())
#输入文件,“>" 开头
print("Type the filename again:")
file_again = input("> ")
#将输入的内容赋给txt_again
txt_again= open(file_again)
#输出内容
print(txt_again.read())
|
bb5aa2c8fc80036459a6883cd95cd153f833eba7 | MarceloSombra/Projeto_3 | /Projeto_3_Codigo_Base.py | 8,430 | 3.53125 | 4 | class Loja(object):
def __init__(self, estoque, caixa):
self.estoque = estoque
self.caixa = caixa
self.aluguelHora = 5
self.aluguelDia = 25
self.aluguelSemana = 100
self.aluguelFamilia = 0
def receberPedido(self, tipoAluguel, qtdeBike, periodo):
... |
383cc99de44752de88a43ed0385a2dd2832b2ae3 | hanamura-yuki/test | /app/test.py | 109 | 3.515625 | 4 | #!python3
from matplotlib import pyplot as plt
plt.plot(range(100), [x ** 2 for x in range(100)])
plt.show()
|
1916dfb9e0fe6e071f41364a68eade456d4310aa | walterkwon/CWK-Memento-Python | /ep018.py | 2,397 | 4.40625 | 4 | #!/usr/bin/env python3
# Wankyu Choi - Creative Works of Knowledge 2019
# https://www.youtube.com/wankyuchoi
#
#
# Episode 018 - Data Types: Tuple & Set Types
def main():
"""Entry Point"""
print("=" * 10, "Tuple", "=" * 10)
a_list = ['wankyu', 'james', 'fred', 'tom', 'harry']
a_tuple = ('wankyu', 'j... |
edcf0635ccfabf8bf6462f59199338689ec9365c | walterkwon/CWK-Memento-Python | /ep016.py | 3,712 | 4.1875 | 4 | #!/usr/bin/env python3
# Wankyu Choi - Creative Works of Knowledge 2019
# https://www.youtube.com/wankyuchoi
#
#
# Episode 016 - Data Types: List Type
from statistics import mean
def main():
"""Entry Point"""
print("=" * 10, "String Sequence vs. List", "=" * 10)
name_string = 'wankyu'
name_list = [... |
e98d3aa0513d9d63b915fd6b897bd5020059dd5f | mwdoyle-sfu/AI-TicTacToe | /aittt.py | 5,261 | 3.921875 | 4 | """
A program to play tic-tac-toe against an AI which uses pure monte-carlo-tree search (MCTS)
"""
import random
def alternate(activePlayer):
if (activePlayer == 2):
activePlayer = 1
else:
activePlayer = 2
return activePlayer
def make_move(player_move, current_player, gam... |
107f1f505647137a18f6346a240b45fa9241ff2b | otakutyrant/Data-Structures-and-Algorithms | /balance_tree.py | 794 | 3.71875 | 4 | class Tree():
def __init__(self, value, left, right):
self.value = value
self.left = left
self.right = right
def partial(list_, n):
if n == 0:
return None
else:
if (n - 1) % 2 == 1:
middle = n // 2 + 1
else:
middle = n // 2
re... |
b80126ea90b1d7a89adad6d2865a322ed0201dd5 | larsbuntemeyer/sandbox | /python/plot_example.py | 614 | 3.640625 | 4 | #!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 0, 1 # mean and standard deviation
f = np.random.normal(mu, sigma, 1000) # generate feature-vector with normal distribution
# plot the histogram - check the distribution
count, bins, ignored = plt.hist(f, 30, normed=True)
plt.plot(bins... |
37e1f2da3bfed6decb9b04f53de749fe2d403de3 | bendog/shecodes_RonakReyhani_shecodes-week-6-task-1 | /section.py | 2,391 | 3.640625 | 4 | from question import Question
class Section:
def __init__(self, sec_title, sec_description, question_list, qualifying_question):
self.sec_title = sec_title
self.sec_description = sec_description
self.qualifying_question = qualifying_question
self.question_list = question_list
... |
87c0c53f6d3d6d82f8528e0bbac329dee0038ddb | natal20-meet/meetyl1201819 | /lab7.py | 1,228 | 3.84375 | 4 | from turtle import *
import random
import turtle
import math
turtle.tracer(0)
class Ball(Turtle):
def __init__(self,radius,color,dx,dy):
Turtle.__init__(self)
self.shape("circle")
self.shapesize(radius/10)
self.radius = radius
self.dx = random.randint(-350,350)/300
self.dy = random.randint(-350,350)/300... |
41d7af3fc16aa836fdf68c2edf21cee7cd1353bd | AbhayKumar8093/pythonprogram | /even.py | 332 | 4.09375 | 4 | """ ist method.................................
n=int(input("enter the number"))
i=1
while(i<=n):
if i%2==0:
print(i)
i = i + 1
"""
# 2nd method....of sum of even number......................................
n=int(input("enter the number"))
i=2
sum=0
while(i<=n):
sum=sum+i
i = i + 2... |
1cc6489406d02438a4dc653ab44bb1b4405c48ab | AbhayKumar8093/pythonprogram | /num.py | 200 | 3.890625 | 4 | """print("hello world 7" ,end=" ")
print("abhay")"""
print("enter your number1")
num1=input()
print("enter your number2")
num2=input()
num=int(num1)+int(num2)
print("sum of two num",num) |
5450e10e71bf1590d28bdb09c6fbd21f867b655e | Sahana1269/python- | /xo.py | 834 | 3.875 | 4 | #printing the game tic-tac toe
a=["1","2","3","4","5","6","7","8","9"]
def printBoard():
print(a[0],"|",a[1],"|",a[2])
print("---------")
print(a[3],"|",a[4],"|",a[5])
print("---------")
print(a[6],"|",a[7],"|",a[8])
playerOneturn=True
while True:
printBoard()
p=input("select a place :")
if(p in a):
if(a[i... |
d95b1bfa19fa52013079f7d63f7794d1c6736d84 | hectorzaragoza/python | /functions.py | 1,985 | 4.1875 | 4 | #functions allow us to put something into it, does something to it, and gives a different output.
#We start with def to define the function, then we name it, VarName()
#def function(input1, input2, input3,...):
# code
# more code
# return value
#result = functionName(In1, In2, In3,...)
#result = value
def addO... |
a8e03319d3486f64f85634781420ee3e8e29b765 | hectorzaragoza/python | /globalVars.py | 466 | 3.859375 | 4 | #global Variables
def addOne():
global y,x #this will make the y variable a global variable
#x here is defined as a global variable so x in line 9 is able to be imported and used in this function.
y = x + 1 #y inside this function is a local variable
return y #a variable inside a function is only defin... |
872505bf037defde6b3cbd7d20a3113bd7056106 | gnavneetg/python-challenge | /ExtraContents/PyParagraph/PyParagraph.py | 1,518 | 3.546875 | 4 | import os
import string
inputfile = os.path.join("..", "resources","paragraph.txt")
with open(inputfile, 'r') as txtfile:
readfile = txtfile.read()
#sentence count using dot, question mark & exclaimation marks [ ., ? , !]
sen_count = readfile.count('.') + readfile.count('?') + readfile.count('!')
#List of wo... |
fab672eb471ab131a88a39895233624e22634bce | saintjeremy/PyBasics | /samples/polynomial.py | 2,783 | 3.953125 | 4 | #
# This module contains operations to manipulate polynomials.
#
# Need some string services, and some standard system services.
import string, sys
#
# Function to evaluate a polynomial at x. The polynomial is given
# as a list of coefficients, from the greatest to the least. It returns
# the value of the polynomia... |
c1974345ee64a2206facd6e52514fedf717c89a1 | Andreivilla/POO | /ExtrasPython/extra2/main.py | 471 | 3.90625 | 4 | from setor import Setor
from produto import Produto
def addProduto():
produto = Produto()
print("IdProduto: ")
produto.setIdProduto(input())
print("Nome: ")
produto.setNome(input())
print("Preco: ")
produto.setPreco(input())
return produto
setor = Setor()
setor.setIdSetor(input())
fo... |
1eeea1f0dbaf41d96394c048186e18f45f9593a4 | carlos398/curso_profesional_de_python | /decoradores.py | 950 | 3.578125 | 4 | from datetime import date, datetime
# def mayusculas(func):
# def envoltura(texto):
# return func(texto).upper()
# return envoltura
# @mayusculas
# def mensaje(nombre):
# return f'{nombre}, recibiste un mensaje'
# print(mensaje('cesar'))
#ejercicio decoradores:
def execution_time(func):
de... |
e6d9d55773b9ff675f22ae2a2c2642b1ab5f0102 | codyhui8/Pocket-Cube-Learning-Alg | /RunProgram.py | 3,274 | 3.734375 | 4 | '''
Cody Hui 1338250
CSE 415, Spring 2016, University of Washington
RunProgram.py
Instructor: S. Tanimoto.
Implementation of the code transparency functions.
'''
import PocketCube
def run():
NUM_SIDE = input("Please enter the size of the side. For example, 3 for a 3x3 and 2 for a 2x2. \n>>> ")
NUM_COLORS... |
50386a3dfac4a1d08f2068c22be44411c5a8aa65 | mdakram09/NPTEL_Joy_of_Computing_using_Python | /Programming_Assignment_wk-05_01_cab and walk.py | 228 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 13 09:15:35 2019
@author: Rajesh D Borate
"""
a,b1,b2=map(int,(input().split()))
cab=(2*a)/b2
walk=(1.414*a)/b1
if walk<cab:
print("Walk",end="")
else:
print("Cab",end="") |
90bee1e5f9008daec378fc3ed954ace587186c71 | mdakram09/NPTEL_Joy_of_Computing_using_Python | /Programming_Assignment_wk-11_02_String Sort.py | 171 | 3.796875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 2 09:32:24 2019
@author: Rajesh D Borate
"""
items=[x for x in input().split(',')]
items.sort()
print (','.join(items)) |
349d2ba0c89dc2d93b98c708d58d07f22017b7c6 | jiani556/Deep-Learning | /RNN_LSTM_Seq2Seq_and_Transformers/models/naive/RNN.py | 1,854 | 3.984375 | 4 | import numpy as np
import torch
import torch.nn as nn
class VanillaRNN(nn.Module):
""" An implementation of vanilla RNN using Pytorch Linear layers and activations.
You will need to complete the class init function, forward function and hidden layer initialization.
"""
def __init__(self, input_siz... |
ef58048b8b05de8a3239b61c320f601d02da1daa | manjushachava1/PythonEndeavors | /ListLessThanTen.py | 498 | 4.21875 | 4 | # Program 3
# Take a list and print out the numbers less than 5
# Extras:
# 1. Write program in one line of code
# 2. Ask the user for a number and return a list that contains elements that are smaller than that user number.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = []
c = []
# Extra 1
for element in a:
if... |
6db8f9dab648636a7d834ebf8715703b8d755ed2 | xinxin3536/leetcode | /35. Search Insert Position.py | 333 | 3.625 | 4 | class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
if not nums:
return 0
l,r = 0,len(nums)-1
while l <= r:
mid = l + ((r-l)>>1)
if nums[mid] >= target:
r = mid - 1
else :
l = mid + 1
... |
cde2aa01051fd03922314d2b7284c25a6e4b0d79 | sam-ager/BBC-Game-Of-Life | /Game of Life/Template/GameOfLifeTemplate.py | 1,798 | 3.625 | 4 | from collections import Counter
def life(world, new): #Generate new grid
for generate in range(new+1): #Add grid for each for each genration
display(world, generate) #Display the grid
counts = Counter(new for c in world for new in offset(neighbour_cells, c))
world = {c for c in counts... |
44f57b812456c89c1c6aa61efd7246581fef85c3 | jcurtis4207/Code-Examples | /Python/functions.py | 350 | 3.8125 | 4 | def main():
v1,v2 = func1()
print(v1)
print(v2)
print(func2(4,5,6))
# function that returns multiple values
def func1():
return 5,6
# function with undetermined number of parameters
def func2(*vars):
sum = 0
for i in vars:
sum = sum + i
return sum
if __name_... |
ea6472f204df2a16b7a4de80407d41d7f56d84be | JavaScriptBach/Project-Euler | /010.py | 495 | 3.765625 | 4 | """
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
"""
def prime_sieve(limit):
a = [True] * limit # Initialize the primality list
a[0] = a[1] = False
for (i, isprime) in enumerate(a):
if isprime:
for n in xrange(i*i, limit, i): ... |
7f66d0d287df330aaad8d58a3d74308a85171942 | JavaScriptBach/Project-Euler | /004.py | 518 | 4.125 | 4 | #coding=utf-8
"""
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def is_palindrome(num):
string = str(num)
for i in range(0, len(string) / 2):
if stri... |
0271687d7b9a4ea77ac4b6364d40d7dc4ab38de0 | logan-j/Practice | /examples/ProjEuler/Written.py | 1,065 | 3.640625 | 4 | #converts a number input into the written format
def written(n):
words = ['and', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen',
'eighteen', 'nineteen', 'twenty', 'thirty', 'forty... |
592e65372e0cbbbbaaaa50e61b16a4546e6301a5 | pgiardiniere/notes-WhirlwindTourOfPython | /06-scalarTypes.py | 2,782 | 4.53125 | 5 | ### Simple Types in Python ::
# --- Python Scalar Types ---
# ----------------------------------------------
# Type Example Description
# ``````````````````````````````````````````````
# int x = 1 integers
# float x = 1.0 floating point nums
# complex x = 1 + 2j complex n... |
9530462986239856552d3d3d33b9149036182869 | osiefat/210-Coursework | /week 3 q1.py | 297 | 4.0625 | 4 | def revs(a):
if a=="This is awesome": #1 # the string input
a.split() #1 # a = split each word up
sen=" ".join(a.split()[::-1]) #1 # join and split the input
print(sen) #1
else: #1
print(a) #1
revs("This is awesome") #1
# O(1) big o notation
|
8466865654ee96b5f63d22a93ce570b1cceb3832 | MonkGirl/Python | /code/chapter1/Exercise.py | 636 | 4.03125 | 4 | import math
import cmath
import turtle
from math import sqrt
print("Hello, World!")
print(2+2)
print(1 // 2) # 取整运算
print(1/2)
print(1 % 2) # 取余运算
print(10 % (-3))
print(2**3)
print(-2**3)
print(math.floor(32.9))
print(math.ceil(34.9))
print(sqrt(2))
print(sqrt(9))
print(cmath.sqrt(-9))
print((1+3j)*(9+4j))
turt... |
df42290656921417a5f441f8444c4ddba8986acb | tristandaly/practice_python | /1_character_input/character_input.py | 370 | 3.875 | 4 | import datetime
now = int(datetime.datetime.now().year)
name_input = input("Please enter your name: ")
age_input = input("Please enter your age: ")
int_age_input = int(age_input)
repeat_input = input("How many times do you want to see this?: ")
int_repeat_input = int(repeat_input)
for i in range(int_repeat_input):
... |
ae10f5bc870486417ae34e14d35aed9dd86f5d0c | npielawski/pytorch_tiramisu | /tiramisu/model.py | 4,776 | 3.59375 | 4 | """Contains a base model for deep learning models to inherit from and have additional
functionalities, such as summaries (like with Keras) and easier initialization.
"""
from __future__ import annotations
from abc import ABC
from collections.abc import Callable
import os
from typing import BinaryIO, IO, Tuple, Union
... |
206f73f8c7ef8de313e20611b6c043eb9834504b | AmmarMian/Fractals | /tests/test_nombrecomplexe.py | 3,500 | 3.5625 | 4 | import sys
sys.path.append('../src')
sys.path.append('./src')
from math import sqrt
from main import NombreComplexe
import unittest
class Test_NombreComplexe(unittest.TestCase):
def test_creation(self):
"""Teste bonne création nombre complexe
"""
z = NombreComplexe(5, 7)
assert z.... |
52da73e98a88e854302051f9a40f82b5a91886ff | luksamuk/study | /SI/2021-1/IA/TP1/src/03.py | 501 | 3.734375 | 4 | from random import randint
num_updates = 0
maximum = randint(1, 100)
print("{}".format(maximum))
for i in range(99):
new_num = randint(1, 100)
if new_num > maximum:
maximum = new_num
num_updates += 1
print("{} (atualizado)".format(new_num))
else:
print("{}".format(new_num))... |
6515f84fcf366664a70057fc2f6d0af667638ca5 | kanoga/prime_numbers | /test_int.py | 359 | 3.609375 | 4 | import unittest
from prime_number import isPrime
class PrimeTests(unittest.TestCase):
def test_input_must_be_a_number(self):
self.assertEqual(isPrime(1),"The input must be a number only")
def test_number_is_int(self):
self.assertIsInstance(isPrime(int), "The input must be an integer")
if __name... |
bb9e2f57068039cdda03127369bbe8ad8ac535c4 | gain620/algorithms-in-python | /recursion/cal_sum_of_list.py | 488 | 4 | 4 | # conventional way
def listSum(numList):
theSum = 0
for i in numList:
theSum += i
return theSum
# calculating the sum of list using a recursive function
def listSumRecursion(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listSumRecursion(numLi... |
4eba6152ec0c08020df760bc04cf854ef5927961 | nathan-miller23/Backtesting_demo | /backtesting_demo/strategies/volume_weighted_moving_average.py | 1,281 | 3.609375 | 4 | from strategies.abstract_strategy import Abstract_strategy
class Volume_weighted_moving_average(Abstract_strategy):
NAME = 'Volume Weighted moving average'
def __init__(self, data, ticker, days):
# Call parent class constructor to set instance variables
super().__init__(data, ticker, days)
def appl... |
eeafa473d689cc64731695f30c912d605d46f244 | mfrisby/DrQuine | /bonus/Colleen.py | 814 | 3.546875 | 4 | '''
Comment
'''
def tutu():
return
def main():
bn = chr(10)
bc = chr(39)
tutu()
'''
myComment
'''
s = '%c%c%c%c Comment%c%c%c%c%cdef tutu():%c return%cdef main():%c bn = chr(10)%c bc = chr(39)%c tutu()%c'
s1 = ' %c%c%c%c myComment%c %c%c%c%c s =... |
f88885ed6864d33c7a7b21f983a63371e6973e49 | AsadR2002/Life-Simulator | /Life Simulator Game.py | 81,881 | 3.65625 | 4 | '''
Asad Rehman
'''
import easygui as a #this program uses easygui, setting as a makes it more convenient
def start(): #set game inside function to allow game to be eaisly restarted at the end
age = 0 #age counter
beg = ["Play", "Quit"]
beg1 = a.buttonbox("Welcome to Life Simulator. This... |
033b6f57df286452a6651896a410d54d3cd45021 | AniketPant02/voronoi-generation | /voronois.py | 2,800 | 3.53125 | 4 | from PIL import Image
import random
import math
import seaborn as sns
from PIL import ImageColor
from tqdm import tqdm
def generate_voronoi_diagram(width, height, num_cells, mean_x, stdv_x, mean_y, stdv_y,
colorMap1, colorMap2):
"""Creates Voronio diagram and saves it. Each site is ra... |
215ebe04fbe172062407fe9a69c2c22653c21520 | pastra98/2d_evolution_sim | /pygame_pymunk_ver/genes.py | 1,520 | 3.890625 | 4 | from translators import Translator
# Holds DNA and performs all relevant actions
class Genome:
"""class that holds the dna with all it's genes. Also contains
a Transcriptor object that is required for expressing gene
functions.
"""
def __init__(self):
"""initializes dna and transcriptor us... |
6adcd05dc22f8c201be79f4e9f4caa26bcf2b7cc | scott-p-lane/Advent-of-Code-2019 | /aoc_helpers/GridCoordinates.py | 5,824 | 3.9375 | 4 | '''
Created on Feb 8, 2020
@author: scott-p-lane
'''
from enum import Enum
class GridOrientation(Enum):
left = 0
up = 1
right = 2
down = 3
class TurnDirection(Enum):
left = 0
right = 1
class GridCoordinates (object):
"""
Dictionary based implementation that represents grid coordinate... |
6b43604d2d995874639262c7995a22dde3bd5b41 | eshulok/2.-Variables | /main.py | 604 | 4.53125 | 5 | #Variables are like nicknames for values
#You can assign a value to a variable
temperature = 75
#And then use the variable name in your code
print(temperature)
#You can change the value of the variable
temperature = 100
print(temperature)
#You can use variables for operations
temp_today = 85
temp_yesterday = 79
#How... |
153ae3409ccd310cc3e426144aa7b47c22530615 | sdcityrobotics/zoidberg_software | /OpenCV/practice/min_enclosingCircle/encloseCircle.py | 805 | 3.515625 | 4 | import numpy as np
import cv2
# not finding center accurately in 3D-images
img = cv2.imread('2d-circle.png', 0)
og = cv2.imread('2d-circle.png', 0)
cv2.imshow('original', og)
# use threshold, findContours and moment functions
ret, thresh = cv2.threshold(img, 127, 255, 0)
im2, contours, hierarchy = cv2.findContours(t... |
37499520285d5a5b5b8746d02a4fc06854627f13 | riyaasenthilkumar/riya19 | /factorial.py | 270 | 4.125 | 4 | num=7
num=int(input("Enter a number:"))
factorial=1
if num<0:
print("factorial does not exist for negative number")
elif num==0:
print("the factorial of0 is 1")
else:
for i in range (1,num+1):
factorial=factorial*i
print("the factorial of",num,"is",factorial)
|
972c5a7959d352a50d54e049b5d847610a62beab | pamsalesr/trybe-exercises | /EXERCISES/CS/BLOCO_33/DIA_1/fixacao.py | 4,099 | 4.09375 | 4 | import statistics
# Exercicio 1 - Crie uma função que receba dois números e retorne o maior deles
def biggest_number(a, b):
if b > a:
return b
return a
# Exercicio 2 - Calcule a média aritmética dos valores contidos em uma lista.
def list_average(list):
return statistics.mean(list)
# Outra ma... |
1b871489089ef44c5e684c1227e9698a276f0d06 | PhilippeCarphin/env-tools | /libexec/env-tools/envtool.py | 6,095 | 4.0625 | 4 | #!/usr/bin/env python3
'''
This class takes the environment and represents it in a way that can be
specified by the user. If no specification is given, the representation
will be equivalent to the os.environ dictionary.
The user
'''
import os
import sys
import json
import subprocess
from pprint import pprint
def ... |
79ee4de72e1b5b309fba075c3256a246519730d5 | sshantel/running | /pace_converter.py | 1,168 | 3.71875 | 4 | import re
import math
def km_to_mi(km):
miles = km / 1.609
return miles
def time_to_seconds(run_time):
components = run_time.split(":")
hours = int(components[0])
minutes = int(components[1])
seconds = int(components[2])
total_s = seconds + (minutes*60) + (hours*3600)
return total_s
... |
021a7b285b13f08e7f68188fd414d75681a5458b | triplingual/mypythonthehardway | /ex33_mod1.py | 736 | 3.953125 | 4 | import random
def looper( param0, param1 ):
"""Loops"""
i = 0
numbers = []
while i < param0:
if ( i < ( 2 * param1 ) ):
print "At the top i is %d" % i
numbers.append( i )
i = i + param1
if ( i < ( 2 * param1 + 1 ) ):
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
return numbers
... |
96888266eb13cc5801d717298e39dfc24d0eb0c1 | Amritha-Venkat/Exercises | /majority.py | 293 | 3.703125 | 4 | def majority(nums):
freq = {}
for item in nums:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
# print(freq)
inverse = [(value, key) for key, value in freq.items()]
return max(inverse)[1]
print(majority([3,2,3]))
|
8eb394b7719ee9f31c69697e82283ab1e643d7c2 | Amritha-Venkat/Exercises | /donuts.py | 224 | 3.59375 | 4 | def donuts(count):
# +++your code here+++
if count > 10:
return "Number of donuts: many"
else:
return "Number of donuts: ", count
if __name__=='__main__':
print (donuts(5))
print (donuts(23)) |
bb11827268e6075e102b96fc62c012da067538d8 | Amritha-Venkat/Exercises | /PalindromeLeetCode.py | 745 | 3.84375 | 4 | # def isPalindrome(x):
# """
# :type x: int
# :rtype: bool
# """
# y = str(x)
# rev = ""
# for i in y:
# rev = i + rev
# if rev == str(x):
# return True
# else:
# return False
# print(isPalindrome(-121))
def isPalindromesigned(x):
ans = ""... |
72be40266fe7adf123de0b20fbbed9bb66dab7f1 | Amritha-Venkat/Exercises | /TwoSum.py | 1,003 | 3.5625 | 4 | # indexes = []
# def twoSum(nums, target,partial = []):
# """
# :type nums: List[int]
# :type target: int
# :rtype: List[int]
# """
#
# total = 0
# for i in range(len(partial)):
# total = total + partial[i]
# # total = sum(partial)
# if total == target:
# ... |
d4db08e217687102d113da64f1ec64ae201b810a | YoungLeeNENU/Online-Judge | /leetcode/algorithms/easy/other-1.py | 332 | 3.546875 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
bin_str = bin(n)[2:]
return len(''.join(bin_str.split('0')))
if __name__ == '__main__':
solution = Solution()
print solution.hammin... |
c00908936aa61fb0d76ec4677a2eb0f57d497c99 | YoungLeeNENU/Online-Judge | /leetcode/algorithms/easy/math-1.py | 565 | 3.734375 | 4 | # -*- coding: utf-8 -*-
#!/usr/bin/python
class Solution(object):
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
for i, x in enumerate(n * "1"):
fizzBuzz = ""
if (i + 1) % 3 == 0: fizzBuzz += "Fizz"
if (i... |
152ff555d31467febe3612547edf0518408f1b5d | oun1982/gitrepo | /test2.py | 1,109 | 3.53125 | 4 | __author__ = 'oun1982'
'''
import time
start_time = time.time()
number = int(input("enter your number : "))
for i in range(1,1000001):
print("%d * %d = %d" %(number,i,(number * i)))
print("---%s seconds ---"%(time.time() - start_time))
tup1 = (12,13,14,15.6)
tup2 = ('Asterisk','linux',1982)
print (tup1)
print (tup... |
cb2aee32edfaf7cc00c8d4fa18ff4f6b6684d16f | oun1982/gitrepo | /TryExcept.py | 646 | 3.953125 | 4 | __author__ = 'oun1982'
'''
try:
fh = open("myfile", "w")
fh.write("This is my file exception handling!!!")
except IOError:
print("Error : Can\'t find file ore read data")
else:
print("Write content in the file successfully")
fh.close()
while True:
try:
n = int(input("Please enter an int... |
1ca788b5d83a3da61df5ec82a13dc7b6c187b177 | JH-Lam/deep-learning-gluon | /1.gradient_decend.py | 712 | 3.515625 | 4 | import numpy as np
import matplotlib.pyplot as plt
x = np.random.random((100, 2))
init_w = np.array([[1.4], [0.9]])
init_b = 0.2
y = np.dot(x, init_w) + init_b # y = wx + b
w = np.random.randn(2, 1)
b = 0
# loss = ((wx + b) - y) ** 2
# d(loss)/dw = 2(wx + b - y) * x
# d(loss)/db = 2(wx + b - y)
... |
ccf67c2b2625e3ae6d1acc1e7cca475f8b3e5f67 | Xtreme-89/Python-projects | /main.py | 1,424 | 4.1875 | 4 | <<<<<<< HEAD
is_male = True
is_tall = False
if is_male and is_tall:
print("You are a tall male")
elif is_male and not is_tall:
print("You are a short male")
elif not is_male and is_tall:
print("You are a tall female")
else:
print("You are a short female")
#comparisons
def max_num(num1, num2, num3):
... |
3f372fc00793c1f2134c4fd0d50ff1a8e38aaf3a | senmelda/PG1926 | /problemSet_1.py | 390 | 3.9375 | 4 | def fizzbuzz(n) :
result = []
for x in range(1,n+1):
if x % 3 == 0 and x % 5 == 0 :
result.append("fizz buzz")
elif x % 3 == 0 :
result.append("fizz")
elif x % 5 == 0 :
result.append("buzz")
else :
result.append(str(x))
retur... |
d7f3433ac5bda1d9eaae98463d9154741a02ef86 | OlegFedotkin/python | /task6.py | 1,159 | 3.796875 | 4 | #6) Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров.
# Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего.
# Требуется определить номер дня, на который результат спортсмена составит не менее b километров.
# Программа должна принимать значения парам... |
909eb38479db65819a09f19f15a7053e3ad5450e | derrick20/AI-Projects | /1-Searches/BFS, DFS, DLS/word_ladder_bfs_liang_d.py | 3,160 | 3.9375 | 4 | import collections
def main():
try:
file = open('words.txt', 'r')
words = set([line.strip() for line in file])
graph = {}
for word in words:
graph[word] = Node(word)
for adjacent in generate_adj(word):
if adjace... |
214ea4ae4b8cc40769a224af589a5b077edbe490 | derrick20/AI-Projects | /0-Python Tasks/eleven_liang_d.py | 170 | 3.546875 | 4 | def eleven():
a,b = [int(x) for x in input().split()]
list = []
for i in range(a, b + 1):
list.append(i**2 - 3*i + 2)
print(list)
eleven()
exit() |
c02b328003add7fe7ac4c0b9c0719a58b4c1f0a4 | derrick20/AI-Projects | /0-Python Tasks/three_liang_d.py | 153 | 3.84375 | 4 | def three():
str = input()
ret = ''
for i in range(len(str)):
if i % 2 == 0:
ret += str[i]
print(ret)
three()
exit() |
742f27d0c4a7d0542829a6f58942a5a6b611302c | derrick20/AI-Projects | /0-Python Tasks/two_liang_d.py | 220 | 3.8125 | 4 | def two():
n = int(input())
fib = []
fib.append(1)
for i in range(1, n):
if i <= 3:
fib.append(i)
else:
fib.append(fib[i-1] + fib[i-2])
print(fib)
two()
exit() |
026da2eb5046eedf726f209933d258b6dc74d293 | derrick20/AI-Projects | /0-Python Tasks/twenty_liang_d.py | 316 | 3.6875 | 4 | def twenty():
str = input()
ret = True
for c in str:
if c not in '01':
ret = False
print(int(str, 2))
'''value = 0
current = 0
if ret:
for c in str[::-1]:
value += (2**current) * int(c)
current += 1''' # unnecessary way
twenty()
exit() |
b387c6daa15dc9ad3c696b2ff2bbe115c03472f6 | webclinic017/TFS | /tfs/utils/charts.py | 6,699 | 3.59375 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import FuncFormatter
import pdb
class Chart(object):
pass
class BulletGraph(Chart):
"""Charts a bullet graph.
For examples see: http://pbpython.com/bullet-graph.html
"""
def draw_graph(self, data=None, labels=None, ax... |
b2624f634c7f35d888bc6bca0f7638fe34c74e90 | vishalsodani/aoc2019 | /day1/part2.py | 245 | 3.640625 | 4 | total = 0
with open('input.txt') as fp:
for input in fp:
total += (int(input) / 3) - 2
next_input = (int(input) / 3) - 2
while next_input > 0:
next_input = (next_input / 3) - 2
if next_input > 0:
total += next_input
print(total) |
da5b4d85ab8ca08a4d0b4a38a3afcb80159d42b9 | segunfamisa/algorithms | /hackerrank/warmup/compare_the_triplets.py | 384 | 3.796875 | 4 | '''
Compare the triplets
https://www.hackerrank.com/challenges/compare-the-triplets
'''
def Solution():
A = map(int, raw_input().split())
B = map(int, raw_input().split())
scoreA = 0
scoreB = 0
for i in range(len(A)):
if A[i] > B[i]:
scoreA += 1
elif A[i] < B[i... |
746a785edf8a8d9c205e389fd02ab93ac1b237a4 | sobriquette/python-gmaps-tsp | /TSP/PrimMST.py | 2,917 | 3.6875 | 4 | from TSP.Vertex import Vertex
from TSP.Graph import Graph
def print_mst(parent, graph, places):
"""
Prints the constructed MST along with labels of our destinations
"""
num_vertices = graph.num_vertices
adj_matrix = graph.adjacency_matrix
print("Edge \tWeight \tPlace")
for i in range(1, num_vertices):
print( ... |
4675dd3b798295d4a5ab3d1a0a8d6021cc7a169c | zacharytower/continued_fraction | /root_period.py | 929 | 3.890625 | 4 | import math
def root_period(n, b = 0, d = 1, original = 0, counter = 0, period_list = []):
'''
Returns the period of sqrt(n). -- in the form [a0, a1, a2, ... an]
i.e. root_period(7) = [2,1,1,1,4], as
sqrt(7) = [2;(1,1,1,4)]
b is what is added to n, and d is the denominator for both n and b.
This recursive f... |
1c552223e3c23ccbbb496e402b7d49ab11f63650 | hailinlwang/Sorting-Algorithms | /complex.py | 1,214 | 4.09375 | 4 | class complex:
def __init__(self,real,imag):
#__init__ is special and must be spelled this way
#it allows us to say "x=complex(0,1)" to create a complex number
self.re=real
self.im=imag
# note: no return value (rare exception to our rule!)
def setRe(self,X):
self.re=x
re... |
afd7d15a6a033f8dfd23391391e0eca08be65ec6 | HanqingXue/Leetcode | /samsung/stack.py | 532 | 3.875 | 4 | class Stack(object):
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
def pop(self):
if self.stack == []:
raise IndexError('pop from empty stack')
else:
del self.stack[-1]
def top(self):
retur... |
3b6c35f55899dbc8819e048fdbdebb065cd01db1 | brunomatt/ProjectEulerNum4 | /ProjectEulerNum4.py | 734 | 4.28125 | 4 | #A palindromic number reads the same both ways.
#The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#Find the largest palindrome made from the product of two 3-digit numbers.
products = []
palindromes = []
three_digit_nums = range(100,1000)
for k in three_digit_nums:
for j in t... |
dc0890ecd390a3379156a55201832cb81ad0c1e2 | AlexDikelsky/cellular-automata | /langton_ant/__main__.py | 1,010 | 3.75 | 4 | import ant
import grid
import time
size = int(input("How large a grid do you want? : "))
print("Do you want to step through the positions, or just see a specific position?")
step_through = int(input("Type 1 to step, or 0 to jump to a point: "))
if step_through == 0:
steps = int(input("How many steps? : "))
i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.